320 lines
12 KiB
Python
320 lines
12 KiB
Python
"""失真对比实验:条件单触发价「写死」vs「标记价缓存服务实时驱动」。
|
||
|
||
一次运行跑完两组对照。两组打**同一个** endpoint、同样的负载参数(10 线程 × 300 请求),
|
||
唯一变量是触发价的来源 —— 这一点在代码里就只差传给 `make_request` 的那个取价函数:
|
||
|
||
stale 组:触发价写死常量。两个相位分别低于 / 高于行情区间 → 触发率塌缩到 100% / 0%。
|
||
live 组:触发价 = 缓存服务(:18097)返回的实时标记价 ± 20 窄带。
|
||
|
||
★ 为什么这是全篇最值钱的一条:两组相位的 HTTP 状态码全是 200、业务 code 全是 0、
|
||
失败数全是 0 —— 单看压测报表(TPS / 错误率 / 延迟)挑不出任何毛病,
|
||
但 stale 组的触发率是 0% / 100%,这批数据对条件单链路的容量评估毫无意义。
|
||
「数据是错的,但看起来是对的」。
|
||
|
||
落盘:两组各写一份 results/{stale_trigger,live_trigger}-<ts>.json;
|
||
compare.py 的 §5 按 trigger.mode 分组,直接读它们出对照表。
|
||
|
||
用法:python3 scenarios/verify_trigger.py
|
||
"""
|
||
|
||
import itertools
|
||
import json
|
||
import math
|
||
import os
|
||
import random
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.request
|
||
|
||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||
RESULTS_DIR = os.path.join(ROOT, "results")
|
||
TARGET_BASE = "http://127.0.0.1:18099"
|
||
MARK_SERVICE_BASE = "http://127.0.0.1:18097"
|
||
|
||
CONTRACT_ID = 1
|
||
SIDE = "bid"
|
||
WORKERS = 10
|
||
REQUESTS_PER_PHASE = 300
|
||
BAND = 20.0 # live 组:触发价相对实时标记价的偏移带宽(约 0.06%)
|
||
|
||
# stale 组的两个相位:写死的触发价,分别落在行情区间下方 / 上方
|
||
STALE_PHASES = [
|
||
("hardcoded_low", 30500.0, "触发价写死 30500(低于行情区间)"),
|
||
("hardcoded_high", 31500.0, "触发价写死 31500(高于行情区间)"),
|
||
]
|
||
|
||
# ---------------------------------------------------------------- 基础设施
|
||
|
||
def http_json(method, url, payload=None, timeout=5.0):
|
||
data = json.dumps(payload).encode() if payload is not None else None
|
||
req = urllib.request.Request(url, data=data, method=method,
|
||
headers={"Content-Type": "application/json"})
|
||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||
return json.loads(r.read().decode())
|
||
|
||
|
||
def is_healthy(base):
|
||
try:
|
||
http_json("GET", base + "/health", timeout=1.0)
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def ensure_process(base, script, tag):
|
||
"""依赖进程自检:已在跑就复用;没在跑就在本机拉起(日志进 .pids/)。"""
|
||
if is_healthy(base):
|
||
return None
|
||
os.makedirs(os.path.join(ROOT, ".pids"), exist_ok=True)
|
||
log = open(os.path.join(ROOT, ".pids", f"{tag}.log"), "ab")
|
||
proc = subprocess.Popen([sys.executable, os.path.join(ROOT, script)],
|
||
cwd=ROOT, stdout=log, stderr=subprocess.STDOUT)
|
||
for _ in range(50):
|
||
if is_healthy(base):
|
||
return proc
|
||
if proc.poll() is not None:
|
||
raise SystemExit(f"{script} 启动即退出,见 .pids/{tag}.log")
|
||
time.sleep(0.2)
|
||
proc.kill()
|
||
raise SystemExit(f"{script} 10s 内未就绪,见 .pids/{tag}.log")
|
||
|
||
|
||
class Stats:
|
||
"""单相位统计:请求数 / 失败数 / 触发数 / 延迟样本(毫秒)。"""
|
||
|
||
def __init__(self):
|
||
self._lock = threading.Lock()
|
||
self.requests = 0
|
||
self.failures = 0
|
||
self.triggered = 0
|
||
self.latencies = []
|
||
|
||
def record(self, latency_ms, ok, triggered=False):
|
||
with self._lock:
|
||
self.requests += 1
|
||
if not ok:
|
||
self.failures += 1
|
||
if triggered:
|
||
self.triggered += 1
|
||
self.latencies.append(latency_ms)
|
||
|
||
def summary(self):
|
||
with self._lock:
|
||
lat = sorted(self.latencies)
|
||
return {
|
||
"requests": self.requests,
|
||
"failures": self.failures,
|
||
"triggered": self.triggered,
|
||
"trigger_rate": (round(self.triggered / self.requests, 4)
|
||
if self.requests else 0.0),
|
||
"p50": _pct(lat, 0.50),
|
||
"p95": _pct(lat, 0.95),
|
||
"p99": _pct(lat, 0.99),
|
||
}
|
||
|
||
|
||
def _pct(sorted_vals, p):
|
||
if not sorted_vals:
|
||
return 0.0
|
||
k = (len(sorted_vals) - 1) * p
|
||
f = math.floor(k)
|
||
c = math.ceil(k)
|
||
if f == c:
|
||
return round(sorted_vals[int(k)], 3)
|
||
return round(sorted_vals[f] + (sorted_vals[c] - sorted_vals[f]) * (k - f), 3)
|
||
|
||
|
||
def run_phase(workers, total_requests, make_request):
|
||
"""workers 个线程抢索引,共执行 total_requests 次 make_request(i)。
|
||
|
||
make_request(i) 返回 (latency_ms, ok, triggered);抛异常按失败计。
|
||
返回 (Stats, elapsed_seconds)。
|
||
"""
|
||
stats = Stats()
|
||
counter = itertools.count()
|
||
started = time.perf_counter()
|
||
|
||
def work():
|
||
while True:
|
||
i = next(counter)
|
||
if i >= total_requests:
|
||
return
|
||
try:
|
||
lat, ok, trig = make_request(i)
|
||
except Exception:
|
||
lat, ok, trig = 0.0, False, False
|
||
stats.record(lat, ok, trig)
|
||
|
||
threads = [threading.Thread(target=work) for _ in range(workers)]
|
||
for t in threads:
|
||
t.start()
|
||
for t in threads:
|
||
t.join()
|
||
return stats, time.perf_counter() - started
|
||
|
||
|
||
def write_result(worker, host, users, run_time_desc, phases, mode):
|
||
"""落一份与 compare.py 兼容的 JSON(多一个 trigger 字段承载实验数据)。
|
||
|
||
phases: [{"name", "detail", "stats": Stats, "elapsed": float}]
|
||
"""
|
||
total_req = sum(p["stats"].requests for p in phases)
|
||
total_fail = sum(p["stats"].failures for p in phases)
|
||
all_lat = sorted(lat for p in phases for lat in p["stats"].latencies)
|
||
elapsed = sum(p["elapsed"] for p in phases)
|
||
avg = round(sum(all_lat) / len(all_lat), 3) if all_lat else 0.0
|
||
rps = round(total_req / elapsed, 3) if elapsed > 0 else 0.0
|
||
result = {
|
||
"worker": worker,
|
||
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
||
"load": {"users": users, "run_time": run_time_desc, "host": host},
|
||
"total": {
|
||
"num_requests": total_req,
|
||
"num_failures": total_fail,
|
||
"avg_response_time": avg,
|
||
"p50": _pct(all_lat, 0.50),
|
||
"p95": _pct(all_lat, 0.95),
|
||
"p99": _pct(all_lat, 0.99),
|
||
"rps": rps,
|
||
},
|
||
"entries": [{
|
||
"name": "/api/v1/order/condition/open",
|
||
"method": "POST",
|
||
"num_requests": total_req,
|
||
"num_failures": total_fail,
|
||
"avg_response_time": avg,
|
||
"p50": _pct(all_lat, 0.50),
|
||
"p95": _pct(all_lat, 0.95),
|
||
"p99": _pct(all_lat, 0.99),
|
||
"rps": rps,
|
||
}],
|
||
"trigger": {
|
||
"mode": mode,
|
||
"phases": [{"name": p["name"], "detail": p["detail"],
|
||
**p["stats"].summary()} for p in phases],
|
||
},
|
||
}
|
||
os.makedirs(RESULTS_DIR, exist_ok=True)
|
||
path = os.path.join(RESULTS_DIR, f"{worker}-{int(time.time())}.json")
|
||
with open(path, "w", encoding="utf-8") as f:
|
||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||
return path
|
||
|
||
|
||
# ---------------------------------------------------------------- 实验本体
|
||
|
||
def make_request(price_source):
|
||
"""构造一次条件单请求。**两组唯一差异就是这个 price_source 参数。**"""
|
||
|
||
def call(_i):
|
||
trigger_price = price_source()
|
||
t0 = time.perf_counter()
|
||
resp = http_json(
|
||
"POST", TARGET_BASE + "/api/v1/order/condition/open",
|
||
payload={
|
||
"user_id": 1 + (_i % 1000),
|
||
"contract_id": CONTRACT_ID,
|
||
"side": SIDE,
|
||
"trigger_price": trigger_price,
|
||
"quantity": "1",
|
||
})
|
||
lat = (time.perf_counter() - t0) * 1000
|
||
data = resp.get("data") or {}
|
||
return lat, resp.get("code") == 0, bool(data.get("triggered"))
|
||
|
||
return call
|
||
|
||
|
||
def smoke_check():
|
||
"""冒烟:条件单 endpoint 必须存在(否则 18099 上跑的是旧版 mock)。"""
|
||
probe = http_json(
|
||
"POST", TARGET_BASE + "/api/v1/order/condition/open",
|
||
payload={"user_id": 0, "contract_id": CONTRACT_ID, "side": SIDE,
|
||
"trigger_price": 31000.0})
|
||
if probe.get("code") != 0 or "triggered" not in (probe.get("data") or {}):
|
||
raise SystemExit("18099 上的 mock 不含条件单 endpoint,请重启 target")
|
||
|
||
|
||
def fetch_live_price():
|
||
"""从缓存服务取实时标记价(断流时服务自动回退默认价,不中断)。"""
|
||
quote = http_json("GET", MARK_SERVICE_BASE
|
||
+ f"/mark/price?contract_id={CONTRACT_ID}")
|
||
return float(quote["price"])
|
||
|
||
|
||
def wait_live_price(timeout=5.0):
|
||
"""等缓存服务从行情源拿到第一笔实时价(stale=False 即缓存已激活)。"""
|
||
deadline = time.time() + timeout
|
||
while time.time() < deadline:
|
||
try:
|
||
q = http_json("GET", MARK_SERVICE_BASE
|
||
+ f"/mark/price?contract_id={CONTRACT_ID}", timeout=1.0)
|
||
if not q.get("stale", True):
|
||
return q["price"]
|
||
except Exception:
|
||
pass
|
||
time.sleep(0.2)
|
||
raise SystemExit("缓存服务未在限时内取到实时价(行情源 18099 是否在跑?)")
|
||
|
||
|
||
def run_stale():
|
||
"""对照组:触发价写死 —— 两个相位分别全触发 / 全不触发。"""
|
||
phases = []
|
||
for name, price, detail in STALE_PHASES:
|
||
stats, elapsed = run_phase(
|
||
WORKERS, REQUESTS_PER_PHASE, make_request(lambda p=price: p))
|
||
phases.append({"name": name, "detail": detail,
|
||
"stats": stats, "elapsed": elapsed})
|
||
s = stats.summary()
|
||
print(f"[{name}] requests={s['requests']} failures={s['failures']} "
|
||
f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} "
|
||
f"p95={s['p95']}ms")
|
||
path = write_result("stale_trigger", TARGET_BASE, WORKERS,
|
||
f"{len(STALE_PHASES)} phases x {REQUESTS_PER_PHASE} req",
|
||
phases, mode="stale")
|
||
total_fail = sum(p["stats"].failures for p in phases)
|
||
print(f"\n结果已写入 {os.path.relpath(path, ROOT)}")
|
||
print(f"★ 失败数={total_fail}(报表一切正常),但两个相位触发率塌缩到 "
|
||
f"0%/100% —— 这就是「数据是错的,但看起来是对的」。")
|
||
|
||
|
||
def run_live():
|
||
"""实验组:触发价由缓存服务的实时标记价驱动 —— 触发率落在中间区间。"""
|
||
price0 = wait_live_price()
|
||
print(f"[live] 缓存服务已激活,实时标记价 ≈ {price0}")
|
||
|
||
def price_source():
|
||
return round(fetch_live_price() + random.uniform(-BAND, BAND), 2)
|
||
|
||
stats, elapsed = run_phase(WORKERS, REQUESTS_PER_PHASE,
|
||
make_request(price_source))
|
||
s = stats.summary()
|
||
print(f"[cache_driven] requests={s['requests']} failures={s['failures']} "
|
||
f"triggered={s['triggered']} trigger_rate={s['trigger_rate']:.2%} "
|
||
f"p95={s['p95']}ms")
|
||
|
||
phases = [{"name": "cache_driven",
|
||
"detail": f"触发价=实时标记价±{BAND:.0f}(缓存服务驱动)",
|
||
"stats": stats, "elapsed": elapsed}]
|
||
path = write_result("live_trigger", TARGET_BASE, WORKERS,
|
||
f"{REQUESTS_PER_PHASE} req", phases, mode="live")
|
||
print(f"\n结果已写入 {os.path.relpath(path, ROOT)}")
|
||
print(f"★ 触发率 {s['trigger_rate']:.2%} 落在中间区间 —— 跟随行情的"
|
||
f"触发价让数据有业务意义。")
|
||
|
||
|
||
def main():
|
||
ensure_process(TARGET_BASE, os.path.join("target", "http_server.py"), "http")
|
||
smoke_check()
|
||
ensure_process(MARK_SERVICE_BASE,
|
||
os.path.join("target", "mark_price_service.py"), "mark-service")
|
||
run_stale()
|
||
print()
|
||
run_live()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|