test: finalize reader snapshots against the published Core

This commit is contained in:
cflmy committed 2026-11-24 14:22:14 +08:00
1 parent a482df80be
commit 5740362880
16 files changed
+297 -33

No files matched your search

+13
View File
@@ -1496,3 +1496,16 @@
.mq-export-result { margin-block-start: .75rem; }
#mq-export-error { color: var(--mq-error); }
}
@layer layout {
.mq-snapshot-topbar .mq-brand { grid-column: 2; }
}
@layer overlays {
.mq-export-dialog input[type="checkbox"] { accent-color: var(--mq-gold); }
.mq-export-dialog button[disabled] { opacity: .55; cursor: default; }
}
@layer semantics {
.mq-snapshot-notice a { color: var(--mq-focus); }
}
+1 -1
View File
@@ -799,7 +799,7 @@
(exportNeedsPartial(data) ? " · 部分观察" : "");
fields.textContent = "";
[
["result_value", "返回值", preview.value_bytes, preview.value_is_public_scalar, previewBytes(result.value_text, preview.value_bytes)],
["result_value", "返回值", preview.value_bytes, preview.value_is_public_scalar, preview.value],
["stdout", "stdout", preview.stdout_bytes, false, previewBytes(result.stdout, preview.stdout_bytes)],
["stderr", "stderr", preview.stderr_bytes, false, previewBytes(result.stderr, preview.stderr_bytes)],
["trace_summary", "轨迹摘要", counts ? new TextEncoder().encode(JSON.stringify(counts)).length : null, true, counts && JSON.stringify(counts, null, 2)],
@@ -6,8 +6,12 @@
![样本记录](../media/result.webp)
## 误差
## 复核
### 误差
同名标题以稳定的序号区分。
![流程图](../media/diagram.svg)
![状态图](../media/status.gif)
+5
View File
@@ -1,3 +1,8 @@
---
import:
notes: "./docs/explanation.mq.md"
---
# @knowledge 小型统计实验
样本的均值 $\bar{x}$ 可用下式计算:
+1 -1
View File
@@ -1 +1 @@
PNG、WebP 和 SVG 均为本仓库原创合成测试图,适用仓库的 MIT/Apache-2.0 双许可。
PNG、WebP、SVG 和 GIF 均为本仓库原创合成测试图,适用仓库的 MIT/Apache-2.0 双许可。
Binary file not shown.

After

Width:  |  Height:  |  Size: 367 B

+2 -1
View File
@@ -66,6 +66,7 @@ import sys
bundle = pathlib.Path(sys.argv[1])
version, target, source_sha = sys.argv[2], sys.argv[3], sys.argv[4]
tool = json.loads((bundle / 'tool.json').read_text())
files = []
for path in sorted(bundle.rglob('*')):
if not path.is_file():
@@ -89,7 +90,7 @@ info = {
'source_sha': source_sha,
'compatibility': {
'marqdo': '>=3.0.0-beta.1,<4.0.0',
'analysis': [2],
'analysis': tool['compatibility']['analysis'],
'trace': [2],
'tool_protocol': 1,
'markdown_profile': 'marqdo.md.v1',
+81 -8
View File
@@ -49,7 +49,7 @@ def post(browser, base, route, token, body, status=200, origin=None):
return error.read(), error.headers
def verify_zip(payload, destination):
def verify_zip(payload, destination, expected_digest):
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
names = archive.namelist()
assert len(names) == len(set(names))
@@ -57,7 +57,9 @@ def verify_zip(payload, destination):
path = PurePosixPath(item.filename)
assert not path.is_absolute() and ".." not in path.parts
assert item.compress_type == zipfile.ZIP_STORED and item.file_size <= 16 * 1024 ** 2
manifest = json.loads(archive.read("manifest.json"))
raw_manifest = archive.read("manifest.json")
assert sha(raw_manifest) == expected_digest
manifest = json.loads(raw_manifest)
assert manifest["schema_version"] == 2 and not manifest["executed_during_export"]
assert manifest["execution"]["source_verified"] and manifest["execution"]["status"] == "succeeded"
assert manifest["execution"]["parameters"] == "omitted"
@@ -81,17 +83,31 @@ def verify_zip(payload, destination):
def check(root):
project = root / "project"
shutil.copytree(ROOT / "examples/complete-reader", project)
attack_text = b"<script>bad()</script><img onerror=bad()>"
lines = ["", "## @exec write_markup", "", f"`buffer = memory.new(1, {len(attack_text)})`", ""]
for index, byte in enumerate(attack_text):
lines.extend([f"`buffer[{index}] = {byte}`", ""])
lines.extend(['`out = resource.open("stdio", "stdout", ["write"])`', "",
f"`resource.write(out, buffer, 0, {len(attack_text)})`", "",
"`resource.close(out)`", "", "`return 1`", ""])
with (project / "index.mq.md").open("a") as source:
source.write("\n".join(lines))
scratch = root / "scratch"
scratch.mkdir()
count = root / "runs"
wrapper = root / "core"
wrapper.write_text(
"#!/usr/bin/env python3\n"
"import os, sys\n"
"import os, subprocess, sys, time\n"
f"core, count = {str(CORE)!r}, {str(count)!r}\n"
"if sys.argv[1] in ('run', 'call'):\n"
" assert '--event-stream' in sys.argv and '--json' not in sys.argv\n"
" with open(count, 'a') as f: f.write(sys.argv[1]+'\\n')\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'write_markup':\n"
" result = subprocess.run([core, *sys.argv[1:]], check=False)\n"
" os.unlink(sys.argv[sys.argv.index('--trace-file') + 1])\n"
" sys.exit(result.returncode)\n"
" if sys.argv[1] == 'call' and sys.argv[3] == 'scan': time.sleep(2)\n"
"os.execv(core, [core, *sys.argv[1:]])\n"
)
wrapper.chmod(0o700)
@@ -121,7 +137,7 @@ def check(root):
raise AssertionError("unauthenticated project media was accessible")
original = {path: sha(path.read_bytes()) for path in project.rglob("*") if path.is_file()}
def run(function, request_id, parameters=None):
def submit(function, request_id, parameters=None):
body = {
"document": "index.mq.md",
"target": {"kind": "function", "function_id": f"root:complete-reader@0.1.0::index.mq.md::计算.{function}"},
@@ -130,12 +146,14 @@ def check(root):
"client_request_id": request_id,
}
payload, _ = post(browser, base, "/api/runs", token, body, 202)
accepted = json.loads(payload)
return json.loads(payload)
def observe(accepted):
with browser.open(base + accepted["events_url"], timeout=20) as response:
events = [json.loads(line[6:]) for line in response.read().decode().splitlines() if line.startswith("data: ")]
return accepted["run_id"], events[-1]
run_id, terminal = run("write_output", "one")
run_id, terminal = observe(submit("write_output", "one"))
assert terminal["state"] == "succeeded" and terminal["result"]["stdout"] == "4\n", terminal
assert terminal["result"]["trace_status"] == "verified"
assert count.read_text().splitlines() == ["call"]
@@ -160,7 +178,7 @@ def check(root):
payload, headers = post(browser, base, "/api/exports", token, selection)
assert headers.get_content_type() == "application/zip" and "attachment" in headers["Content-Disposition"]
assert headers["Cache-Control"] == "no-store" and headers["X-Content-Type-Options"] == "nosniff"
verify_zip(payload, os.environ.get("SNAPSHOT_ZIP"))
verify_zip(payload, os.environ.get("SNAPSHOT_ZIP"), headers["X-Marqdo-Manifest-SHA256"])
subprocess.run([*args, "export", str(project), "--out", str(root / "pure")], check=True, env=env)
assert "本次执行快照" not in (root / "pure/index.html").read_text()
assert count.read_text().splitlines() == ["call"]
@@ -179,12 +197,67 @@ def check(root):
post(browser, base, "/api/exports", token, selection, 409)
image.unlink()
image.write_bytes(original_image)
dependency = project / "docs/explanation.mq.md"
dependency_bytes = dependency.read_bytes()
dependency.write_bytes(dependency_bytes + b"\nDependency changed.\n")
post(browser, base, "/api/exports", token, selection, 409)
dependency.write_bytes(dependency_bytes)
lock = project / "marqdo.lock"
assert not lock.exists()
lock.write_text("changed lock bytes")
post(browser, base, "/api/exports", token, selection, 409)
lock.unlink()
assert count.read_text().splitlines() == ["call"]
print("pure and selected export both leave execution count at 1; source and media staleness denied")
print("pure and selected export leave execution count at 1; source, lock, dependency and media staleness denied")
pending = submit("scan", "cancelled")
pending_selection = {**selection, "run_id": pending["run_id"]}
post(browser, base, "/api/exports", token, pending_selection, 409)
bare_cancel = urllib.request.Request(base + pending["cancel_url"], b"", {
"Origin": base, "X-View-CSRF": token
}, method="POST")
with browser.open(bare_cancel, timeout=10) as response:
assert response.status in (200, 202)
_, cancelled = observe(pending)
assert cancelled["state"] == "cancelled", cancelled
post(browser, base, "/api/exports", token, pending_selection, 409)
failed_id, failed = observe(submit("fail", "failed", [{"name": "divisor", "expression": "0"}]))
assert failed["state"] == "failed", failed
failed_selection = {**selection, "run_id": failed_id}
post(browser, base, "/api/exports", token, failed_selection, 400)
failed_zip, _ = post(browser, base, "/api/exports", token, {**failed_selection, "confirm_partial": True})
with zipfile.ZipFile(io.BytesIO(failed_zip)) as archive:
assert json.loads(archive.read("manifest.json"))["execution"]["status"] == "failed"
text_id, text = observe(submit("write_markup", "markup"))
assert text["state"] == "succeeded" and text["result"]["trace_status"] == "unavailable", text
assert text["result"]["stdout"] == attack_text.decode()
text_zip, _ = post(browser, base, "/api/exports", token, {**selection, "run_id": text_id})
with zipfile.ZipFile(io.BytesIO(text_zip)) as archive:
html = archive.read("index.html").decode()
assert "<script>" not in html and "&lt;script&gt;bad()" in html
assert json.loads(archive.read("manifest.json"))["execution"]["trace_status"] == "unavailable"
print("active/cancelled export denied, verified failure gated, stdout escaped, missing Trace separate")
calls = count.read_text().splitlines()
assert calls == ["call"] * 4, calls
print("run/call count matches four explicit submissions:", calls)
finally:
server.terminate()
server.wait(timeout=5)
with subprocess.Popen(
[*args, str(project), "--port", "0", "--no-open"],
stderr=subprocess.PIPE, text=True, env=env,
) as restarted:
try:
base = restarted.stderr.readline().split()[-1].rstrip("/")
fresh, fresh_token, _, _ = session(base)
post(fresh, base, "/api/exports", fresh_token, selection, 404)
finally:
restarted.terminate()
restarted.wait(timeout=5)
assert not list(scratch.iterdir()), list(scratch.iterdir())
print("restarted View cannot recover the previous job; private scratch directories are empty")
if __name__ == "__main__":
+53
View File
@@ -198,6 +198,25 @@ impl ExecutionController {
}
}
/// Sweep inactive jobs even if the browser never makes another request.
pub fn start_expiry_sweep(self: &Arc<Self>) {
let weak = Arc::downgrade(self);
let period = self
.config
.terminal_ttl
.min(Duration::from_secs(30))
.max(Duration::from_millis(100));
std::thread::spawn(move || loop {
std::thread::sleep(period);
let Some(controller) = weak.upgrade() else {
break;
};
if let Ok(mut state) = controller.state.lock() {
controller.purge_locked(&mut state);
};
});
}
pub fn config(&self) -> &ExecutionConfig {
&self.config
}
@@ -1179,6 +1198,40 @@ fn unique_counter() -> u64 {
mod tests {
use super::*;
#[test]
fn expired_terminal_job_is_never_returned_for_export() {
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("examples/welcome");
let service = Arc::new(DocumentService::open(&root, None).unwrap());
let config = ExecutionConfig {
terminal_ttl: Duration::ZERO,
..Default::default()
};
let controller = ExecutionController::new(service, config);
let job = Arc::new(Job::new(
"expired".into(),
"owner".into(),
"index.mq.md".into(),
));
{
let mut inner = job.inner.lock().unwrap();
inner.log.publish_state(RunState::Succeeded);
inner.terminal_at = Some(Instant::now());
}
{
let mut state = controller.state.lock().unwrap();
state.jobs.insert(job.run_id.clone(), Arc::clone(&job));
state.order.push_back(job.run_id.clone());
}
assert_eq!(
controller
.get_export_candidate("owner", &job.run_id)
.unwrap_err()
.code(),
"view.run_not_found"
);
assert!(controller.state.lock().unwrap().jobs.is_empty());
}
#[test]
fn wire_value_summary_is_safe_and_never_html() {
assert_eq!(
+27 -14
View File
@@ -56,9 +56,29 @@ impl TerminalExportCandidate {
.functions
.iter()
.find(|function| function.id == plan.function_id)?;
let (stdout, stdout_complete) = bounded_text(&result["stdout"]);
let (stderr, stderr_complete) = bounded_text(&result["stderr"]);
let (value, value_complete) = bounded_text(&result["value_text"]);
let (stdout, stdout_complete) = bounded_text(result["stdout"].as_str());
let (stderr, stderr_complete) = bounded_text(result["stderr"].as_str());
let wire = &result["value"];
let value_is_scalar = matches!(
wire["type"].as_str(),
Some("int" | "float" | "bool" | "unit" | "none" | "text")
);
let value_text = match state {
RunState::Succeeded if value_is_scalar => {
result["value_text"].as_str().map(str::to_string)
}
RunState::Succeeded if crate::protocol::value_wire_v1::transferable(wire) => {
Some(wire.to_string())
}
_ => None,
};
let (value, value_complete) = match value_text {
Some(text) => {
let (text, complete) = bounded_text(Some(&text));
(Some(text), complete)
}
None => (None, false),
};
let trace_status = match &result["trace_status"] {
Value::String(status) if status == "verified" => {
if trace.is_some_and(|trace| !trace["truncated"].is_null()) {
@@ -79,15 +99,7 @@ impl TerminalExportCandidate {
.filter_map(|(kind, count)| Some((kind.clone(), count.as_u64()?)))
.collect()
});
let value_is_public_scalar = matches!(
result["value"]["type"].as_str(),
Some("int" | "float" | "bool" | "unit")
);
let value = if state == RunState::Succeeded && !value.is_empty() {
Some(value)
} else {
None
};
let value_is_public_scalar = value_is_scalar && wire["type"] != "text";
Some(Self {
document: plan.document.to_string(),
function_id: function.id.clone(),
@@ -123,6 +135,7 @@ impl TerminalExportCandidate {
json!({
"label": self.label,
"value_bytes": self.value.as_ref().map(String::len),
"value": self.value,
"value_is_public_scalar": self.value_is_public_scalar,
"stdout_bytes": self.stdout.len(),
"stderr_bytes": self.stderr.len(),
@@ -136,8 +149,8 @@ impl TerminalExportCandidate {
}
}
fn bounded_text(value: &Value) -> (String, bool) {
let Some(text) = value.as_str() else {
fn bounded_text(value: Option<&str>) -> (String, bool) {
let Some(text) = value else {
return (String::new(), true);
};
let mut end = text.len().min(MAX_TEXT);
+1 -1
View File
@@ -187,7 +187,7 @@ fn consume(
"run.completed" => {
let value = payload
.get("value")
.filter(|value| value["type"].is_string())
.filter(|value| super::value_wire_v1::valid(value))
.ok_or(())?;
if text(payload, "status") != Some("ok") || (!*entry_frame_seen && !stream.truncated) {
return Err(());
+1
View File
@@ -7,3 +7,4 @@ pub mod analysis_v2;
pub mod execution_events_v1;
pub mod tool_v1;
pub mod trace_v2;
pub mod value_wire_v1;
+83
View File
@@ -0,0 +1,83 @@
//! Validation for the public CLI result encoding. Values stay as inert JSON.
use serde_json::Value;
pub fn valid(value: &Value) -> bool {
valid_at(value, 0)
}
fn valid_at(value: &Value, depth: usize) -> bool {
if depth > 64 {
return false;
}
let child = |item: &Value| valid_at(item, depth + 1);
match value["type"].as_str() {
Some("unit" | "none" | "resource" | "memory") => true,
Some("bool") => value["value"].is_boolean(),
Some("int") => value["decimal"].as_str().is_some_and(|value| {
let digits = value.strip_prefix('-').unwrap_or(value);
!digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit())
}),
Some("float") => match (value.get("value"), value.get("special")) {
(Some(value), None) => value.as_f64().is_some_and(f64::is_finite),
(None, Some(special)) => {
matches!(special.as_str(), Some("nan" | "infinity" | "-infinity"))
}
_ => false,
},
Some("text") => value["value"].is_string(),
Some("list") => value["items"]
.as_array()
.is_some_and(|items| items.iter().all(child)),
Some("map") => value["entries"]
.as_object()
.is_some_and(|entries| entries.values().all(child)),
Some("table") => value["header"].as_array().is_some_and(|header| {
header.iter().all(Value::is_string)
&& value["rows"].as_array().is_some_and(|rows| {
rows.iter().all(|row| {
row.as_array().is_some_and(|cells| {
cells.len() == header.len() && cells.iter().all(child)
})
})
})
}),
Some("formula") => {
value["latex"].is_string() && optional(value, "display", Value::is_boolean)
}
Some("code") => {
value["source"].is_string()
&& optional(value, "language", Value::is_string)
&& optional(value, "content_hash", Value::is_string)
}
Some("function_ref") => value["module"].is_string() && value["name"].is_string(),
Some("plugin_handle") => {
value["plugin"].is_string() && value["export"].is_string() && value["id"].is_u64()
}
_ => false,
}
}
fn optional(value: &Value, name: &str, check: fn(&Value) -> bool) -> bool {
value.get(name).is_none_or(check)
}
/// Archive terminal values that can be represented as data without handle IDs.
pub fn transferable(value: &Value) -> bool {
match value["type"].as_str() {
Some("memory" | "resource" | "plugin_handle" | "function_ref") => false,
Some("list") => value["items"]
.as_array()
.is_some_and(|items| items.iter().all(transferable)),
Some("map") => value["entries"]
.as_object()
.is_some_and(|items| items.values().all(transferable)),
Some("table") => value["rows"].as_array().is_some_and(|rows| {
rows.iter().all(|row| {
row.as_array()
.is_some_and(|values| values.iter().all(transferable))
})
}),
_ => true,
}
}
+13 -4
View File
@@ -227,7 +227,7 @@ impl ReaderRenderer {
if navigation.welcome {
self.render_welcome(&mut html, navigation);
}
self.render_document_meta(&mut html, model);
self.render_document_meta(&mut html, model, ctx.overlay.is_some());
if ctx.overlay.is_some() {
let prefix = match ctx.links {
LinkPolicy::StaticRelative { page_depth } => "../".repeat(page_depth),
@@ -278,7 +278,7 @@ impl ReaderRenderer {
navigation: &crate::reader::model::Navigation,
) {
if ctx.snapshot_package {
let _ = write!(html, "<header class=\"mq-topbar\"><a class=\"mq-brand\" href=\"#mq-main\"><img class=\"mq-brand-logo\" src=\"{}\" width=\"44\" height=\"44\" alt=\"\"><span class=\"mq-brand-word\">{}</span></a></header>",
let _ = write!(html, "<header class=\"mq-topbar mq-snapshot-topbar\"><a class=\"mq-brand\" href=\"#mq-main\"><img class=\"mq-brand-logo\" src=\"{}\" width=\"44\" height=\"44\" alt=\"\"><span class=\"mq-brand-word\">{}</span></a></header>",
escape_attr(&self.assets.logo().data_uri()), escape_text(&navigation.site_title));
return;
}
@@ -343,7 +343,12 @@ impl ReaderRenderer {
);
}
fn render_document_meta(&self, html: &mut String, model: &PresentationModel) {
fn render_document_meta(
&self,
html: &mut String,
model: &PresentationModel,
has_snapshot: bool,
) {
let status = model.source_status;
let _ = write!(
html,
@@ -353,7 +358,11 @@ impl ReaderRenderer {
"##,
file = escape_text(&model.document.identity.relative_path),
status_value = status.data_value(),
label = escape_text(status.label()),
label = if has_snapshot {
"静态文档 · 含执行快照".into()
} else {
escape_text(status.label())
},
);
if let Some(run) = &model.run {
let _ = write!(
+1
View File
@@ -41,6 +41,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
Arc::clone(&service),
ExecutionConfig::default().with_timeout(opts.run_timeout_secs),
));
controller.start_expiry_sweep();
let state = Arc::new(ServerState {
service,
controller,
+10 -2
View File
@@ -83,8 +83,13 @@ async function verifyOffline(browser, url) {
assert.match(await page.locator(".mq-snapshot pre[aria-label=返回值]").innerText(), /4\.0|Float\(4\)/);
assert.equal(await page.locator(".mq-snapshot [aria-label=stdout]").count(), 0);
await screenshot(page, "offline-snapshot.png");
await page.locator(".mq-snapshot").scrollIntoViewIfNeeded();
await screenshot(page, "offline-result.png");
await page.emulateMedia({ media: "print" });
assert.equal(await page.locator(".mq-snapshot").isVisible(), true);
await page.emulateMedia({ media: "screen" });
await page.getByRole("link", { name: "误差说明", exact: true }).click();
await imagesLoaded(page, 2);
await imagesLoaded(page, 3);
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
assert.equal(await page.locator(":target").textContent(), "误差");
assert.equal(await page.locator(".mq-snapshot").count(), 0);
@@ -114,7 +119,7 @@ async function verifyOffline(browser, url) {
await imagesLoaded(page, 1);
assert.equal(await page.locator("math mfrac").count(), 1);
await page.getByRole("link", { name: "误差说明", exact: true }).click();
await imagesLoaded(page, 2);
await imagesLoaded(page, 3);
assert.equal(await page.locator(":target").textContent(), "误差");
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
await page.getByRole("link", { name: "返回计算均值", exact: true }).click();
@@ -138,6 +143,9 @@ async function verifyOffline(browser, url) {
assert.equal(await page.locator("#mq-export-fields [name=arguments]").isChecked(), false);
assert.equal(await page.locator("#mq-export-fields [name=stdout]").isChecked(), false);
await screenshot(page, "export-preview.png");
await page.keyboard.press("Escape");
assert.equal(await page.locator("#mq-dialog-export").isVisible(), false);
await result.locator("[data-action=export-result]").click();
await page.locator("#mq-export-confirm").check();
const downloading = page.waitForEvent("download");
await page.locator("#mq-export-download").click();