Files
CyberGril/spike/hel857/retest868.py
T
zonggongandmultica-agent 81d50f28af HEL-868: fixed 13-call real A/B retest executed in one bounded round per rework860 _retest_plan under the original '同意测试' authorization after manager HEL-867 review lifted the stop gate - criteria/fixtures/orchestration untouched at e06dcaf (driver only captures per-call raw input/sent-context/answers and writes per-scenario outputs, never overwriting ab_scenarios.json); preflight zero-embed zero-network audit861_reuse868 + audit867_reuse868 both exit 0 with prior evidence and ledgers unchanged; 13/13 calls sent HTTP 200 (ADD1-5 anchored real extraction + QA1-8), real ledger continued on a SQLite-consistent backup of the original 26-row ledger (prefix line digest 03f92557 identical, original read-only preserved) now 39/60, embed ledger 458->498/500 (+40 dense, pre-computed debit guard held), usage 163041 tokens recorded per call; honest per-scenario results: S1/S4/S5/S8/S9 pass, S2/S3 mem0 side and S7 fail fail-closed because base-group batch-anchored infer hits carry the unshared t1 companion row in the group anchor and companion_unshared rejects them at every exit (zero leak markers in all sent contexts - the gate holds; row-level provenance for batch extractions is our adaptation gap, not visible to offline row-anchored fake payloads), S3 retrieval layer strictly better re-confirmed (11:11 target hits vs baseline 0:0) but model-use verdict fails without the gated content, S6 orchestration/status-in-block/unresolved-contrast all pass while both real answers are descriptive '资料里说...' unsupported by the pre-declared bounded grammar and honestly fail closed; no rerun, no criteria relaxation, no debug requests, no merge, no deploy; dual-target requirement checks 4/4 pass with handoff-HEL-868.json
Co-authored-by: multica-agent <github@multica.ai>
2026-10-26 03:49:33 +08:00

