#!/usr/bin/env python3
"""Comprehensive DeepSeek-V4.1-Flash Benchmark Suite on isolated port 18199.

Measures:
  1. Prose, Thinking, and Tool token decode across:
     - Context lengths: 5K, 50K, 150K, 250K, 500K, 750K tokens (exact tokenizer-calibrated)
     - Concurrencies:   1, 2, 4, 8, 12, 16, 24, 32
     - Both metrics per cell:
         * Raw token decode tok/s (NOT factoring in prefill time; server-side generation_duration)
         * Effective token decode tok/s WITH prefill/TTFT factored in (per-slot & batch wall-span)
  2. Cold prefill of 1,000,000 tokens at concurrency=1 (guaranteed cached_tokens==0)
     to measure average cold prefill tokens/sec.
"""
from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import re
import statistics
import subprocess
import sys
import time
import urllib.request
from pathlib import Path
from typing import Any

MODEL_ID = "DeepSeek-V4.1-Flash-1017-Abliterated-MLX"
MODEL_DIR = "<HOME>/models/apetersson/DeepSeek-V4.1-Flash-1017-Abliterated-MLX"

CONTEXTS = [
    ("5K", 5_000),
    ("50K", 50_000),
    ("150K", 150_000),
    ("250K", 250_000),
    ("500K", 500_000),
    ("750K", 750_000),
]
CONCURRENCIES = [1, 2, 4, 8, 12, 16, 24, 32]
MODES = ["prose", "thinking", "tool"]

TOOLS_SCHEMA = [
    {
        "type": "function",
        "function": {
            "name": "create_remediation_plan",
            "description": "Create a structured multi-step engineering remediation plan for a distributed system incident.",
            "parameters": {
                "type": "object",
                "properties": {
                    "incident_id": {"type": "string", "description": "Unique incident identifier"},
                    "severity": {"type": "string", "enum": ["SEV1", "SEV2", "SEV3"]},
                    "affected_subsystems": {
                        "type": "array",
                        "items": {"type": "string"},
                        "description": "List of impacted services and storage tiers",
                    },
                    "root_cause_analysis": {"type": "string", "description": "Detailed technical root cause summary"},
                    "remediation_steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "step_order": {"type": "integer"},
                                "component": {"type": "string"},
                                "action": {"type": "string"},
                                "validation_command": {"type": "string"},
                                "rollback_action": {"type": "string"},
                            },
                            "required": ["step_order", "component", "action", "validation_command", "rollback_action"],
                        },
                    },
                    "slo_verification_metrics": {
                        "type": "array",
                        "items": {"type": "string"},
                    },
                },
                "required": [
                    "incident_id",
                    "severity",
                    "affected_subsystems",
                    "root_cause_analysis",
                    "remediation_steps",
                    "slo_verification_metrics",
                ],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "apply_config_patch",
            "description": "Apply a validated configuration patch to cluster telemetry, scheduler, or cache parameters.",
            "parameters": {
                "type": "object",
                "properties": {
                    "service_name": {"type": "string"},
                    "environment": {"type": "string", "enum": ["staging", "canary", "production"]},
                    "parameters": {
                        "type": "object",
                        "additionalProperties": True,
                        "description": "Key-value configuration overrides",
                    },
                    "canary_percentage": {"type": "integer"},
                    "justification": {"type": "string"},
                },
                "required": ["service_name", "environment", "parameters", "canary_percentage", "justification"],
            },
        },
    },
]

