Files
marqdo-ext-ai/scripts/run_cases.py
cflmy 155a5fa347
ci/woodpecker/push/ci Pipeline was successful
ci/woodpecker/pr/ci Pipeline was successful
feat: add candidate AI-U1 document read closed-loop case
Add the candidate-input closed loop unlocked by marqdo-cli#24 (CLI afea4f9):
the program selects the unit/anchor outline with document.outline, reads the
exact knowledge section with document.read, feeds that exact source text to
ai.classify and returns the structured identity/result.

The default component CI image still ships a CLI without document.*, so this is
a separate candidate lane (scripts/candidate_document_cycle.sh +
MARQDO_AI_CASES_DIR); the default scripts/ci.sh and 39-case suite are unchanged
and stay green. Fixture server gains a deterministic valid_yes scenario.

STATUS updates AI-U1 resolved, C01/C03 candidate PASS, I08 PARTIAL
(select->read->classify->structured result closed; compute/explain and real
model continue). Evidence: docs/evidence/2026-11-30-ai-u1-document-cycle.md.

No release, no new cross-repo dependency, no CLI/other component change.
2026-11-30 15:59:17 +08:00

392 lines
15 KiB
Python
Executable File

#!/usr/bin/env python3
"""marqdo-ext-ai independent acceptance runner.
Inputs (explicit, never inferred from a sibling checkout):
MARQDO_BIN verified marqdo executable (required)
MARQDO_STDLIB_DIR installed default Bundle directory (required)
MARQDO_AI_OUT optional evidence directory for a machine-readable summary
MARQDO_AI_TEST_TOKEN optional synthetic credential used by the credential case
(defaults to a fixed synthetic value); never printed and
never written into the evidence
The runner copies this repository into a throwaway consumer project, locks the
declared `marqdo-ext-http` dependency exactly as a real consumer would, serves
deterministic loopback HTTP fixtures, runs real `marqdo call` invocations and
asserts actual Observation values, request counts and request contents.
"""
from __future__ import annotations
import json
import os
import shutil
import socket
import subprocess
import sys
import tempfile
import time
from pathlib import Path
REPO = Path(__file__).resolve().parents[1]
CASES = REPO / "tests" / "cases"
SCHEMA = "marqdo.ai-test-case"
SCHEMA_VERSION = 1
REDACTED = "<redacted>"
class CaseError(Exception):
pass
def run(cmd: list[str], cwd: Path, env: dict[str, str], timeout: int = 180) -> subprocess.CompletedProcess:
return subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, timeout=timeout)
def consumer_manifest(alias: str) -> str:
return (
"project:\n"
" name: ai-acceptance-consumer\n"
" version: 0.0.0\n"
' marqdo: ">=3.0.0-beta.1,<4.0.0"\n'
"dependencies:\n"
f" {alias}:\n"
f" path: ./deps/{alias}\n"
)
def copy_package(target: Path) -> None:
shutil.copytree(
REPO,
target,
ignore=shutil.ignore_patterns(".git", ".marqdo", "__pycache__", "*.pyc"),
)
class Fixture:
def __init__(self, scenario: str, workdir: Path) -> None:
self.record = workdir / f"record-{scenario}-{os.getpid()}-{time.time_ns()}.jsonl"
self.process = subprocess.Popen(
[
sys.executable,
str(REPO / "scripts" / "fixture_server.py"),
"--port",
"0",
"--scenario",
scenario,
"--record",
str(self.record),
],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
)
self.port = 0
deadline = time.time() + 20
while time.time() < deadline:
line = self.process.stdout.readline() if self.process.stdout else ""
if line.startswith("PORT="):
self.port = int(line.strip().split("=", 1)[1])
break
if not line and self.process.poll() is not None:
stderr = self.process.stderr.read() if self.process.stderr else ""
raise CaseError(f"fixture failed to start: {stderr}")
if not self.port:
raise CaseError("fixture did not report a port")
# Wait for the listener to accept connections.
for _ in range(100):
try:
with socket.create_connection(("127.0.0.1", self.port), timeout=0.2):
return
except OSError:
time.sleep(0.02)
raise CaseError("fixture port never accepted a connection")
def records(self) -> list[dict]:
if not self.record.exists():
return []
text = self.record.read_text(encoding="utf-8").strip()
if not text:
return []
return [json.loads(line) for line in text.splitlines() if line.strip()]
def close(self) -> None:
self.process.terminate()
try:
self.process.wait(timeout=10)
except subprocess.TimeoutExpired:
self.process.kill()
def normalize(value):
"""Convert an Observation value document into a plain Python value."""
kind = value.get("type")
if kind == "text":
return value.get("value")
if kind == "bool":
return value.get("value")
if kind == "int":
return int(value.get("decimal"))
if kind == "float":
if "special" in value:
return value["special"]
return value.get("value")
if kind == "none":
return None
if kind == "list":
return [normalize(item) for item in value.get("items", [])]
if kind == "map":
return {key: normalize(item) for key, item in value.get("entries", {}).items()}
return {"__unhandled__": value}
def subset(expected, actual, path="$"):
if isinstance(expected, dict):
if not isinstance(actual, dict):
raise CaseError(f"{path}: expected object, got {type(actual).__name__}")
for key, value in expected.items():
if key not in actual:
raise CaseError(f"{path}: missing key {key!r}; actual keys {sorted(actual)}")
subset(value, actual[key], f"{path}.{key}")
return
if isinstance(expected, list):
if not isinstance(actual, list) or len(expected) != len(actual):
raise CaseError(f"{path}: list length/content mismatch: expected {expected!r}, got {actual!r}")
for index, value in enumerate(expected):
subset(value, actual[index], f"{path}[{index}]")
return
if isinstance(expected, float) and isinstance(actual, (int, float)):
if abs(expected - float(actual)) > 1e-9:
raise CaseError(f"{path}: {expected!r} != {actual!r}")
return
if expected != actual:
raise CaseError(f"{path}: expected {expected!r}, got {actual!r}")
def terminal(report: dict) -> dict:
events = report.get("events") or []
if not events:
raise CaseError("observation has no events")
for event in reversed(events):
if event.get("kind") in {"run.completed", "run.failed"}:
return event["payload"]
raise CaseError(f"observation has no terminal event; run status {report.get('run', {}).get('status')}")
def entry_path(case: dict) -> str:
source = case["entry"]
if source.startswith("examples/"):
return "tests/" + source
return "tests/" + source.removeprefix("tests/")
def prepare_consumer(workdir: Path, env: dict[str, str]) -> Path:
consumer = workdir / "consumer"
deps_ai = consumer / "deps" / "ai"
deps_ai.parent.mkdir(parents=True)
copy_package(deps_ai)
(consumer / "marqdo.yaml").write_text(consumer_manifest("ai"), encoding="utf-8")
tests = consumer / "tests"
(tests / "integration").mkdir(parents=True)
for source in sorted((REPO / "tests" / "integration").glob("*.mq.md")):
shutil.copy2(source, tests / "integration" / source.name)
if (REPO / "examples").is_dir():
shutil.copytree(REPO / "examples", tests / "examples")
lock = run([env["MARQDO_BIN"], "lock"], consumer, env)
if lock.returncode != 0:
raise CaseError(f"marqdo lock failed:\n{lock.stdout}\n{lock.stderr}")
# The white-box unit entry runs inside the package itself, so the package
# owns its own lock/cache there as well.
package_lock = run([env["MARQDO_BIN"], "lock"], deps_ai, env)
if package_lock.returncode != 0:
raise CaseError(f"package marqdo lock failed:\n{package_lock.stdout}\n{package_lock.stderr}")
return consumer
def case_command(case: dict, consumer: Path, env: dict[str, str], port: int) -> list[str]:
cmd = [env["MARQDO_BIN"], "call", entry_path(case), case["function"]]
for arg in case.get("args", []):
cmd += ["--arg", arg.replace("${PORT}", str(port))]
mode = case.get("mode")
if mode:
cmd += ["--mode", mode]
if case.get("mode") != "pure":
for host in case.get("grants", []):
cmd += ["--allow-net", host]
for name in case.get("allow_env", []):
cmd += ["--allow-env", name]
cmd += ["--output", "json"]
return cmd
def check_request_assertions(case: dict, records: list[dict], raw_text: str, token: str | None) -> None:
expected = case.get("request_asserts", {})
count = expected.get("count")
if count is not None and len(records) != count:
raise CaseError(f"request count {len(records)} != expected {count}")
if token:
if token in raw_text:
raise CaseError("synthetic credential leaked into the fixture record")
if any(record["headers"].get("Authorization") == token for record in records):
raise CaseError("credential was recorded unredacted")
if not records:
return
bodies = []
for record in records:
try:
bodies.append(json.loads(record["body"]))
except json.JSONDecodeError as error:
raise CaseError(f"request body is not JSON: {error}") from error
for index, body in enumerate(bodies):
where = f"request[{index}]"
if "model" in expected and body.get("model") != expected["model"]:
raise CaseError(f"{where}: model {body.get('model')!r} != {expected['model']!r}")
if expected.get("stream_false", False) and body.get("stream") is not False:
raise CaseError(f"{where}: stream is not false")
for key, value in expected.get("body_fields", {}).items():
if body.get(key) != value:
raise CaseError(f"{where}: body field {key}={body.get(key)!r} != {value!r}")
for fragment in expected.get("body_present", []):
if fragment not in json.dumps(body, ensure_ascii=False):
raise CaseError(f"{where}: request body is missing {fragment!r}")
for fragment in expected.get("body_absent", []):
if fragment in json.dumps(body, ensure_ascii=False):
raise CaseError(f"{where}: request body unexpectedly contains {fragment!r}")
if expected.get("authorization_redacted"):
if not records[-1]["headers"].get("Authorization") == REDACTED:
raise CaseError("expected a redacted Authorization header")
def run_case(case: dict, workdir: Path, env: dict[str, str], token: str | None) -> None:
name = case["name"]
consumer = workdir / "consumer"
fixture = None
try:
if case.get("kind") == "fixture":
fixture = Fixture(case["scenario"], workdir)
port = fixture.port
else:
port = 0
case_env = env.copy()
for key, value in case.get("env", {}).items():
case_env[key] = value.replace("${TEST_TOKEN}", token or "")
cmd = case_command(case, consumer, case_env, port)
result = run(cmd, consumer, case_env)
expected = case["expected"]
if expected.get("cli_failure"):
if result.returncode == 0:
raise CaseError("expected a non-zero CLI exit")
else:
if result.returncode != 0:
raise CaseError(f"CLI exited {result.returncode}:\n{result.stdout[-2000:]}\n{result.stderr[-2000:]}")
try:
report = json.loads(result.stdout)
except json.JSONDecodeError as error:
raise CaseError(f"observation is not JSON: {error}") from error
if report.get("run", {}).get("status") != "ok":
raise CaseError(f"run status is {report.get('run', {}).get('status')}")
payload = terminal(report)
actual = normalize(payload.get("value"))
if "value" in expected:
subset(expected["value"], actual)
if "meta" in expected:
meta = actual.get("meta") if isinstance(actual, dict) else None
if not isinstance(meta, dict):
raise CaseError("expected result meta map")
subset(expected["meta"], meta)
if fixture is not None:
records = fixture.records()
check_request_assertions(case, records, fixture.record.read_text(encoding="utf-8"), token)
finally:
if fixture is not None:
fixture.close()
def unit_case(case: dict, workdir: Path, env: dict[str, str]) -> None:
package = workdir / "consumer" / "deps" / "ai"
cmd = [
env["MARQDO_BIN"],
"call",
"tests/unit/internal.mq.md",
"主流程",
"--allow-env",
"MARQDO_AI_ABSENT_TOKEN",
"--output",
"json",
]
result = run(cmd, package, env)
if result.returncode != 0:
raise CaseError(f"unit CLI exited {result.returncode}:\n{result.stdout[-2000:]}\n{result.stderr[-2000:]}")
report = json.loads(result.stdout)
payload = terminal(report)
failures = normalize(payload.get("value")) or []
if failures:
raise CaseError("unit failures: " + json.dumps(failures, ensure_ascii=False))
def main() -> int:
global CASES
override = os.environ.get("MARQDO_AI_CASES_DIR")
if override:
CASES = Path(override).resolve()
binary = os.environ.get("MARQDO_BIN")
bundle = os.environ.get("MARQDO_STDLIB_DIR")
if not binary or not shutil.which(binary):
print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr)
return 2
if not bundle or not Path(bundle).is_dir():
print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr)
return 2
env = os.environ.copy()
env["MARQDO_STDLIB_DIR"] = str(Path(bundle).resolve())
token = os.environ.get("MARQDO_AI_TEST_TOKEN") or "synthetic-acceptance-token"
cases = [json.loads(path.read_text(encoding="utf-8")) for path in sorted(CASES.glob("*.json"))]
if not cases:
print("no test cases", file=sys.stderr)
return 2
for case in cases:
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
print(f"FAIL {case.get('name')}: unsupported case schema", file=sys.stderr)
return 2
version = run([binary, "--version"], REPO, env).stdout.strip()
summary = {"schema": "marqdo.ai-acceptance", "schema_version": 1, "cli_version": version, "cases": []}
failures = 0
with tempfile.TemporaryDirectory(prefix="mq-ai-acceptance-") as tmp:
workdir = Path(tmp)
try:
prepare_consumer(workdir, env)
except (CaseError, OSError) as error:
print(f"FAIL setup: {error}", file=sys.stderr)
if token:
print("(credential present but not printed)", file=sys.stderr)
return 1
for case in cases:
name = case["name"]
try:
if case.get("kind") == "unit":
unit_case(case, workdir, env)
else:
run_case(case, workdir, env, token)
print(f"PASS {name}")
summary["cases"].append({"name": name, "status": "PASS"})
except (CaseError, OSError, subprocess.TimeoutExpired, json.JSONDecodeError) as error:
failures += 1
print(f"FAIL {name}: {error}", file=sys.stderr)
summary["cases"].append({"name": name, "status": "FAIL", "detail": str(error)[:2000]})
summary["status"] = "PASS" if failures == 0 else "FAIL"
summary["passed"] = len(cases) - failures
summary["failed"] = failures
out = os.environ.get("MARQDO_AI_OUT")
if out:
target = Path(out)
target.mkdir(parents=True, exist_ok=True)
(target / "acceptance.json").write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
if failures:
print(f"{failures} of {len(cases)} cases failed", file=sys.stderr)
return 1
print(f"{len(cases)} cases passed ({version})")
return 0
if __name__ == "__main__":
sys.exit(main())