cmvr-visual/scripts/e2e_smoke.py

140 lines
9.3 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.

"""Explicit real-model smoke run. Run only against a private acceptance environment.
Reads ADMIN_USERNAME/ADMIN_PASSWORD from environment; never logs credentials.
Uses small inference parameters to check integration, not output quality.
"""
import asyncio
from datetime import datetime, timedelta, timezone
import json
import os
from pathlib import Path
import secrets
import sys
import time
import httpx
async def main():
destination = Path(os.environ.get("SMOKE_REPORT", "/workspace/projects/cmvr-visual/.deploy/e2e.json"))
previous_run = json.loads(destination.read_text(encoding="utf-8")) if os.environ.get("SMOKE_RESUME") == "1" and destination.exists() else {}
report = {"started_at": datetime.now(timezone.utc).isoformat(), "checks": [], "jobs": {}, "events": 0}
base = os.environ.get("SMOKE_BASE_URL", "http://127.0.0.1:8000")
def save():
destination.parent.mkdir(parents=True, exist_ok=True)
destination.write_text(json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
def check(label, condition):
assert condition, label
report["checks"].append(label)
print("PASS", label, flush=True)
save()
async with httpx.AsyncClient(base_url=base, timeout=120) as c:
r = await c.post("/api/auth/login", json={"username": os.environ.get("ADMIN_USERNAME", "admin"), "password": os.environ["ADMIN_PASSWORD"]})
r.raise_for_status()
c.headers["X-CSRF-Token"] = r.json()["csrf_token"]
check("login", r.json()["user"]["role"] == "admin")
status = (await c.get("/api/system/status")).json()
check("explicit_preview_mysql", status["environment"] == "preview" and status["database_backend"] == "mysql")
check("gpu_inference_online", status["inference_online"])
report["scheduler"] = status["scheduler"]
save()
async def listen():
async with c.stream("GET", "/api/events?after=0", timeout=None) as stream:
stream.raise_for_status()
async for line in stream.aiter_lines():
if line.startswith("event:"):
report["events"] += 1
watcher = asyncio.create_task(listen())
async def submit(label, typ, inputs, parameters, **extra):
previous = previous_run.get("jobs", {}).get(label)
if label in {"image", "speech"} and previous and previous["state"] == "succeeded":
return previous
payload = {"task_type": typ, "input": inputs, "parameters": parameters, **extra}
r = await c.post("/api/jobs", json=payload, headers={"Idempotency-Key": "acceptance-" + secrets.token_hex(12)})
if r.status_code != 202:
raise RuntimeError(f"{label}: submission {r.status_code} {r.text[:400]}")
job = r.json()["jobs"][0]
report["jobs"][label] = job
save()
return job
async def wait(label, job, timeout=1500):
started = time.monotonic()
previous = None
while time.monotonic() - started < timeout:
r = await c.get("/api/jobs/" + job["id"])
r.raise_for_status()
job = r.json()
report["jobs"][label] = job
save()
if job["state"] != previous:
print(label, job["state"], job.get("phase"), flush=True)
previous = job["state"]
if job["state"] in {"succeeded", "failed", "cancelled", "timed_out"}:
check(label, job["state"] == "succeeded")
return job
await asyncio.sleep(2)
raise TimeoutError(label)
try:
image = await submit("image", "image.generate", {"prompt": "A white ceramic tea cup on a natural oak table, warm morning window light, product photograph, clean composition"}, {"width": 512, "height": 512, "num_inference_steps": 10, "seed": 20261110})
speech = await submit("speech", "audio.speech", {"prompt": "你好,这里是本地智能创作工作台。我们可以生成图片、视频和中文配音。"}, {"voice": "zf_xiaobei", "speed": 1.0})
math = await submit("math", "math.solve", {"prompt": "计算 17 乘以 23,简要给出计算过程和答案。"}, {"max_tokens": 512, "enable_thinking": False})
image, speech, math = await asyncio.gather(wait("image", image), wait("speech", speech), wait("math", math))
image_asset = next(a for a in image["result_assets"] if a["kind"] == "image")
audio_asset = next(a for a in speech["result_assets"] if a["kind"] == "audio")
check("math_real_answer", "391" in math["result"].get("text", ""))
# Download then upload a real output: validates multipart and ownership.
content = await c.get(image_asset["download_url"])
content.raise_for_status()
upload = await c.post("/api/assets", files={"file": ("验收参考图.png", content.content, "image/png")})
upload.raise_for_status()
own = upload.json()
updated = await c.patch("/api/assets/" + own["id"], json={"name": "验收参考图", "tags": ["真实验收"], "favorite": True})
check("upload_rename_tag_favorite", updated.status_code == 200 and updated.json()["favorite"])
video = await submit("video", "video.generate", {"prompt": "A gentle slow camera push toward the tea cup, soft daylight, stable composition", "image_asset_id": image_asset["id"]}, {"width": 512, "height": 288, "num_frames": 25, "fps": 24, "num_inference_steps": 4, "upscale": False, "seed": 20261110})
defect = await submit("defect", "defect.generate", {"prompt": "A white ceramic cup with small hairline surface scratches, product photograph", "image_asset_id": own["id"]}, {"width": 512, "height": 512, "num_inference_steps": 6, "seed": 20261110})
asr = await submit("asr", "audio.transcribe", {"audio_asset_id": audio_asset["id"]}, {"language": "zh"})
vision = await submit("vision", "media.structure", {"asset_id": image_asset["id"]}, {"frame_count": 2})
video, defect, asr, vision = await asyncio.gather(wait("video", video), wait("defect", defect), wait("asr", asr), wait("vision", vision))
video_asset = next(a for a in video["result_assets"] if a["kind"] == "video")
check("asr_has_chinese_text", bool(asr["result"].get("text", "").strip()))
composed = await submit("compose", "video.compose", {"audio_asset_id": audio_asset["id"]}, {"clips": [{"asset_id": video_asset["id"]}, {"asset_id": video_asset["id"]}], "subtitles": [{"start": 0, "end": 1.8, "text": "本地智能创作 · 中文字幕验收"}], "width": 640, "height": 360, "fps": 24})
composed = await wait("compose", composed)
final = next(a for a in composed["result_assets"] if a["kind"] == "video")
ranged = await c.get(final["preview_url"], headers={"Range": "bytes=0-99"})
check("video_range_206", ranged.status_code == 206 and len(ranged.content) == 100 and ranged.headers.get("content-range", "").startswith("bytes 0-99/"))
# Cancel a future job before it can consume compute; then retry explicitly.
scheduled = (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat()
cancelled = await submit("scheduled_cancel", "math.solve", {"prompt": "1+1"}, {"max_tokens": 16}, scheduled_at=scheduled)
r = await c.post("/api/jobs/" + cancelled["id"] + "/cancel")
check("scheduled_cancel", r.status_code == 200 and r.json()["state"] == "cancelled")
retried = await c.post("/api/jobs/" + cancelled["id"] + "/retry")
retried.raise_for_status()
retry = retried.json()["jobs"][0]
check("retry_new_business_id", retry["id"] != cancelled["id"])
await c.post("/api/jobs/" + retry["id"] + "/cancel")
# CSRF and owner isolation with a second dedicated acceptance account.
invalid = await c.patch("/api/assets/" + own["id"], json={"name": "blocked"}, headers={"X-CSRF-Token": "invalid"})
check("csrf_rejected", invalid.status_code == 403)
username, password = "qa_" + secrets.token_hex(5), secrets.token_urlsafe(24)
user = await c.post("/api/auth/users", json={"username": username, "display_name": "验收隔离账户", "password": password})
user.raise_for_status()
async with httpx.AsyncClient(base_url=base, timeout=30) as other:
(await other.post("/api/auth/login", json={"username": username, "password": password})).raise_for_status()
foreign_asset = await other.get(image_asset["preview_url"])
foreign_job = await other.get("/api/jobs/" + image["id"])
check("owner_isolation", foreign_asset.status_code == 404 and foreign_job.status_code == 404)
deleted = await c.delete("/api/assets/" + own["id"])
check("delete_asset", deleted.status_code == 204)
check("sse_received_real_updates", report["events"] > 10)
report["ok"] = True
finally:
watcher.cancel()
await asyncio.gather(watcher, return_exceptions=True)
report["finished_at"] = datetime.now(timezone.utc).isoformat()
save()
if __name__ == "__main__":
asyncio.run(main())