PROSE_PROMPTS = [
    "Write a thorough, continuous multi-paragraph architectural analysis of the replication and cache-coherence mechanics described in the reference specification, explaining failure modes and mitigation trade-offs in plain technical prose without bullet lists or code blocks.",
    "Explain in detailed, flowing technical prose how tail-latency amplification arises across the storage, networking, and scheduler layers described above, and discuss how backpressure and admission control stabilize p99 latency.",
    "Provide an in-depth narrative review of the memory hierarchy, NUMA placement, and page-cache eviction behavior documented in the system records, focusing on bandwidth saturation and cache-line contention.",
    "Write a comprehensive prose postmortem synthesis comparing the throughput bottlenecks, queue-depth oscillations, and recovery dynamics observed across the telemetry chapters in the reference archive.",
    "Discuss in sustained technical prose the durability versus latency trade-offs of write-ahead logging, group commit batching, and asynchronous checkpointing as presented in the engineering notes.",
    "Describe in rich, continuous prose how consensus heartbeats, lease renewals, and split-brain fencing interact under asymmetric network partitions according to the documented cluster design.",
    "Write an extensive prose explanation of how dynamic load balancing, consistent hashing, and hot-key mitigation prevent cascading overload across stateless and stateful service tiers.",
    "Analyze in continuous technical prose the operational risks of rolling upgrades, schema migrations, and version skew across heterogeneous hardware fleets as outlined in the reference corpus.",
]

THINKING_PROMPTS = [
    "Carefully reason step by step through the trade-offs between strict serializability and bounded-staleness reads under a 3-region failover scenario described in the specification, deriving exact latency and availability bounds before giving your conclusion.",
    "Work through a deep first-principles bottleneck analysis of why p99.9 latency spikes by 4x when write-ahead log flush concurrency exceeds 16 on the documented storage tier, checking queuing theory, lock contention, and write amplification.",
    "Reason carefully through every edge case of migrating live traffic from a single-leader ring to a multi-raft sharded topology without dropping in-flight idempotent writes, verifying invariants at each transition step.",
    "Analyze step by step how an intermittent 1.5% packet loss on the east-west fabric interacts with TCP congestion control, RPC retries, and circuit-breaker thresholds to trigger metastable overload.",
    "Derive from first principles the optimal cache partitioning strategy between hot metadata blocks and sequential scan buffers given the workload skew and memory ceiling documented in the telemetry archive.",
    "Think through how clock skew of 45ms across nodes affects snapshot isolation, MVCC garbage collection watermarks, and distributed deadlock detection in the documented database engine.",
    "Reason step by step about the failure modes of dual-write migration versus change-data-capture backfill when splitting a 40TB monolithic table into 64 range partitions under live load.",
    "Perform a detailed quantitative capacity and headroom analysis for doubling peak request concurrency while maintaining sub-100ms p95 latency and zero swap activity under the documented cluster constraints.",
]

TOOL_PROMPTS = [
    "Based on the reference architecture and incident telemetry above, immediately call apply_config_patch for kv-cache-coordinator in canary (canary_percentage=15) with 6 specific tuning parameters in parameters and a detailed 3-sentence technical justification citing the telemetry thresholds. Output only the tool call.",
    "Using the documented system telemetry, immediately invoke apply_config_patch for scheduler-gateway in staging (canary_percentage=25) with 6 concrete queue/batching parameters in parameters and a detailed 3-sentence technical justification. Output only the tool call.",
    "From the engineering archive above, immediately call apply_config_patch for metadata-quorum in canary (canary_percentage=10) with 6 concrete raft/lease parameters in parameters and a thorough 3-sentence justification. Output only the tool call.",
    "Referring to the cluster records above, immediately invoke apply_config_patch for ingress-proxy in production (canary_percentage=5) with 6 concrete connection-pool/timeout parameters in parameters and a detailed 3-sentence justification. Output only the tool call.",
    "Based on the specification above, immediately call apply_config_patch for shard-balancer in canary (canary_percentage=20) with 6 concrete rebalance/throttle parameters in parameters and a detailed 3-sentence justification. Output only the tool call.",
    "Using the documented failure patterns, immediately invoke apply_config_patch for raft-transport in staging (canary_percentage=50) with 6 concrete transport/retry parameters in parameters and a detailed 3-sentence justification. Output only the tool call.",
    "From the reference notes above, immediately call apply_config_patch for buffer-pool-mgr in canary (canary_percentage=10) with 6 concrete eviction/dirty-ratio parameters in parameters and a detailed 3-sentence justification. Output only the tool call.",
    "Based on the system archive above, immediately invoke apply_config_patch for admission-controller in canary (canary_percentage=15) with 6 concrete rate-limit/burst parameters in parameters and a detailed 3-sentence justification. Output only the tool call.",
]


