#!/usr/bin/env python3 """ bench_scale_performance.py — Tier 5: 6-Tier CPU ISA Kernel Micro-Benchmark + Live 200-Station Scale Test Measures real hardware throughput of unmodified `build/native/libstl_kernels.a` and `build/native/stl_native_server` under 200 concurrent live TCP serial stations: Part A: All supported CPU ISA tiers (SSE2 -> SSSE3 -> SSE4.2+PCLMUL -> SHA-NI -> AVX2+BMI2 -> AVX-512) for Base64, Hex, IEEE CRC-32, 64B batch SIMD state-diff, ASM serial cleaner, and 200-station RMT eye. Part B: Live 200-station `stl_native_server` over 200 real simultaneous TCP serial streams with full detail trace enabled — measuring OS thread count, VmRSS, sustained aggregate MB/s, lines/s, and WS RPC latency. """ import asyncio import contextlib import json import os from pathlib import Path import shutil import subprocess import sys import tempfile import time from typing import Any, Dict, List, Optional import aiohttp ROOT_DIR = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT_DIR / "sim" / "hil_cluster")) from cluster_harness import CONTRACTS_PATH, STL_SERVER_BIN, WEB_DIR, WsRpcClient # noqa: E402 ISA_BENCH_C = r""" #include #include #include #include #include #include "native/stl_accel/stl_accel.h" static double now_sec(void) { return (double)stl_mono_us() / 1e6; } int main(void) { int detected_tier = stl_cpu_tier_detect(); StlOpenClInfo ocl; memset(&ocl, 0, sizeof(ocl)); stl_opencl_query_info(&ocl); long nprocs = sysconf(_SC_NPROCESSORS_ONLN); const size_t PAYLOAD_SZ = 1024 * 1024; /* 1 MiB */ uint8_t *src = (uint8_t *)malloc(PAYLOAD_SZ); uint8_t *dst = (uint8_t *)malloc(PAYLOAD_SZ * 2 + 64); uint32_t x = 0x13579BDFu; for (size_t i = 0; i < PAYLOAD_SZ; i++) { x = x * 1664525u + 1013904223u; src[i] = (uint8_t)(x >> 24); } /* Realistic 1 MiB BIOS/Training/RMT/ANSI/MT86 serial payload */ const char *sample_lines[] = { "[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=128 ms\r\n", "\x1b[12;1HRunning test #7 [Moving inversions, 32 bit pattern] (Test: 7/26 26%) Errors: 0\r\n", "N0.C3.D0.R0 -18 19 -16 17 -14 15 -12 13 34500 mV\r\n", "[0][Hovsee]Current stage is 1 [HS_DRAM] N0.C0.D0 DDR5 Present Size:65536\r\n", }; uint8_t *ser_buf = (uint8_t *)malloc(PAYLOAD_SZ); size_t spos = 0; int lidx = 0; while (spos < PAYLOAD_SZ) { const char *ln = sample_lines[lidx++ & 3]; size_t ll = strlen(ln); size_t cp = (spos + ll <= PAYLOAD_SZ) ? ll : (PAYLOAD_SZ - spos); memcpy(ser_buf + spos, ln, cp); spos += cp; } /* 200-station x 320B snapshot diff buffers */ const size_t N_ST = 200; const size_t STRIDE = 320; uint8_t *prev_st = (uint8_t *)calloc(N_ST, STRIDE); uint8_t *cur_st = (uint8_t *)calloc(N_ST, STRIDE); for (size_t i = 0; i < N_ST; i += 5) cur_st[i * STRIDE + 128] = 0x5A; uint64_t masks[200]; /* 200-station RMT eye reduction buffers */ float *margins = (float *)malloc(N_ST * 24 * 4 * sizeof(float)); float *eye_out = (float *)malloc(N_ST * 24 * 256 * sizeof(float)); float *sum_out = (float *)malloc(N_ST * 4 * sizeof(float)); for (size_t i = 0; i < N_ST * 24 * 4; i++) margins[i] = 14.0f; printf("{\"detected_tier\":%d,\"detected_tier_name\":\"%s\",\"online_cpus\":%ld,\"opencl_available\":%d,\"opencl_device\":\"%s\",\"tiers\":[", detected_tier, stl_isa_tier_name(detected_tier), nprocs, ocl.available, ocl.device_name); int first = 1; for (int t = 0; t <= detected_tier; t++) { stl_force_isa_tier(t); if (!first) printf(","); first = 0; /* 1. Base64 */ double t0 = now_sec(); volatile size_t sink = 0; for (int it = 0; it < 48; it++) sink += stl_base64_encode(src, PAYLOAD_SZ, dst); double b64_mbps = (48.0 * 1.0) / (now_sec() - t0); /* 2. Hex */ t0 = now_sec(); for (int it = 0; it < 48; it++) sink += stl_hex_encode(src, PAYLOAD_SZ, dst); double hex_mbps = (48.0 * 1.0) / (now_sec() - t0); /* 3. CRC32 IEEE */ t0 = now_sec(); volatile uint32_t crc_sink = 0; for (int it = 0; it < 96; it++) crc_sink ^= stl_crc32_ieee(0, src, PAYLOAD_SZ); double crc_mbps = (96.0 * 1.0) / (now_sec() - t0); /* 4. 200-station batch 64B diff */ t0 = now_sec(); for (int it = 0; it < 50000; it++) { stl_batch_mem_diff_64b_masks(prev_st, cur_st, STRIDE, STRIDE, N_ST, masks); } double diff_dt = now_sec() - t0; double diff_mstations_s = ((double)50000 * (double)N_ST / 1e6) / diff_dt; /* 5. ASM single-pass serial cleaner */ StlCleanStreamState cst; stl_clean_stream_init(&cst); uint8_t *out_clean = (uint8_t *)malloc(PAYLOAD_SZ * 2); StlCleanLineSpan *spans = (StlCleanLineSpan *)malloc(32768 * sizeof(StlCleanLineSpan)); size_t total_lines = 0; t0 = now_sec(); for (int it = 0; it < 32; it++) { StlCleanOutput co; memset(&co, 0, sizeof(co)); co.clean_buf = out_clean; co.clean_cap = PAYLOAD_SZ * 2; co.spans = spans; co.spans_cap = 32768; stl_clean_split_classify(&cst, ser_buf, PAYLOAD_SZ, &co); total_lines += co.spans_count; } double clean_dt = now_sec() - t0; double clean_mbps = 32.0 / clean_dt; double clean_mlines_s = ((double)total_lines / 1e6) / clean_dt; free(out_clean); free(spans); /* 6. 200-station RMT eye reduction */ int used_gpu = 0; t0 = now_sec(); for (int it = 0; it < 10; it++) { stl_batch_rmt_eye_reduce(margins, N_ST, eye_out, sum_out, &used_gpu); } double rmt_ms = ((now_sec() - t0) / 10.0) * 1000.0; printf("{\"tier\":%d,\"tier_name\":\"%s\",\"b64_mbps\":%.1f,\"hex_mbps\":%.1f,\"crc32_mbps\":%.1f," "\"diff200_mstations_s\":%.2f,\"clean_mbps\":%.1f,\"clean_mlines_s\":%.2f," "\"rmt200_ms\":%.2f,\"rmt_used_gpu\":%d}", t, stl_isa_tier_name(t), b64_mbps, hex_mbps, crc_mbps, diff_mstations_s, clean_mbps, clean_mlines_s, rmt_ms, used_gpu); (void)sink; (void)crc_sink; } stl_force_isa_tier(-1); printf("]}\n"); free(src); free(dst); free(ser_buf); free(prev_st); free(cur_st); free(margins); free(eye_out); free(sum_out); return 0; } """ def clean_env() -> Dict[str, str]: env = dict(os.environ) for k in ( "LD_LIBRARY_PATH", "http_proxy", "https_proxy", "HTTP_PROXY", "HTTPS_PROXY", "all_proxy", "ALL_PROXY", ): env.pop(k, None) return env def run_part_a_isa_bench() -> Dict[str, Any]: print("[Tier5][Part A] Running 6-tier CPU ISA kernel throughput benchmark...", flush=True) tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_isa_bench_")) try: c_file = tmp_dir / "isa_bench.c" bin_file = tmp_dir / "isa_bench" c_file.write_text(ISA_BENCH_C, encoding="utf-8") subprocess.run( [ "gcc", "-O2", f"-I{ROOT_DIR}", str(c_file), f"-L{ROOT_DIR / 'build' / 'native'}", "-lstl_kernels", "-lfreeipmi", "-lipmiconsole", "-lssh", "-lutil", "-ldl", "-lpthread", "-lm", "-o", str(bin_file), ], check=True, cwd=str(ROOT_DIR), env=clean_env(), capture_output=True, text=True, ) out = subprocess.run( [str(bin_file)], check=True, cwd=str(ROOT_DIR), env=clean_env(), capture_output=True, text=True, timeout=60, ) data = json.loads(out.stdout.strip()) for row in data.get("tiers", []): print( f" Tier {row['tier']}: B64={row['b64_mbps']} MB/s | Hex={row['hex_mbps']} MB/s | " f"CRC32={row['crc32_mbps']} MB/s | Clean={row['clean_mbps']} MB/s ({row['clean_mlines_s']}M ln/s) | " f"Diff200={row['diff200_mstations_s']}M st/s | RMT200={row['rmt200_ms']} ms", flush=True, ) return data finally: shutil.rmtree(tmp_dir, ignore_errors=True) def read_proc_metrics(pid: int) -> Dict[str, Any]: threads = 0 rss_kb = 0 try: for line in Path(f"/proc/{pid}/status").read_text(encoding="utf-8").splitlines(): if line.startswith("Threads:"): threads = int(line.split()[1]) elif line.startswith("VmRSS:"): rss_kb = int(line.split()[1]) except Exception: pass cpu_ticks = 0 try: parts = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8").rsplit(")", 1)[1].split() cpu_ticks = int(parts[11]) + int(parts[12]) # utime + stime except Exception: pass return {"threads": threads, "rss_mb": round(rss_kb / 1024.0, 2), "cpu_ticks": cpu_ticks} async def run_part_b_200_stations(num_stations: int = 200, duration_s: float = 4.0) -> Dict[str, Any]: print(f"[Tier5][Part B] Running live {num_stations}-station concurrent TCP serial scale benchmark ({duration_s}s)...", flush=True) tmp_dir = Path(tempfile.mkdtemp(prefix="xjkj_scale200_")) data_dir = tmp_dir / "data" data_dir.mkdir(parents=True, exist_ok=True) web_port = 19885 tcp_port = 19886 # Build synthetic realistic BIOS/RMT/MT86 burst payload (~8 KiB per burst) burst_unit = ( b"[HS_BIOS]Version:108_VD012\r\n" b"[HS_BIOS][Training][ScktId: 0][42]Read Vref Training -- SUCCEEDED,Time=120 ms\r\n" b"N0.C0.D0.R0 -16 18 -14 16 -12 14 -11 12\r\n" b"\x1b[10;1HRunning test #7 (Test: 7/26 26%) Errors: 0\r\n" ) burst_payload = burst_unit * 32 # ~6.8 KiB, 128 lines per burst lines_per_burst = 4 * 32 connected_writers: List[asyncio.StreamWriter] = [] conn_event = asyncio.Event() stop_stream = asyncio.Event() sent_bytes = 0 sent_lines = 0 async def handle_client(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: nonlocal sent_bytes, sent_lines connected_writers.append(writer) if len(connected_writers) >= num_stations: conn_event.set() try: # Wait until streaming starts, then pump bursts continuously until stop_stream await conn_event.wait() while not stop_stream.is_set(): writer.write(burst_payload) await writer.drain() sent_bytes += len(burst_payload) sent_lines += lines_per_burst await asyncio.sleep(0.025) # ~270 KB/s per station -> ~54 MB/s across 200 stations except Exception: pass finally: with contextlib.suppress(Exception): writer.close() tcp_server = await asyncio.start_server(handle_client, "127.0.0.1", tcp_port, backlog=512) server_proc: Optional[subprocess.Popen] = None try: stations_cfg = [] for i in range(1, num_stations + 1): sid = f"S{i:03d}" stations_cfg.append({ "station_id": sid, "frontend_index": i - 1, "name": f"压测工位 {i:03d}", "mode": "hardware", "cpu_count": 2, "channels_per_cpu": 12, "bmc": {"enabled": False, "host": ""}, "console": { "enabled": True, "transport": "tcp_serial", "host": "127.0.0.1", "port": tcp_port, }, }) cfg_path = tmp_dir / "scale200.json" cfg_path.write_text(json.dumps({"mode": "hardware", "data_dir": str(data_dir), "stations": stations_cfg}), encoding="utf-8") server_proc = subprocess.Popen( [ str(STL_SERVER_BIN), "--config", str(cfg_path), "--data-dir", str(data_dir), "--web-listen", f"127.0.0.1:{web_port}", "--tftp-listen", "disabled", "--pxe-mode", "disabled", "--batch-window-ms", "100", "--detail-log", "on", "--web-dir", str(WEB_DIR), "--contracts", str(CONTRACTS_PATH), "--web-password", "disabled", ], cwd=str(ROOT_DIR), stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, env=clean_env(), ) # Wait for all 200 TCP serial connections to establish! await asyncio.wait_for(conn_event.wait(), timeout=20.0) clk_tck = os.sysconf(os.sysconf_names["SC_CLK_TCK"]) m0 = read_proc_metrics(server_proc.pid) t_stream0 = time.monotonic() # While all 200 streams blast data simultaneously, also measure live WebSocket ListStations RPC latency! rpc_latencies_ms: List[float] = [] async with aiohttp.ClientSession() as http: ws = WsRpcClient(http, f"ws://127.0.0.1:{web_port}/ws") await ws.connect() try: while time.monotonic() - t_stream0 < duration_s: tr0 = time.monotonic() lst = await ws.call("ListStations", {}, timeout=10.0) rpc_latencies_ms.append(round((time.monotonic() - tr0) * 1000.0, 2)) assert len(lst.get("stations") or []) == num_stations await asyncio.sleep(0.5) stop_stream.set() await asyncio.sleep(0.25) m1 = read_proc_metrics(server_proc.pid) hw_info = await ws.call("GetHardwareInfo", {}) trace_st = await ws.call("GetTraceStatus", {}) finally: await ws.close() elapsed = max(0.01, time.monotonic() - t_stream0) cpu_sec = (m1["cpu_ticks"] - m0["cpu_ticks"]) / float(clk_tck) cpu_pct = round((cpu_sec / elapsed) * 100.0, 1) mb_sent = sent_bytes / (1024.0 * 1024.0) mb_per_s = round(mb_sent / elapsed, 2) lines_per_s = int(sent_lines / elapsed) avg_rpc_ms = round(sum(rpc_latencies_ms) / max(1, len(rpc_latencies_ms)), 2) assert m1["threads"] <= 32, f"Thread explosion! Expected <= 32 OS threads for 200 stations, got {m1['threads']}" assert mb_per_s >= 10.0, f"Throughput too low: {mb_per_s} MB/s" res = { "num_stations": num_stations, "connected_streams": len(connected_writers), "duration_s": round(elapsed, 2), "os_threads": m1["threads"], "vm_rss_mb": m1["rss_mb"], "cpu_percent_total": cpu_pct, "total_mb_ingested": round(mb_sent, 2), "sustained_mb_per_sec": mb_per_s, "sustained_lines_per_sec": lines_per_s, "list200_rpc_avg_ms": avg_rpc_ms, "trace_serial_mb_written": round(float(trace_st.get("serial_bytes_written", 0)) / (1024.0 * 1024.0), 2), "isa_tier_name": hw_info.get("tier_name"), "ok": True, } print( f" 200 Stations LIVE: Threads={res['os_threads']} | RSS={res['vm_rss_mb']} MiB | " f"CPU={res['cpu_percent_total']}% | Throughput={res['sustained_mb_per_sec']} MB/s " f"({res['sustained_lines_per_sec']} lines/s) | ListStations(200)={res['list200_rpc_avg_ms']} ms | " f"TraceRawDisk={res['trace_serial_mb_written']} MiB", flush=True, ) return res finally: stop_stream.set() tcp_server.close() with contextlib.suppress(Exception): await tcp_server.wait_closed() if server_proc is not None and server_proc.poll() is None: with contextlib.suppress(Exception): server_proc.terminate() server_proc.wait(timeout=3.0) if server_proc.poll() is None: with contextlib.suppress(Exception): server_proc.kill() shutil.rmtree(tmp_dir, ignore_errors=True) def main() -> None: t0 = time.monotonic() part_a = run_part_a_isa_bench() part_b = asyncio.run(run_part_b_200_stations(num_stations=200, duration_s=4.0)) report = { "tier": "Tier5_6Tier_ISA_And_200Station_Scale_Benchmark", "ok": True, "elapsed_s": round(time.monotonic() - t0, 2), "isa_kernels": part_a, "live_200_stations": part_b, } out_file = ROOT_DIR / "build" / "sim" / "tier5_scale_bench_report.json" out_file.parent.mkdir(parents=True, exist_ok=True) out_file.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(f"\n[Tier5] 6-TIER ISA & 200-STATION SCALE BENCHMARK PASSED in {report['elapsed_s']}s! Report: {out_file}", flush=True) if __name__ == "__main__": main()