Files
CyberGril/tools/verify_http_pagination_hel895.py
T
zonggongandmultica-agent 04eff611e7 HEL-895 release candidate: the approved kernel 152479b + the HEL-881-passed proactive-inbox frontend bf234570 assembled into one auditable head, with the full post-synthesis battery, the release package and the one-approval budget execution package - integration is a clean merge (the mainline 31970c4..152479b never touched web/, so the merge brings exactly the visual director's six frontend files plus handoff-HEL-875/880.json; web/ is verbatim bf234570 and src/tests/tools/config are verbatim 152479b, all HEL-874..894 backend fixes preserved, no redesign, no visual decision, the unpushed b48d28b test merge superseded); verification rerun on the merged head: 299 python tests pass on the 3.11.16 venv + requirements.lock offline, ruff clean (src/tests/tools), web typecheck 0 errors / lint 0 errors 1 pre-existing warning / vitest 55/55 / build passes with CSS still index-DdDYzR5S.css (visual untouched), pinned-SDK regressions on hel857-venv (3.10.12, deterministic 512-dim stand-in, loopback-only, temp ledgers): verify_close_ownership_hel894.py 16/16, verify_shutdown_queued_hel889.py 12/12, verify_inflight_lifecycle_hel886.py 6/6, verify_semantic_recovery_hel885.py 7/7, verify_mem0_real_hel874.py 12/12, check_release_offline_hel882.py R1-R7 15/15 (R6 honestly records the 3.11 mem0 gap); NEW real-HTTP pagination contract 7/7 (tools/verify_http_pagination_hel895.py: the real product service seeded with 327 rows proves the reverse-page + limit+1 probe + next_before + epoch contract the approved frontend depends on, the public field allowlist with proactive exactly on reach-out rows, and a mechanical port of inbox.ts fetchAfter proving the HEL-880 gap semantics against the real backend - 5-page cap leaves the gap, the next call closes it and hands the two new reach-outs exactly once); NEW real-server browser 7/7 (web/tests/hel895_real.mjs: Chromium CDP against the real API + built dist - real boot, reach card arriving over real HTTP, stage playback, the 260-row long-absence gap regression, SIGTERM restart epoch+1 with no duplicate rows, zero permission requests; evidence docs/rework/hel895/); deliverables: deploy/hel895-release-candidate.md (exact head, manifest, install reference, health matrix, disable/rollback, the exact 3.11 fixed-SDK gap verified offline - product venv imports fine, no mem0/qdrant/fastembed wheels in any local cache, hel857-venv 3.10 fixed stack untouched and un-mixed, zero downloads, resolution path unchanged per hel874-release.md §4) and docs/budget-package-hel895.md (the A/B/C tables as one approvable package: per-send four-gate stacking semantics, the cross/duplicate/missed accounting verdict - A totals stack on daily category caps by design, B extraction LLMs are dual-counted in llm_ops cumulative AND the semantic daily gate by design, embeds count only as items, all four request categories plus the global token pool cover every outbound site, failures/cancels conservatively billed with no refunds, cap-hit stop semantics and evidence - all still cap=0 defaults, the 39/60 and 498/500 freezes and the HEL-835 gate untouched); requirement checks 6/6 (origin/main, origin/agent/agent/de8874a3803b and the actual mainline 152479b, each with and without handoff-HEL-895.json); zero real LLM, zero real embeddings, zero downloads, authoritative ledgers and freezes unwritten, not deployed, PR#11 appended-not-merged, no visual changes, R5/R6/R7 honestly deferred
Co-authored-by: multica-agent <github@multica.ai>
2026-10-27 02:23:08 +08:00

282 lines
13 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-895 · 真实 HTTP 分页合同检查(零真实模型调用、仅回环、临时目录)。
被测对象是本 checkout 的真实产品服务(``python -m cybergril.api``,PYTHONPATH=src),
不是 mock。目的是证明 HEL-881 已审核的主动留言前端所依赖的 GET /api/messages
合同(倒序取页 + limit+1 探测 + next_before + epoch,web/tests/hel875_mock.mjs
逐字镜像的那份)由真实后端原样提供,且 inbox.ts 的 fetchAfter 缺口游标逻辑
(HEL-880 修复)在真实服务上同样成立。
检查项:
H1 无档案时 /api/messages 404(真实负例)。
H2 首页合同:ascending messages、恰好 limit 行、next_before=本页最小 id、
epoch 为正整数。
H3 向后整走:沿 next_before 走到底,重建全部已播种行——无重复、无缺口、
全局升序;页边界与 limit+1 探测一致(next_before 非空 ⟺ 还有更旧行)。
H4 字段允许清单:每行恰为 id/ts/role/text/turn_id/status/lifeIds(+proactive),
proactive:true 仅出现在播种的主动留言行;无回执令牌或私有候选外泄。
H5 fetchAfter 语义(inbox.ts 的机械 Python 移植):离开很久(新增 320 行,
其中 2 条主动留言)后,单次调用最多 5 页×50 行,缺口保留;下一次调用
补完,所有主动留言按 id 序恰好交出一次、无跳过、无重复。
H6 epoch 在整走期间稳定;/api/nope 404。
运行(在仓库根):
python3 tools/verify_http_pagination_hel895.py --venv /path/to/.venv311/bin/python [out.json]
证据 JSON 写 out.json(默认 docs/rework/hel895/http-pagination.json)。
"""
from __future__ import annotations
import json
import os
import shutil
import signal
import sqlite3
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
REPORT: dict = {"checks": [], "failures": []}
def check(name: str, ok: bool, detail: str = "") -> bool:
REPORT["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
if not ok:
REPORT["failures"].append(name)
print(("PASS " if ok else "FAIL ") + name + (f" — {detail}" if detail else ""))
return bool(ok)
def get(base: str, path: str):
try:
with urllib.request.urlopen(base + path, timeout=10) as r:
return r.status, json.loads(r.read().decode())
except urllib.error.HTTPError as e:
body = e.read().decode()
try:
return e.code, json.loads(body)
except json.JSONDecodeError:
return e.code, body
def seed(db: Path, rows: int) -> dict:
"""Seed a companion identity + interleaved rows: 5 history rows (one old
reach-out) then `rows` bulk turn rows, then 2 fresh reach-outs on top."""
conn = sqlite3.connect(db)
conn.execute("PRAGMA journal_mode=WAL")
identity = {
"id": "1", "name": "测试的她", "birth": "2000-03-14", "hour": "子时",
"relation": "朋友", "nickname": "", "boundary": "",
"color": {"pillars": {"year": "庚辰", "month": "己卯", "day": "丙午", "hour": "戊子"},
"traits": "HEL-895 真实合同检查合成档案"},
}
conn.execute("INSERT INTO companion VALUES(1,?)", (json.dumps(identity, ensure_ascii=False),))
t0 = 1761393600_000
plan = [
("user", "下雨天的时候,你会想听什么?", "t-1", 0),
("companion", "会想把窗开一条缝,听雨落在铁皮檐上。", "t-1", 0),
("companion", "昨晚的月亮很亮,想起你说过喜欢夜里散步。", "reach-old", 1),
("user", "今天加班到九点,好累。", "t-2", 0),
("companion", "那先别急着做别的,喝口热水。", "t-2", 0),
]
for i in range(rows):
plan.append(("user" if i % 2 == 0 else "companion", f"别处的第{i + 1}句", f"bulk-{i}", 0))
plan.append(("companion", "窗外的雨停了,想跟你说一声。", "reach-new-1", 1))
plan.append(("companion", "刚看到一只猫从窗台跳下去。", "reach-new-2", 1))
for n, (role, text, turn, proactive) in enumerate(plan, start=1):
conn.execute(
"INSERT INTO chat_message(ts,role,text,turn_id,status,proactive) VALUES(?,?,?,?,?,?)",
(t0 + n * 60_000, role, text, turn, "sent", proactive),
)
conn.commit()
conn.close()
return {"total": len(plan), "proactive_ids": [i for i, p in enumerate(plan, start=1) if p[3]]}
def fetch_after(base: str, cursor: dict, pages: int = 5):
"""Mechanical Python port of web/src/adapters/inbox.ts fetchAfter (HEL-880):
walks backwards page by page, holds reach-outs found inside an unclosed gap,
and hands everything over in id order exactly once when the read meets the
previously-read watermark (or the record's end). The cursor mirrors the TS
shape {through, gap: {before, top, held} | None} and is passed back whole."""
rows: list = []
through = cursor["through"]
gap = dict(cursor["gap"]) if cursor["gap"] else None
if gap:
gap["held"] = list(gap["held"])
carried = gap is not None
queries = []
for _ in range(pages):
before = f"&before={gap['before']}" if gap else ""
q = f"messages?limit=50{before}"
queries.append(q)
_, page = get(base, "/api/" + q)
lst = [m for m in page.get("messages", [])
if isinstance(m.get("id"), int) and m["id"] > 0 and isinstance(m.get("text"), str)]
fresh = [m for m in lst if m["id"] > through]
opened = gap is None
if gap is None:
gap = {"before": 0, "top": max([m["id"] for m in lst], default=through), "held": []}
gap["held"][:0] = [m for m in fresh if m.get("proactive") is True]
if len(fresh) == len(lst) and page.get("next_before"):
gap["before"] = page["next_before"]
continue
rows.extend(gap["held"])
through, gap = gap["top"], None
if opened or not carried:
break
carried = False
return rows, {"through": through, "gap": gap}, queries
def main() -> int:
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("--venv", required=True, help="3.11 venv python (bin/python)")
ap.add_argument("out", nargs="?", default="docs/rework/hel895/http-pagination.json")
args = ap.parse_args()
work = Path(tempfile.mkdtemp(prefix="hel895-http-"))
data = work / "data"
data.mkdir()
db = data / "companion.db"
port = 8395
base = f"http://127.0.0.1:{port}"
env = dict(os.environ, CYBERGRIL_DB=str(db), PYTHONPATH=str(ROOT / "src"),
CYBERGRIL_R2_ENABLED="0", CYBERGRIL_SEMANTIC="off",
CYBERGRIL_LIFE_TIMEZONE="Asia/Shanghai", CYBERGRIL_PORT=str(port))
proc = subprocess.Popen([args.venv, "-m", "cybergril.api"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
try:
# Wait for the service (schema init happens on first request's lifespan).
alive = False
for _ in range(120):
try:
status, _body = get(base, "/api/messages")
alive = True
break
except Exception:
if proc.poll() is not None:
print(proc.stderr.read().decode()[-2000:])
break
time.sleep(0.5)
if not check("H0_service_up", alive, f"port {port}"):
return 1
# H1 — no companion yet: the real negative.
status, body = get(base, "/api/messages")
check("H1_404_before_companion", status == 404, f"status={status}")
info = seed(db, rows=320)
time.sleep(0.2)
# H2 — first page contract.
status, page = get(base, "/api/messages?limit=50")
msgs = page.get("messages", [])
ids = [m["id"] for m in msgs]
ok = (status == 200 and len(msgs) == 50 and ids == sorted(ids)
and page.get("next_before") == min(ids) and isinstance(page.get("epoch"), int)
and page["epoch"] > 0)
check("H2_first_page_contract", ok,
f"len={len(msgs)} ascending={ids == sorted(ids)} next_before={page.get('next_before')} epoch={page.get('epoch')}")
# H3 — full backward walk over the real server.
all_ids, cursor, pages_used, page_mins, ascending = [], None, 0, [], True
while True:
q = f"/api/messages?limit=200{f'&before={cursor}' if cursor else ''}"
status, page = get(base, q)
ids = [m["id"] for m in page["messages"]]
ascending = ascending and ids == sorted(ids)
all_ids.extend(ids)
pages_used += 1
if ids:
page_mins.append(min(ids))
nxt = page.get("next_before")
if nxt is None or pages_used > 20:
break
# The probe contract: next_before is the page's lowest id, and only
# while strictly older rows remain.
assert nxt == min(ids), (nxt, min(ids))
cursor = nxt
expected = list(range(1, info["total"] + 1))
# Each later page's lowest id must be smaller than the previous page's
# lowest id (strict backward pages, ascending rows inside every page).
backward = all(page_mins[i] > page_mins[i + 1] for i in range(len(page_mins) - 1))
ok = (sorted(all_ids) == expected and len(set(all_ids)) == len(all_ids)
and pages_used == 2 and nxt is None and backward and ascending)
check("H3_full_backward_walk", ok,
f"rows={len(all_ids)} unique={len(set(all_ids))} pages={pages_used} "
f"backward_pages={backward} last_next_before={nxt}")
# H4 — public allowlist and the proactive flag exactly on seeded reach-outs.
status, page = get(base, "/api/messages?limit=200")
allow = {"id", "ts", "role", "text", "turn_id", "status", "lifeIds", "proactive"}
rows_seen, proactive_seen, bad_keys = 0, [], []
cursor = None
while True:
q = f"/api/messages?limit=200{f'&before={cursor}' if cursor else ''}"
_, page = get(base, q)
for m in page["messages"]:
rows_seen += 1
if not allow.issuperset(m.keys()) or "lifeIds" not in m:
bad_keys.append(sorted(m.keys()))
if m.get("proactive") is True:
proactive_seen.append(m["id"])
nxt = page.get("next_before")
if nxt is None:
break
cursor = nxt
ok = (not bad_keys and sorted(proactive_seen) == sorted(info["proactive_ids"])
and rows_seen == info["total"])
check("H4_public_allowlist_proactive_flag", ok,
f"rows={rows_seen} proactive={sorted(proactive_seen)} "
f"expected={sorted(info['proactive_ids'])} bad_keys={bad_keys[:1]}")
# H5 — fetchAfter gap semantics against the real server (returning user,
# through = id 5, then 322 newer rows landed during the absence).
cursor = {"through": 5, "gap": None}
rows1, cursor1, queries1 = fetch_after(base, cursor, pages=5)
ok1 = (cursor1["gap"] is not None and cursor1["gap"]["before"] > 0 and not rows1
and len(queries1) == 5)
rows2, cursor2, _ = fetch_after(base, cursor1, pages=5)
ok2 = (cursor2["gap"] is None and cursor2["through"] == info["total"]
and [r["id"] for r in rows2] == info["proactive_ids"][-2:])
check("H5_fetchafter_gap_semantics", ok1 and ok2,
f"call1: gap={bool(cursor1['gap'])} pages={len(queries1)} handed={len(rows1)}; "
f"call2: gap={bool(cursor2['gap'])} through={cursor2['through']}/{info['total']} "
f"handed_ids={[r['id'] for r in rows2]}")
# H6 — epoch stable across the walk; unknown API path is an honest 404.
_, p1 = get(base, "/api/messages?limit=1")
_, p2 = get(base, "/api/messages?limit=1&before=3")
status404, _ = get(base, "/api/nope")
check("H6_epoch_stable_404_shape", p1["epoch"] == p2["epoch"] and status404 == 404,
f"epoch={p1['epoch']}/{p2['epoch']} unknown={status404}")
finally:
proc.send_signal(signal.SIGTERM)
try:
proc.wait(timeout=15)
except subprocess.TimeoutExpired:
proc.kill()
err = proc.stderr.read().decode()[-1500:] if proc.stderr else ""
if err.strip():
REPORT["service_stderr_tail"] = err
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(REPORT, ensure_ascii=False, indent=1))
print(json.dumps({"ok": not REPORT["failures"], "checks": len(REPORT["checks"]),
"failures": REPORT["failures"], "out": str(out)}))
shutil.rmtree(work, ignore_errors=True)
return 0 if not REPORT["failures"] else 1
if __name__ == "__main__":
sys.exit(main())