def load_auth_headers() -> dict[str, str]:
    headers = {"Content-Type": "application/json"}
    cfg = Path.home() / ".omlx" / "settings.json"
    if cfg.exists():
        try:
            data = json.loads(cfg.read_text())
            tok = (data.get("auth") or {}).get("api_key") or data.get("api_key") or ""
            if isinstance(tok, str) and tok.strip():
                headers["Authorization"] = f"Bearer {tok.strip()}"
        except Exception:
            pass
    return headers


AUTH_HEADERS = load_auth_headers()


def get_mem() -> dict[str, float]:
    out = subprocess.check_output(["vm_stat"], text=True)
    pg = int(re.search(r"page size of (\d+) bytes", out).group(1))
    wd = int(re.search(r"Pages wired down:\s+(\d+)\.", out).group(1))
    sw = subprocess.check_output(["sysctl", "vm.swapusage"], text=True)
    m = re.search(r"used = ([0-9.]+)M", sw)
    return {"wired_gib": round(wd * pg / 1024**3, 2), "swap_mb": float(m.group(1)) if m else -1.0}


def build_realistic_corpus(tokenizer, target_tokens: int, seed_tag: str) -> str:
    """Build a realistic, varied engineering architecture & telemetry corpus of exact target_tokens."""
    subsystems = [
        "storage-router", "kv-cache-coordinator", "wal-compactor", "scheduler-gateway",
        "metadata-quorum", "snapshot-mover", "ingress-proxy", "lease-manager",
        "shard-balancer", "rpc-dispatcher", "checkpoint-writer", "raft-transport",
        "query-planner", "buffer-pool-mgr", "admission-controller", "gc-coordinator",
    ]
    regions = ["us-east-nh1", "us-south-fl2", "eu-central-1", "ap-northeast-1"]
    topics = [
        "Write-ahead log group-commit latency rose during concurrent checkpoint flushes when dirty page ratios crossed 38 percent.",
        "Sliding-window KV cache compression maintained recall above 99.4 percent while bounding per-slot footprint under 2.4 kilobytes per token.",
        "Consistent hash ring rebalancing throttled background partition moves to 180 megabytes per second to preserve foreground p99 latency.",
        "Asymmetric packet drops on fabric spine switches triggered aggressive TCP backoff and duplicated speculative RPC retries.",
        "NUMA-aware thread pinning reduced cross-socket cache-line bouncing on shared ring buffer head and tail indices by 41 percent.",
        "Lease renewal jitter under heavy garbage-collection pauses caused transient follower read rejections before fencing timers expired.",
        "Hierarchical token-bucket admission control shed low-priority batch backfill traffic whenever queue wait exceeded 22 milliseconds.",
        "Zero-copy page-cache slicing eliminated redundant host-to-device staging copies across concurrent multi-tenant prefill batches.",
    ]

    # Measure tokens per 100 chapters to overshoot slightly, then binary-search exact token count
    def make_chapters(n_ch: int) -> str:
        parts = [f"# Systems Engineering Reference Archive ({seed_tag})\n\n"]
        for i in range(n_ch):
            sub = subsystems[i % len(subsystems)]
            reg = regions[(i * 3) % len(regions)]
            top = topics[(i * 5 + (i // 7)) % len(topics)]
            p50 = 4.2 + (i % 19) * 0.37
            p99 = 18.5 + (i % 31) * 1.42
            qps = 1200 + ((i * 97) % 8400)
            err = (i % 13) * 0.002
            parts.append(
                f"## Chapter {i:05d} [{seed_tag}] — {sub} ({reg})\n"
                f"Telemetry window W-{i:05d}: throughput={qps} req/s, p50={p50:.2f}ms, p99={p99:.2f}ms, "
                f"error_rate={err:.3f}%, queue_depth={1 + (i % 64)}, active_shards={8 + (i % 56)}.\n"
                f"Observation: {top} Operator note #{i}: verify lock ordering between epoch counter "
                f"0x{(i * 2654435761) & 0xFFFF:04x} and ring cursor {(i * 131) % 4096}, confirm CRC32C "
                f"checksums on segment {(i * 17) % 9999:04d}, and monitor DRAM bandwidth headroom.\n\n"
            )
        return "".join(parts)

    sample = make_chapters(64)
    toks_per_ch = len(tokenizer.encode(sample, add_special_tokens=False)) / 64.0
    est_ch = max(4, int(target_tokens / toks_per_ch) + 12)
    text = make_chapters(est_ch)
    ids = tokenizer.encode(text, add_special_tokens=False)
    while len(ids) < target_tokens:
        est_ch = int(est_ch * 1.15) + 16
        text = make_chapters(est_ch)
        ids = tokenizer.encode(text, add_special_tokens=False)
    # Exact token slice + decode back
    exact_ids = ids[:target_tokens]
    return tokenizer.decode(exact_ids, skip_special_tokens=True)


def stream_request(
    base_url: str,
    messages: list[dict[str, Any]],
    *,
    mode: str,
    max_tokens: int,
    temperature: float,
    seed: int,
    timeout: int = 1800,
) -> dict[str, Any]:
    payload: dict[str, Any] = {
        "model": MODEL_ID,
        "messages": messages,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stream": True,
        "stream_options": {"include_usage": True},
        "seed": seed,
    }
    if temperature > 0.0:
        payload["top_p"] = 0.95
        payload["top_k"] = 20
    if mode == "prose":
        payload["chat_template_kwargs"] = {"enable_thinking": False}
    elif mode == "thinking":
        payload["chat_template_kwargs"] = {"enable_thinking": True}
    elif mode == "tool":
        payload["chat_template_kwargs"] = {"enable_thinking": False}
        payload["tools"] = TOOLS_SCHEMA
        payload["tool_choice"] = "required"
    else:
        raise ValueError(f"Unknown mode: {mode}")

    body = json.dumps(payload).encode("utf-8")
    req = urllib.request.Request(
        f"{base_url}/v1/chat/completions",
        data=body,
        headers=AUTH_HEADERS,
    )
    t_start = time.perf_counter()
    t_first: float | None = None
    content_parts: list[str] = []
    reasoning_parts: list[str] = []
    tool_chunks: list[Any] = []
    usage: dict[str, Any] = {}
    finish_reason = None
    chunk_count = 0

    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            for raw_line in resp:
                line = raw_line.decode("utf-8", errors="replace").strip()
                if not line or not line.startswith("data:"):
                    continue
                data_str = line[5:].strip()
                if data_str == "[DONE]":
                    break
                obj = json.loads(data_str)
                if obj.get("usage"):
                    usage = obj["usage"]
                choices = obj.get("choices") or []
                if choices:
                    fr = choices[0].get("finish_reason")
                    if fr:
                        finish_reason = fr
                    delta = choices[0].get("delta") or {}
                    c_s = delta.get("content") or ""
                    r_s = delta.get("reasoning_content") or ""
                    tc = delta.get("tool_calls") or []
                    if c_s or r_s or tc:
                        if t_first is None:
                            t_first = time.perf_counter()
                        if c_s:
                            content_parts.append(c_s)
                        if r_s:
                            reasoning_parts.append(r_s)
                        if tc:
                            tool_chunks.extend(tc)
                        chunk_count += 1
        t_end = time.perf_counter()
        total_s = max(1e-4, t_end - t_start)
        client_ttft_s = (t_first - t_start) if t_first is not None else total_s
        client_decode_s = max(1e-4, t_end - (t_first or t_start))

        prompt_tokens = int(usage.get("prompt_tokens") or 0)
        comp_tokens = int(usage.get("completion_tokens") or chunk_count)
        cached_tokens = int(((usage.get("prompt_tokens_details") or {}).get("cached_tokens")) or 0)
        reasoning_tokens = int(((usage.get("completion_tokens_details") or {}).get("reasoning_tokens")) or 0)

        srv_ttft = usage.get("time_to_first_token")
        srv_prefill_dur = usage.get("prompt_eval_duration")
        srv_gen_dur = usage.get("generation_duration")
        srv_gen_tps = usage.get("generation_tokens_per_second")
        srv_prompt_tps = usage.get("prompt_tokens_per_second")

        # Raw decode tok/s (NO prefill time): prefer exact server generation_tokens_per_second
        # (immune to tool-call SSE buffering!); fallback to client SSE decode rate.
        client_sse_decode_tps = (max(0, comp_tokens - 1) / client_decode_s) if comp_tokens > 1 else (comp_tokens / total_s)
        if srv_gen_tps is not None and float(srv_gen_tps) > 0:
            raw_decode_tps = float(srv_gen_tps)
        elif srv_gen_dur is not None and float(srv_gen_dur) > 0:
            raw_decode_tps = comp_tokens / float(srv_gen_dur)
        else:
            raw_decode_tps = client_sse_decode_tps

        # Effective decode tok/s WITH prefill/TTFT factored in:
        with_prefill_tps = comp_tokens / total_s

        # Count distinct tool calls emitted
        tc_indices = {t.get("index", 0) for t in tool_chunks if isinstance(t, dict)}
        return {
            "ok": True,
            "prompt_tokens": prompt_tokens,
            "cached_tokens": cached_tokens,
            "completion_tokens": comp_tokens,
            "reasoning_tokens": reasoning_tokens,
            "content_chars": len("".join(content_parts)),
            "reasoning_chars": len("".join(reasoning_parts)),
            "tool_call_count": len(tc_indices),
            "finish_reason": finish_reason,
            "total_s": round(total_s, 3),
            "client_ttft_s": round(client_ttft_s, 3),
            "srv_ttft_s": srv_ttft,
            "srv_prefill_s": srv_prefill_dur,
            "srv_gen_s": srv_gen_dur,
            "srv_prompt_tps": srv_prompt_tps,
            "raw_decode_tps": round(raw_decode_tps, 2),
            "client_sse_decode_tps": round(client_sse_decode_tps, 2),
            "with_prefill_tps": round(with_prefill_tps, 2),
            "preview": ("".join(reasoning_parts)[:80] + " | " + "".join(content_parts)[:80] + f" | tc={len(tc_indices)}"),
        }
    except Exception as exc:
        return {
            "ok": False,
            "error": str(exc),
            "prompt_tokens": 0,
            "cached_tokens": 0,
            "completion_tokens": 0,
            "raw_decode_tps": 0.0,
            "with_prefill_tps": 0.0,
            "total_s": round(time.perf_counter() - t_start, 3),
        }


def run_cell(
    base_url: str,
    prefix_text: str,
    *,
    ctx_label: str,
    mode: str,
    batch_size: int,
    max_tokens: int,
    temperature: float,
) -> dict[str, Any]:
    prompts = PROSE_PROMPTS if mode == "prose" else (THINKING_PROMPTS if mode == "thinking" else TOOL_PROMPTS)

    def _one(idx: int) -> dict[str, Any]:
        msgs = [
            {"role": "system", "content": prefix_text},
            {"role": "user", "content": f"[slot={idx:02d} ctx={ctx_label} mode={mode}] {prompts[idx % len(prompts)]}"},
        ]
        return stream_request(
            base_url,
            msgs,
            mode=mode,
            max_tokens=max_tokens,
            temperature=temperature,
            seed=1000 + idx,
        )

    t0 = time.perf_counter()
    with concurrent.futures.ThreadPoolExecutor(max_workers=batch_size) as ex:
        futs = [ex.submit(_one, i) for i in range(batch_size)]
        outs = [f.result() for f in futs]
    wall_s = max(1e-4, time.perf_counter() - t0)

    ok_outs = [o for o in outs if o.get("ok")]
    errors = len(outs) - len(ok_outs)
    if not ok_outs:
        return {
            "ctx": ctx_label, "mode": mode, "batch_size": batch_size,
            "errors": errors, "error_sample": outs[0].get("error", ""), "wall_s": round(wall_s, 3),
        }

    total_comp = sum(o["completion_tokens"] for o in ok_outs)
    raw_list = [o["raw_decode_tps"] for o in ok_outs]
    wp_list = [o["with_prefill_tps"] for o in ok_outs]
    ttft_list = [o["srv_ttft_s"] if o["srv_ttft_s"] is not None else o["client_ttft_s"] for o in ok_outs]
    total_list = [o["total_s"] for o in ok_outs]
    pt_med = int(statistics.median([o["prompt_tokens"] for o in ok_outs]))
    ct_med = int(statistics.median([o["completion_tokens"] for o in ok_outs]))
    cached_med = int(statistics.median([o["cached_tokens"] for o in ok_outs]))
    reas_med = int(statistics.median([o["reasoning_tokens"] for o in ok_outs]))
    tc_total = sum(o["tool_call_count"] for o in ok_outs)

    ttft_sorted = sorted(ttft_list)
    p95_ttft = ttft_sorted[min(len(ttft_sorted) - 1, int(0.95 * len(ttft_sorted)))]

    return {
        "ctx": ctx_label,
        "mode": mode,
        "batch_size": batch_size,
        "prompt_tokens": pt_med,
        "cached_tokens_med": cached_med,
        "comp_tokens_med": ct_med,
        "total_comp_tokens": total_comp,
        "reasoning_tokens_med": reas_med,
        "tool_calls_total": tc_total,
        "errors": errors,
        # Raw decode (no prefill)
        "raw_med_per_slot": round(statistics.median(raw_list), 2),
        "raw_mean_per_slot": round(statistics.mean(raw_list), 2),
        "raw_agg_tps": round(sum(raw_list), 2),
        # With prefill/TTFT factored in
        "with_prefill_med_per_slot": round(statistics.median(wp_list), 2),
        "with_prefill_mean_per_slot": round(statistics.mean(wp_list), 2),
        "with_prefill_wall_agg_tps": round(total_comp / wall_s, 2),
        "with_prefill_wall_per_slot": round((total_comp / wall_s) / len(ok_outs), 2),
        # Latencies
        "med_ttft_s": round(statistics.median(ttft_list), 3),
        "p95_ttft_s": round(p95_ttft, 3),
        "med_total_s": round(statistics.median(total_list), 3),
        "wall_s": round(wall_s, 3),
        "mem": get_mem(),
    }


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--port", type=int, default=18199)
    ap.add_argument("--out", required=True)
    ap.add_argument("--max-tokens", type=int, default=192)
    ap.add_argument("--smoke", action="store_true")
    ap.add_argument("--matrix", action="store_true")
    ap.add_argument("--cold-1m", action="store_true")
    ap.add_argument("--resume", action="store_true")
    args = ap.parse_args()

    base_url = f"http://127.0.0.1:{args.port}"
    out_path = Path(args.out)
    out_path.parent.mkdir(parents=True, exist_ok=True)

    from transformers import AutoTokenizer
    print("Loading DeepSeek-V4.1 tokenizer for exact context calibration...", flush=True)
    t_tok = time.perf_counter()
    tokenizer = AutoTokenizer.from_pretrained(MODEL_DIR, trust_remote_code=True)
    print(f"Tokenizer loaded in {time.perf_counter()-t_tok:.2f}s", flush=True)

    results: dict[str, Any] = {}
    if args.resume and out_path.exists():
        results = json.loads(out_path.read_text())
    results.setdefault("port", args.port)
    results.setdefault("max_tokens", args.max_tokens)
    results.setdefault("cold_prefills", {})
    results.setdefault("cells", {})

    def save():
        out_path.write_text(json.dumps(results, indent=2))

    if args.smoke:
        print("\n=== SMOKE TEST (5K context, B=1, prose/thinking/tool) ===", flush=True)
        doc5k = build_realistic_corpus(tokenizer, 4800, "smoke5k")
        for mode in MODES:
            prompts = PROSE_PROMPTS if mode == "prose" else (THINKING_PROMPTS if mode == "thinking" else TOOL_PROMPTS)
            msgs = [
                {"role": "system", "content": doc5k},
                {"role": "user", "content": f"[smoke {mode}] {prompts[0]}"},
            ]
            r = stream_request(base_url, msgs, mode=mode, max_tokens=args.max_tokens, temperature=1.0, seed=42)
            print(
                f"  [SMOKE {mode:8s}] ok={r['ok']} pt={r.get('prompt_tokens')} cached={r.get('cached_tokens')} "
                f"ct={r.get('completion_tokens')} reas={r.get('reasoning_tokens')} tc={r.get('tool_call_count')} "
                f"raw={r.get('raw_decode_tps')} sse={r.get('client_sse_decode_tps')} "
                f"with_pf={r.get('with_prefill_tps')} srv_ttft={r.get('srv_ttft_s')} cli_ttft={r.get('client_ttft_s')} "
                f"fr={r.get('finish_reason')} | {r.get('preview','')}",
                flush=True,
            )
        return

    if args.matrix:
        print("\nBuilding base 750K corpus once for nested exact slices (5K..750K)...", flush=True)
        t_b = time.perf_counter()
        # Reserve ~150-350 tokens for chat template + user prompt (+ tool schema)
        full_doc_750k = build_realistic_corpus(tokenizer, 750_000, "bench_v41_w43")
        full_ids = tokenizer.encode(full_doc_750k, add_special_tokens=False)
        print(f"Built {len(full_ids)} tokens in {time.perf_counter()-t_b:.2f}s", flush=True)

        docs_by_ctx: dict[str, str] = {}
        for label, target in CONTEXTS:
            # Subtract 150 tokens for template/user suffix so prompt_tokens lands right on ~target
            n_sys = max(1000, target - 150)
            docs_by_ctx[label] = tokenizer.decode(full_ids[:n_sys], skip_special_tokens=True)

        for ctx_label, target in CONTEXTS:
            prefix = docs_by_ctx[ctx_label]
            print(f"\n================ CONTEXT {ctx_label} (~{target:,} tokens) ================", flush=True)

            # Warm chat (prose+tool) prefix AND thinking prefix once per tier (recording incremental prefill!)
            for warm_mode in ("prose", "thinking"):
                wkey = f"warm_{ctx_label}_{warm_mode}"
                if wkey not in results["cold_prefills"]:
                    w_msgs = [
                        {"role": "system", "content": prefix},
                        {"role": "user", "content": f"Warmup ping for {ctx_label} {warm_mode}. Reply OK."},
                    ]
                    wr = stream_request(base_url, w_msgs, mode=warm_mode, max_tokens=4, temperature=0.0, seed=1)
                    results["cold_prefills"][wkey] = wr
                    save()
                    print(
                        f"  [WARM {ctx_label:4s} {warm_mode:8s}] pt={wr.get('prompt_tokens')} cached={wr.get('cached_tokens')} "
                        f"pf_s={wr.get('srv_prefill_s')} pf_tps={wr.get('srv_prompt_tps')} ttft={wr.get('srv_ttft_s')} "
                        f"tot={wr.get('total_s')}s mem={get_mem()}",
                        flush=True,
                    )

            for mode in MODES:
                print(f"\n  --- {ctx_label} | mode={mode} ---", flush=True)
                for b in CONCURRENCIES:
                    cell_key = f"{ctx_label}_{mode}_B{b}"
                    if cell_key in results["cells"] and results["cells"][cell_key].get("errors", 1) == 0:
                        c = results["cells"][cell_key]
                        print(f"    [SKIP cached] {cell_key}: raw={c['raw_med_per_slot']} with_pf={c['with_prefill_med_per_slot']}", flush=True)
                        continue
                    c = run_cell(
                        base_url,
                        prefix,
                        ctx_label=ctx_label,
                        mode=mode,
                        batch_size=b,
                        max_tokens=args.max_tokens,
                        temperature=1.0,
                    )
                    results["cells"][cell_key] = c
                    save()
                    if c.get("errors", 0) == b:
                        print(f"    [{cell_key:16s}] ALL FAILED: {c.get('error_sample')}", flush=True)
                    else:
                        print(
                            f"    [{cell_key:16s}] pt={c['prompt_tokens']:7d} (cached={c['cached_tokens_med']:7d}) "
                            f"ct={c['comp_tokens_med']:3d} reas={c['reasoning_tokens_med']:3d} tc={c['tool_calls_total']:2d} | "
                            f"RAW={c['raw_med_per_slot']:6.2f}/slot ({c['raw_agg_tps']:6.1f} agg) | "
                            f"WITH_PF={c['with_prefill_med_per_slot']:6.2f}/slot (wall={c['with_prefill_wall_agg_tps']:6.1f} agg) | "
                            f"ttft={c['med_ttft_s']:5.2f}s (p95={c['p95_ttft_s']:5.2f}s) wall={c['wall_s']:5.2f}s "
                            f"err={c['errors']} wired={c['mem']['wired_gib']}G",
                            flush=True,
                        )

    if args.cold_1m:
        print("\n================ COLD 1,000,000-TOKEN PREFILL (B=1) ================", flush=True)
        tag_1m = f"cold1m_unique_{int(time.time())}"
        t_b = time.perf_counter()
        # 999,900 system tokens + ~100 wrapper/user tokens -> ~1,000,000 exact prompt tokens
        doc_1m = build_realistic_corpus(tokenizer, 999_900, tag_1m)
        print(f"Built unique 1M corpus ({tag_1m}) in {time.perf_counter()-t_b:.2f}s", flush=True)
        msgs_1m = [
            {"role": "system", "content": doc_1m},
            {"role": "user", "content": f"Confirm receipt of archive {tag_1m} and state the final chapter number concisely."},
        ]
        r1m = stream_request(
            base_url, msgs_1m, mode="prose", max_tokens=16, temperature=0.0, seed=42, timeout=3600
        )
        pt = r1m.get("prompt_tokens", 0)
        pf_s = r1m.get("srv_prefill_s") or r1m.get("srv_ttft_s") or r1m.get("client_ttft_s") or 1.0
        avg_pf_tps = round(pt / float(pf_s), 2) if pf_s else 0.0
        r1m["computed_avg_prefill_tps"] = avg_pf_tps
        r1m["client_ttft_prefill_tps"] = round(pt / max(1e-4, float(r1m.get("client_ttft_s", 1.0))), 2)
        r1m["mem"] = get_mem()
        results["cold_1m"] = r1m
        save()
        print(
            f"  [COLD 1M B=1] ok={r1m['ok']} pt={pt:,} cached={r1m.get('cached_tokens')} "
            f"srv_prefill_s={r1m.get('srv_prefill_s')} srv_prompt_tps={r1m.get('srv_prompt_tps')} "
            f"client_ttft_s={r1m.get('client_ttft_s')} avg_pf_tps={avg_pf_tps} "
            f"client_ttft_pf_tps={r1m['client_ttft_prefill_tps']} raw_dec={r1m.get('raw_decode_tps')} "
            f"wired={r1m['mem']['wired_gib']}G",
            flush=True,
        )

    print(f"\nDONE! Saved results to {out_path}", flush=True)


if __name__ == "__main__":
    main()