243 lines
9.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""HEL-868 真实 A/B 复测执行器(原获批隔离验证的剩余真实复测)。
依据:HEL-868 任务卡(总管独立复核 HEL-867 通过后解除离线纠错链的隐私停止门)
与 results/rework860_offline.json 的 _retest_plan 固定 13 次方案:
ADD1-5(base / correction_first / correction_later / fact_feeling / promise
五批真实提取,锚点随 add 写入)+ QA1-8(S2 现状带门回读 / S2 现状 gist 子测 /
S2 Mem0 / S3 现状 / S3 Mem0 / S4 更新后 / S6 已结 / S6 未结对照)。
判据、夹具、编排全部沿用 ab_scenarios.run()(提交 e06dcaf),本脚本不改任何
判据,只做三件事:
1. 逐笔捕获原始调用与实际发送上下文(add 的输入/提取结果、ask 的问题/块/回答),
边执行边落 JSONL 流水,异常退出也不丢已完成部分;
2. 逐场景独立输出 results/retest_HEL-868_S1..S9.json 与总调用审计
results/retest_HEL-868_calls.json——不调用 write_result 默认路径,
不覆盖 ab_scenarios.json 及任何历史证据;
3. 出站前守门:真实账为唯一可写续账(原 26 行只读保全,SQLite 一致备份),
嵌入账为唯一权威账,发送前由传输层/嵌入包装层按 60/500 上限扣账拦截;
预算不足或连续真实失败 3 次即停,保全已完成项并如实报告。
环境(本卡执行时由调用方设置并记录在输出中):
HEL857_DATA=<本卡全新合成目录>
HEL857_LEDGER=<本卡唯一可写续账(原 26 行前缀的 SQLite 一致备份)>
HEL857_EMBED_LEDGER=<唯一权威嵌入账(沿用,不补种不双扣)>
FASTEMBED_CACHE_PATH=<既有模型缓存(不下载新资源)>
"""
from __future__ import annotations
import json
import os
import subprocess
import sys
import time
import traceback
from datetime import datetime, timezone
from pathlib import Path
REPO = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO))
from spike.hel857 import ab_scenarios as A # noqa: E402
from spike.hel857.common import EMBED_LEDGER # noqa: E402
from spike.hel857.ledger import Ledger # noqa: E402
RESULTS = REPO / "spike/hel857/results"
CARD = "HEL-868"
STREAM = RESULTS / "retest_HEL-868_calls_stream.jsonl"
CALLS: list[dict] = []
SCENARIO_FILES = {
"S1": ["_fixture_integrity", "S1_verbatim_retention"],
"S2": ["S2_cross_session_detail"],
"S3": ["S3_paraphrase_recall"],
"S4": ["S4_correction"],
"S5": ["S5_fact_feeling_separation"],
"S6": ["S6_promise_status"],
"S7": ["S7_source_reread"],
"S8": ["S8_process_restart"],
"S9": ["S9_backup_restore"],
}
def now_iso() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def _emit(rec: dict) -> None:
rec["ts"] = now_iso()
CALLS.append(rec)
with STREAM.open("a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
f.flush()
def install_capture() -> None:
"""逐笔捕获真实 add(输入/锚点/提取结果)与 ask(问题/实际发送块/回答)。"""
seq = {"n": 0}
def next_seq(prefix: str) -> str:
seq["n"] += 1
return f"{prefix}{seq['n']}"
orig_add = A.RealRunner.add
def rec_add(self, messages, metadata=None):
call_no = next_seq("ADD")
_emit({"call": call_no, "kind": "add",
"messages": messages, "metadata": metadata})
try:
r = orig_add(self, messages, metadata)
except BaseException as e: # 失败也是逐笔记录的一部分
_emit({"call": call_no, "kind": "add_error",
"error": f"{type(e).__name__}: {e}"})
raise
_emit({"call": call_no, "kind": "add_result",
"normalized": A.normalize_add_result(r),
"raw_repr": repr(r)[:2000]})
return r
A.RealRunner.add = rec_add
orig_ask = A.ask_model
def rec_ask(ledger, m, question, context_block):
call_no = next_seq("QA")
_emit({"call": call_no, "kind": "ask", "question": question,
"sent_context": context_block})
try:
r = orig_ask(ledger, m, question, context_block)
except BaseException as e:
_emit({"call": call_no, "kind": "ask_error",
"error": f"{type(e).__name__}: {e}"})
raise
_emit({"call": call_no, "kind": "ask_result", "ok": r.get("ok"),
"answer": r.get("answer"), "latency_ms": r.get("latency_ms")})
return r
A.ask_model = rec_ask
def ledger_facts() -> dict:
led = Ledger()
rows = led.rows()
return {"ledger_path": str(led.path), "total_rows": len(rows),
"rows": rows,
"summary": {k: v for k, v in led.summary().items() if k != "rows"}}
def commit_of_repo() -> str:
return subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True,
text=True, cwd=str(REPO)).stdout.strip()
def meta() -> dict:
return {
"card": CARD,
"commit": commit_of_repo(),
"generated_at": now_iso(),
"authorization": ("HEL-797 白栖知评论 01a1737a-2f3f-7499-bafb-"
"26a41e509ef9『同意测试』;总管《HEL-867-独立复核》"
"通过后按 HEL-868 任务卡解除停止门执行剩余真实复测"),
"retest_plan": "spike/hel857/results/rework860_offline.json#_retest_plan",
"fixtures_source": "spike/hel857/fixtures.py(固定合成语料,未改动)",
"criteria_source": "spike/hel857/ab_scenarios.py(判据未改动,e06dcaf)",
"env": {k: os.environ.get(k, "") for k in (
"HEL857_DATA", "HEL857_LEDGER", "HEL857_EMBED_LEDGER",
"FASTEMBED_CACHE_PATH", "HF_HUB_OFFLINE", "TRANSFORMERS_OFFLINE",
"MEM0_TELEMETRY")},
"gateway": A.GATEWAY_BASE_URL,
"model": A.GATEWAY_MODEL,
}
def write_scenario_files(results: dict) -> None:
for s, keys in SCENARIO_FILES.items():
payload = dict(meta())
payload["scenario"] = s
payload["results"] = {k: results.get(k) for k in keys if k in results}
payload["keys_missing"] = [k for k in keys if k not in results]
passes = [bool((results.get(k) or {}).get("pass"))
for k in keys if k in results]
payload["pass"] = bool(passes) and all(passes)
(RESULTS / f"retest_{CARD}_{s}.json").write_text(
json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
def main(argv: list[str]) -> int:
if STREAM.exists():
STREAM.unlink()
RESULTS.mkdir(parents=True, exist_ok=True)
install_capture()
before_ledger = ledger_facts()
before_embed = EMBED_LEDGER.summary()
before = {"real_ledger": before_ledger["summary"] | {
"path": before_ledger["ledger_path"]},
"embed_ledger": before_embed,
"started_at": now_iso()} | meta()
print(json.dumps(before, ensure_ascii=False, indent=2))
status = "completed"
results: dict = {}
error: dict = {}
t0 = time.monotonic()
try:
results = A.run()
except BaseException as e:
status = "exception"
error = {"type": type(e).__name__, "message": str(e),
"traceback": traceback.format_exc()}
print("RUN EXCEPTION:", json.dumps(error, ensure_ascii=False),
file=sys.stderr)
after_ledger = ledger_facts()
after_embed = EMBED_LEDGER.summary()
elapsed = round(time.monotonic() - t0, 1)
calls_payload = dict(meta())
calls_payload.update({
"status": status,
"elapsed_s": elapsed,
"before": {"real_ledger": before_ledger["summary"],
"embed_ledger": before_embed},
"after": {"real_ledger": after_ledger["summary"],
"embed_ledger": after_embed},
"real_rows_new": (after_ledger["rows"][before_ledger["total_rows"]:]
if after_ledger["total_rows"] >= before_ledger[
"total_rows"] else after_ledger["rows"]),
"raw_calls": CALLS,
"usage_totals": after_ledger["summary"].get("usage_totals"),
"outcome": results.get("outcome"),
"known_ids": results.get("_known_ids"),
"mem0_adds": results.get("_mem0_adds"),
"counters": results.get("_counters"),
})
if error:
calls_payload["error"] = error
(RESULTS / f"retest_{CARD}_calls.json").write_text(
json.dumps(calls_payload, ensure_ascii=False, indent=2),
encoding="utf-8")
if status == "completed":
write_scenario_files(results)
all_pass = bool(results.get("outcome", {}).get("all_scenarios_pass"))
print(json.dumps({"status": status, "all_scenarios_pass": all_pass,
"real_calls_used": results.get("_real_calls_used"),
"embed_total": after_embed["embed_items_total"],
"elapsed_s": elapsed}, ensure_ascii=False))
return 0 if all_pass else 1
# 异常退出:保全已完成调用/用量(已在 JSONL 与 calls 文件),单独交异常报告
exc_payload = dict(meta())
exc_payload.update({"status": "exception", "error": error,
"elapsed_s": elapsed, "raw_calls": CALLS,
"real_ledger": after_ledger["summary"],
"embed_ledger": after_embed})
(RESULTS / f"retest_{CARD}_exception.json").write_text(
json.dumps(exc_payload, ensure_ascii=False, indent=2),
encoding="utf-8")
return 2
if __name__ == "__main__":
raise SystemExit(main(sys.argv[1:]))