test: finalize reader snapshots against the published Core
This commit is contained in:
1 parent
a482df80be
commit
5740362880
16 files changed
+297
-33
No files matched your search
@@ -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!(
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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(());
|
||||
|
||||
@@ -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;
|
||||
@@ -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
@@ -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!(
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in new issue
Block a user