feat(PR-04): explicit-run flow, Trace v2 validation and run visualization

- trace.rs: strict Trace v2 validation (schema/product/root_id/analysis_digest,
  known module ids, increasing seq, span bounds) + run states and anchor summaries
- POST /api/run: explicit confirm, CSRF token, Origin/Host checks, JSON limits,
  pure-only mode, one active run, process-group timeout, in-memory run cache
- POST /api/clear-run: session cache cleanup without touching project files
- server-rendered run panel (escaped stdout/stderr, Core error code, public final
  value only, capped event list, truncation/stale/failure states) and inline chips
  anchored to real statement spans; no per-assignment values or memory claims
- page refresh/open never invokes run (tested 10x); rejected requests never spawn
- real Trace v2 goldens (ok/truncated/arity error) from frozen CLI + contract
  and raw-HTTP tests; ADR-0004; docs updated
This commit is contained in:
marqdo-view dev committed 2026-11-22 11:38:39 +08:00
1 parent 80ce564f09
commit df1cf9ec24
25 files changed
+5724 -62

No files matched your search

+62
View File
@@ -0,0 +1,62 @@
{
"name": "marqdo-view-browser-tests",
"version": "0.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "marqdo-view-browser-tests",
"version": "0.0.0",
"devDependencies": {
"playwright": "1.49.0"
}
},
"node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
},
"node_modules/playwright": {
"version": "1.49.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.49.0.tgz",
"integrity": "sha512-eKpmys0UFDnfNb3vfsf8Vx2LEOtflgRebl0Im2eQQnYMA4Aqd+Zw8bEOB+7ZKvN76901mRnqdsiOGKxzVTbi7A==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.49.0"
},
"bin": {
"playwright": "cli.js"
},
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"fsevents": "2.3.2"
}
},
"node_modules/playwright-core": {
"version": "1.49.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.49.0.tgz",
"integrity": "sha512-R+3KKTQF3npy5GTiKH/T+kdhoJfJojjHESR1YEWhYuEKRVfVaxH3+4+GvXE5xyCngCxhxnykk0Vlah9v8fs3jA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "marqdo-view-browser-tests",
"private": true,
"version": "0.0.0",
"description": "Playwright browser acceptance tests for marqdo-view",
"scripts": {
"test": "node reader.browser.cjs"
},
"devDependencies": {
"playwright": "1.49.0"
}
}
+112
View File
@@ -0,0 +1,112 @@
{
"command": "run",
"diagnostics": [],
"stderr": "",
"stdout": "0\n0\n2\n",
"success": true,
"trace": [
{
"duration_micros": 17,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.open",
"result": "ok",
"seq": 66,
"span": {
"end": 1581,
"start": 1538
}
},
{
"duration_micros": 2,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.write",
"result": "kind=stdio count=2",
"seq": 70,
"span": {
"end": 730,
"start": 678
}
},
{
"duration_micros": 1,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.close",
"result": "flushed_bytes=0",
"seq": 85,
"span": {
"end": 1666,
"start": 1647
}
},
{
"duration_micros": 2,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.open",
"result": "ok",
"seq": 160,
"span": {
"end": 1581,
"start": 1538
}
},
{
"duration_micros": 0,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.write",
"result": "kind=stdio count=2",
"seq": 164,
"span": {
"end": 730,
"start": 678
}
},
{
"duration_micros": 0,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.close",
"result": "flushed_bytes=0",
"seq": 179,
"span": {
"end": 1666,
"start": 1647
}
},
{
"duration_micros": 0,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.open",
"result": "ok",
"seq": 253,
"span": {
"end": 1581,
"start": 1538
}
},
{
"duration_micros": 0,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.write",
"result": "kind=stdio count=2",
"seq": 257,
"span": {
"end": 730,
"start": 678
}
},
{
"duration_micros": 0,
"module": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io/stream.mq.md",
"op": "resource.close",
"result": "flushed_bytes=0",
"seq": 272,
"span": {
"end": 1666,
"start": 1647
}
}
],
"value": {
"decimal": "3",
"type": "int"
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,12 @@
{
"command": "run",
"diagnostics": [],
"stderr": "",
"stdout": "0\n0\n2\n",
"success": true,
"trace": [],
"value": {
"decimal": "3",
"type": "int"
}
}
@@ -0,0 +1,83 @@
{
"events": [
{
"detail": null,
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
"kind": "call.enter",
"module_id": "root:control-flow@0.1.0::index.mq.md",
"seq": 0,
"span": null
},
{
"detail": "continue",
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
"kind": "loop.iteration",
"module_id": "root:control-flow@0.1.0::index.mq.md",
"seq": 1,
"span": {
"end": 197,
"start": 182
}
},
{
"detail": "false",
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
"kind": "branch.eval",
"module_id": "root:control-flow@0.1.0::index.mq.md",
"seq": 2,
"span": {
"end": 211,
"start": 199
}
},
{
"detail": "true",
"function_id": "root:control-flow@0.1.0::index.mq.md::演示.main",
"kind": "branch.eval",
"module_id": "root:control-flow@0.1.0::index.mq.md",
"seq": 3,
"span": {
"end": 211,
"start": 199
}
},
{
"detail": null,
"function_id": "std:marqdo-stdlib@0.1.0#5407d3665ba2fe105820d0f1af5efaafa10c277a69eb819c3225719813c8c713::io.mq.md::io.写值",
"kind": "call.enter",
"module_id": "root:control-flow@0.1.0::index.mq.md",
"seq": 4,
"span": {
"end": 247,
"start": 239
}
},
{
"detail": "event_budget",
"kind": "trace.truncated",
"module_id": null,
"seq": 5,
"span": null
}
],
"limits": {
"max_bytes": 33554432,
"max_events": 5
},
"run": {
"entry": "root:control-flow@0.1.0::index.mq.md::main",
"id": "6-1795317753027990146",
"status": "ok"
},
"schema": "marqdo.trace",
"schema_version": 2,
"source": {
"analysis_digest": "sha256:e2aca5a1a0c9fa073a21b5af7deb8ef493ac981b97c788b721347c24c94f48ab",
"root_id": "root:control-flow@0.1.0"
},
"truncated": {
"limit": 5,
"reason": "event_budget",
"written": 5
}
}
@@ -0,0 +1,19 @@
{
"command": "run",
"error": {
"code": "call.arity",
"column": null,
"file": null,
"frames": [],
"line": null,
"message": "`演示.main` is missing required argument `n`",
"module_id": null,
"origin": "source",
"relative_path": null,
"span": null
},
"stderr": "",
"stdout": "",
"success": false,
"trace": []
}
@@ -0,0 +1,28 @@
{
"events": [
{
"detail": null,
"function_id": "root:mixed-modes@0.1.0::index.mq.md::演示.main",
"kind": "call.enter",
"module_id": "root:mixed-modes@0.1.0::index.mq.md",
"seq": 0,
"span": null
}
],
"limits": {
"max_bytes": 33554432,
"max_events": 100000
},
"run": {
"entry": "root:mixed-modes@0.1.0::index.mq.md::main",
"id": "12-1795317753068595848",
"status": "call.arity"
},
"schema": "marqdo.trace",
"schema_version": 2,
"source": {
"analysis_digest": "sha256:5b13d0cd2044cbe3d5d5f51145a9dd0015e2992400f803dad5f0e42214ce4959",
"root_id": "root:mixed-modes@0.1.0"
},
"truncated": null
}
+324 -20
View File
@@ -1,6 +1,6 @@
//! Live server smoke tests over a raw TCP HTTP/1.1 client (no extra deps).
//! The server is a real child process so startup, URL output, routing and
//! security headers are all exercised end to end.
//! Live server tests over a raw TCP HTTP/1.1 client (no extra deps).
//! The server is a real child process so startup, URL output, routing, security
//! headers, CSRF and the explicit-run flow are exercised end to end.
mod common;
@@ -24,23 +24,37 @@ impl Drop for LiveServer {
}
fn start_server() -> LiveServer {
start_server_with(
"examples/welcome",
"tests/golden/analysis-v2/welcome.json",
None,
None,
)
}
fn start_server_with(
project: &str,
analysis_golden: &str,
run_golden: Option<&str>,
trace_golden: Option<&str>,
) -> LiveServer {
use std::sync::atomic::{AtomicUsize, Ordering};
static NEXT: AtomicUsize = AtomicUsize::new(0);
let seq = NEXT.fetch_add(1, Ordering::Relaxed);
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let core = FakeCore::new(&format!("live-core-{seq}"));
let golden = std::fs::read(repo_root.join("tests/golden/analysis-v2/welcome.json")).unwrap();
let golden = std::fs::read(repo_root.join(analysis_golden)).unwrap();
core.set_analysis(std::str::from_utf8(&golden).unwrap());
if let Some(run_golden) = run_golden {
let run = std::fs::read_to_string(repo_root.join(run_golden)).unwrap();
let trace =
trace_golden.map(|trace| std::fs::read_to_string(repo_root.join(trace)).unwrap());
core.set_run(0, &run, trace.as_deref());
}
let mut child = Command::new(common::view_bin())
.current_dir(&repo_root)
.args([
"examples/welcome",
"--port",
"0",
"--no-open",
"--marqdo-bin",
])
.args([project, "--port", "0", "--no-open", "--marqdo-bin"])
.arg(&core.script)
.env_remove("MARQDO_BIN")
.env_remove("MARQDO_TOOL_PROTOCOL")
@@ -93,12 +107,37 @@ struct HttpResponse {
}
fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
http_request(port, host, "GET", path, &[], None)
}
fn http_post(port: u16, path: &str, headers: &[(&str, String)], body: &str) -> HttpResponse {
http_request(port, None, "POST", path, headers, Some(body))
}
fn http_request(
port: u16,
host: Option<&str>,
method: &str,
path: &str,
headers: &[(&str, String)],
body: Option<&str>,
) -> HttpResponse {
let mut stream = TcpStream::connect(("127.0.0.1", port)).expect("connect");
let host = host
.map(str::to_string)
.unwrap_or_else(|| format!("127.0.0.1:{port}"));
let request =
format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n\r\n");
let mut request =
format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nAccept: */*\r\n");
for (name, value) in headers {
request.push_str(&format!("{name}: {value}\r\n"));
}
if let Some(body) = body {
request.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
request.push_str("\r\n");
if let Some(body) = body {
request.push_str(body);
}
stream.write_all(request.as_bytes()).expect("write request");
let mut raw = Vec::new();
stream.read_to_end(&mut raw).expect("read response");
@@ -117,6 +156,18 @@ fn http_get(port: u16, host: Option<&str>, path: &str) -> HttpResponse {
}
}
fn csrf_token(page: &str) -> String {
page.split("name=\"mq-csrf-token\" content=\"")
.nth(1)
.and_then(|rest| rest.split('"').next())
.expect("csrf meta token")
.to_string()
}
fn json_body(page: &str) -> serde_json::Value {
serde_json::from_str(page).expect("json body")
}
#[test]
fn live_server_serves_pages_assets_and_health() {
let server = start_server();
@@ -127,9 +178,9 @@ fn live_server_serves_pages_assets_and_health() {
assert!(page.headers.contains("X-Content-Type-Options: nosniff"));
assert!(page.body.contains("mq-reader"));
assert!(page.body.contains("欢迎来到 Marqdo"));
assert!(!page.body.contains("data-live=\"false\""));
// CSRF token meta is present for the future explicit-run API.
assert!(page.body.contains("data-live=\"true\""));
assert!(page.body.contains("mq-csrf-token"));
assert!(page.body.contains("data-run-available=\"false\""));
let css_path = page
.body
@@ -145,8 +196,10 @@ fn live_server_serves_pages_assets_and_health() {
let health = http_get(server.port, None, "/api/health");
assert_eq!(health.status, 200);
assert!(health.body.contains("\"schema\": \"marqdo.view-health\""));
assert!(health.body.contains("\"analysis\": 2"));
let health = json_body(&health.body);
assert_eq!(health["schema"], "marqdo.view-health");
assert_eq!(health["protocols"]["analysis"], 2);
assert_eq!(health["run_api"], true);
let document = http_get(server.port, None, "/file?path=guide.mq.md");
assert_eq!(document.status, 200);
@@ -175,7 +228,6 @@ fn live_server_rejects_dns_rebinding_and_path_escape() {
let missing = http_get(server.port, None, "/file?path=missing.mq.md");
assert_eq!(missing.status, 404);
let unknown = http_get(server.port, None, "/api/run");
assert_eq!(unknown.status, 404);
}
@@ -183,10 +235,9 @@ fn live_server_rejects_dns_rebinding_and_path_escape() {
#[test]
fn live_server_rejects_unknown_methods_and_bad_assets() {
let server = start_server();
// POST is not exposed yet.
let mut stream = TcpStream::connect(("127.0.0.1", server.port)).expect("connect");
let request = format!(
"POST /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
"PUT /api/run HTTP/1.1\r\nHost: 127.0.0.1:{}\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}",
server.port
);
stream.write_all(request.as_bytes()).unwrap();
@@ -199,6 +250,259 @@ fn live_server_rejects_unknown_methods_and_bad_assets() {
assert_eq!(bad_asset.status, 404);
}
#[test]
fn opening_and_refreshing_never_runs_the_document() {
// R-01: ten page loads must produce zero Core `run` invocations.
let server = start_server_with(
"examples/control-flow",
"tests/golden/analysis-v2/control-flow.json",
Some("tests/golden/trace-v2/control-flow.run.json"),
Some("tests/golden/trace-v2/control-flow.trace.json"),
);
for _ in 0..10 {
let page = http_get(server.port, None, "/");
assert_eq!(page.status, 200);
assert!(page.body.contains("data-run-state=\"not-run\""));
assert!(!page.body.contains("mq-run-panel"));
}
let args = server._core.argv_lines();
let run_calls = args
.iter()
.filter(|line| line.as_str() == "arg=run")
.count();
assert_eq!(run_calls, 0, "page loads must never call Core run");
}
fn run_and_get_page(server: &LiveServer) -> (String, String) {
let page = http_get(server.port, None, "/");
let token = csrf_token(&page.body);
let response = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
],
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
);
assert_eq!(response.status, 200, "body: {}", response.body);
let json = json_body(&response.body);
assert_eq!(json["ok"], true);
let redirect = json["redirect"].as_str().expect("redirect").to_string();
let run_page = http_get(server.port, None, &redirect);
assert_eq!(run_page.status, 200);
(token, run_page.body)
}
#[test]
fn explicit_run_requires_csrf_and_confirm_then_renders_real_trace() {
let server = start_server_with(
"examples/control-flow",
"tests/golden/analysis-v2/control-flow.json",
Some("tests/golden/trace-v2/control-flow.run.json"),
Some("tests/golden/trace-v2/control-flow.trace.json"),
);
let (_, page) = run_and_get_page(&server);
assert!(page.contains("mq-run-panel"));
assert!(page.contains("data-run-state=\"succeeded\""));
assert!(page.contains("真实 Trace v2 事件"));
assert!(page.contains("mq-run-chip"), "inline run chips expected");
assert!(
page.contains("0\n0\n2"),
"Core stdout must be shown escaped"
);
// Public JSON final value is allowed; per-statement values are not claimed.
assert!(page.contains("Core 本次返回值"));
assert!(page.contains("<code>3</code>"));
assert!(
!page.contains("变量值"),
"must not claim per-assignment values"
);
let args = server._core.argv_lines();
let run_calls = args
.iter()
.filter(|line| line.as_str() == "arg=run")
.count();
assert_eq!(run_calls, 1, "exactly one explicit run expected");
assert!(args.iter().any(|line| line == "arg=pure"));
assert!(args.iter().any(|line| line == "arg=--trace-file"));
}
#[test]
fn run_api_rejects_missing_token_wrong_origin_and_bad_requests() {
let server = start_server_with(
"examples/control-flow",
"tests/golden/analysis-v2/control-flow.json",
Some("tests/golden/trace-v2/control-flow.run.json"),
Some("tests/golden/trace-v2/control-flow.trace.json"),
);
let body = r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#;
let no_token = http_post(
server.port,
"/api/run",
&[("Content-Type", "application/json".to_string())],
body,
);
assert_eq!(no_token.status, 403);
assert!(no_token.body.contains("view.run_denied"));
let page = http_get(server.port, None, "/");
let token = csrf_token(&page.body);
let wrong_origin = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
("Origin", "https://attacker.example".to_string()),
],
body,
);
assert_eq!(wrong_origin.status, 403);
let no_confirm = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
],
r#"{"path":"index.mq.md","mode":"pure","confirm":false}"#,
);
assert_eq!(no_confirm.status, 400);
let project_mode = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
],
r#"{"path":"index.mq.md","mode":"project","confirm":true}"#,
);
assert_eq!(project_mode.status, 403);
assert!(project_mode.body.contains("pure"));
let args = server._core.argv_lines();
let run_calls = args
.iter()
.filter(|line| line.as_str() == "arg=run")
.count();
assert_eq!(run_calls, 0, "rejected requests must never spawn a run");
}
#[test]
fn run_cache_can_be_cleared_and_stales_after_source_change() {
// Use a temporary copy so the test never mutates committed examples while
// other test binaries read them.
let repo_root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let project = common::TempProject::new("stale-run-project");
project.write(
"marqdo.yaml",
"project:\n name: control-flow\n version: 0.1.0\n",
);
let source =
std::fs::read_to_string(repo_root.join("examples/control-flow/index.mq.md")).unwrap();
let source_path = project.write("index.mq.md", &source);
let project_path = project.dir.to_str().unwrap().to_string();
let server = start_server_with(
&project_path,
"tests/golden/analysis-v2/control-flow.json",
Some("tests/golden/trace-v2/control-flow.run.json"),
Some("tests/golden/trace-v2/control-flow.trace.json"),
);
let page = http_get(server.port, None, "/");
let token = csrf_token(&page.body);
let response = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
],
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
);
let json = json_body(&response.body);
let run_id = json["run_id"].as_str().unwrap().to_string();
let redirect = json["redirect"].as_str().unwrap().to_string();
let run_page = http_get(server.port, None, &redirect);
assert!(run_page.body.contains("mq-run-panel"));
let clear = http_post(
server.port,
"/api/clear-run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token.clone()),
],
&format!(r#"{{"run_id":"{run_id}"}}"#),
);
assert_eq!(clear.status, 200);
let after_clear = http_get(server.port, None, &redirect);
assert!(!after_clear.body.contains("mq-run-panel"));
// Run again, then change the source bytes.
let rerun = http_post(
server.port,
"/api/run",
&[
("Content-Type", "application/json".to_string()),
("X-MQ-CSRF", token),
],
r#"{"path":"index.mq.md","mode":"pure","confirm":true}"#,
);
let rerun_json = json_body(&rerun.body);
let stale_redirect = rerun_json["redirect"].as_str().unwrap().to_string();
std::fs::write(
&source_path,
format!("{source}\n<!-- changed after run -->\n"),
)
.unwrap();
let stale_page = http_get(server.port, None, &stale_redirect);
assert_eq!(stale_page.status, 200);
assert!(
stale_page.body.contains("data-run-state=\"stale\"")
|| stale_page
.body
.contains("data-source-status=\"source-mismatch\""),
"expected stale/source-mismatch marker"
);
assert!(!stale_page.body.contains("mq-run-chip"));
}
#[test]
fn truncated_trace_is_marked_not_claimed_complete() {
let server = start_server_with(
"examples/control-flow",
"tests/golden/analysis-v2/control-flow.json",
Some("tests/golden/trace-v2/control-flow.truncated.run.json"),
Some("tests/golden/trace-v2/control-flow.truncated.trace.json"),
);
let (_, page) = run_and_get_page(&server);
assert!(page.contains("data-run-state=\"truncated\""));
assert!(page.contains("Trace 被截断"));
assert!(!page.contains("data-run-state=\"succeeded\""));
}
#[test]
fn failed_run_reports_core_error_code_without_fake_success() {
let server = start_server_with(
"examples/mixed-modes",
"tests/golden/analysis-v2/mixed-modes.json",
Some("tests/golden/trace-v2/mixed-modes.arity.run.json"),
Some("tests/golden/trace-v2/mixed-modes.arity.trace.json"),
);
// The fake core exits 0 for run, but the run JSON reports failure with the
// Core error code; View must surface that instead of a success state.
let (_, page) = run_and_get_page(&server);
assert!(page.contains("data-run-state=\"failed\""));
assert!(page.contains("call.arity"));
assert!(!page.contains("data-run-state=\"succeeded\""));
}
#[test]
fn cli_verify_output_contract_still_holds_for_installed_style_invocation() {
// Regression guard: `view verify` must remain a pure static check.
+2
View File
@@ -37,6 +37,7 @@ fn example(name: &str) -> (marqdo_view::presentation::PresentationModel, String)
diagnostics: Vec::new(),
navigation,
core_version: Some("3.0.0-beta.1".to_string()),
run: None,
});
(model, source)
}
@@ -210,6 +211,7 @@ fn malicious_markdown_cannot_inject_markup_or_scripts() {
diagnostics: Vec::new(),
navigation,
core_version: None,
run: None,
});
let html = render_live(&model);
assert!(!html.contains("<script>alert"));
+270
View File
@@ -0,0 +1,270 @@
//! Trace v2 contract tests against goldens emitted by the frozen CLI. The
//! goldens bind to the committed Analysis v2 bytes by digest, so a changed
//! source cannot silently reuse an old trace.
use marqdo_view::semantic;
use marqdo_view::source_map::{sha256_prefixed, SourceIndex};
use marqdo_view::trace::{verify_trace, RunDisplayState, TraceVerificationInput};
use serde_json::Value;
struct Fixture {
source: String,
index: SourceIndex,
analysis: Vec<u8>,
semantic: semantic::VerifiedAnalysis,
}
fn fixture(analysis_golden: &str, source_path: &str) -> Fixture {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let source = std::fs::read_to_string(root.join(source_path)).unwrap();
let index = SourceIndex::new(&source);
let analysis = std::fs::read(root.join(analysis_golden)).unwrap();
let semantic = semantic::verify_analysis(&analysis, &source, &index, "index.mq.md").unwrap();
Fixture {
source,
index,
analysis,
semantic,
}
}
fn golden_json(path: &str) -> Value {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
serde_json::from_slice(&std::fs::read(root.join(path)).unwrap()).unwrap()
}
fn golden_bytes(path: &str) -> Vec<u8> {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
std::fs::read(root.join(path)).unwrap()
}
fn verify(
fixture: &Fixture,
trace_golden: &str,
run_golden: &str,
exit_code: i32,
) -> marqdo_view::trace::VerifiedRun {
let trace = golden_bytes(trace_golden);
let run_json = golden_json(run_golden);
verify_trace(TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code,
})
.expect("trace verifies")
}
#[test]
fn real_control_flow_trace_binds_and_projects_events() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/control-flow.trace.json",
"tests/golden/trace-v2/control-flow.run.json",
0,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Succeeded);
assert_eq!(projection.counts.total(), 285);
assert_eq!(projection.entry_event_count, 18);
assert_eq!(projection.other_event_count, 267);
assert_eq!(projection.run_status, "ok");
assert!(projection.truncated.is_none());
assert_eq!(projection.stdout, "0\n0\n2\n");
let value = projection.result_value.as_ref().expect("return value");
assert_eq!(value.ty, "int");
assert_eq!(value.display, "3");
// Public JSON final value only; never a per-assignment value claim.
assert!(projection.analysis_digest.starts_with("sha256:"));
// The loop header is evaluated four times (three iterations + exit).
let loop_span = projection
.events
.iter()
.find(|event| event.anchor_span.is_some() && event.detail.as_deref() == Some("exit"))
.and_then(|event| event.anchor_span)
.expect("loop anchor");
let summary = projection.anchor_summary(loop_span).expect("loop summary");
assert_eq!(summary.count, 4);
assert_eq!(summary.detail, "loop exit");
assert!(summary.kinds.contains(&"loop.iteration".to_string()));
let return_anchors: Vec<_> = projection
.events
.iter()
.filter(|event| event.anchor_span.is_some())
.collect();
assert!(!return_anchors.is_empty());
// Only entry-module events ever get statement anchors.
for event in &projection.events {
if event.anchor_span.is_some() {
assert_eq!(
event.module_id.as_deref(),
Some(fixture.semantic.projection.module_id.as_str())
);
}
}
}
#[test]
fn truncated_trace_is_explicitly_marked() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/control-flow.truncated.trace.json",
"tests/golden/trace-v2/control-flow.truncated.run.json",
0,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Truncated);
let truncated = projection.truncated.as_ref().expect("truncation");
assert_eq!(truncated.reason, "event_budget");
assert_eq!(truncated.limit, 5);
assert_eq!(truncated.written, 5);
assert!(truncated.label().contains("事件数量上限"));
assert_ne!(projection.state, RunDisplayState::Succeeded);
}
#[test]
fn failed_run_keeps_the_core_error_code() {
let fixture = fixture(
"tests/golden/analysis-v2/mixed-modes.json",
"examples/mixed-modes/index.mq.md",
);
let run = verify(
&fixture,
"tests/golden/trace-v2/mixed-modes.arity.trace.json",
"tests/golden/trace-v2/mixed-modes.arity.run.json",
1,
);
let projection = &run.projection;
assert_eq!(projection.state, RunDisplayState::Failed);
assert_eq!(projection.error_code.as_deref(), Some("call.arity"));
assert_eq!(projection.run_status, "call.arity");
assert!(projection.result_value.is_none());
assert_eq!(projection.state.label(), "运行失败");
}
#[test]
fn stale_analysis_bytes_are_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut tampered = fixture.analysis.clone();
tampered.push(b' ');
let trace = golden_bytes("tests/golden/trace-v2/control-flow.trace.json");
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace,
analysis_bytes: &tampered,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
assert_eq!(err.exit_code(), 1);
}
#[test]
fn unknown_event_module_is_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["events"][0]["module_id"] = Value::String("rogue::module.mq.md".to_string());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
}
#[test]
fn non_monotonic_sequence_is_rejected() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["events"][1]["seq"] = Value::Number(0.into());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.trace_stale");
}
#[test]
fn unknown_schema_major_is_a_protocol_error_not_a_stale_trace() {
let fixture = fixture(
"tests/golden/analysis-v2/control-flow.json",
"examples/control-flow/index.mq.md",
);
let mut trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
trace["schema_version"] = Value::Number(3.into());
let trace_bytes = serde_json::to_vec(&trace).unwrap();
let run_json = golden_json("tests/golden/trace-v2/control-flow.run.json");
let err = verify_trace(TraceVerificationInput {
trace_bytes: &trace_bytes,
analysis_bytes: &fixture.analysis,
semantic: &fixture.semantic.projection,
modules: &fixture.semantic.projection.modules,
source: &fixture.source,
source_index: &fixture.index,
run_json: &run_json,
exit_code: 0,
})
.unwrap_err();
assert_eq!(err.code(), "view.protocol_incompatible");
assert_eq!(err.exit_code(), 2);
}
#[test]
fn golden_digest_is_really_sha256_of_analysis_bytes() {
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let analysis = std::fs::read(root.join("tests/golden/analysis-v2/control-flow.json")).unwrap();
let trace: Value = golden_json("tests/golden/trace-v2/control-flow.trace.json");
assert_eq!(
trace["source"]["analysis_digest"].as_str().unwrap(),
sha256_prefixed(&analysis)
);
assert_eq!(
trace["source"]["root_id"].as_str().unwrap(),
"root:control-flow@0.1.0"
);
}