diff --git a/Cargo.lock b/Cargo.lock index 9fc11f5..44d0c31 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -58,6 +58,12 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d92bec98840b8f03a5ff5413de5293bfcd8bf96467cf5452609f939ec6f5de16" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "block-buffer" version = "0.10.4" @@ -265,6 +271,7 @@ checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" name = "marqdo-view" version = "0.2.0" dependencies = [ + "base64", "clap", "comrak", "libc", diff --git a/Cargo.toml b/Cargo.toml index 19ea9ca..81c971a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ name = "integration" path = "tests/integration/main.rs" [dependencies] +base64 = "0.22" clap = { version = "4.5", features = ["derive"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/assets/reader.js b/assets/reader.js index 9717098..46f1196 100644 --- a/assets/reader.js +++ b/assets/reader.js @@ -372,12 +372,13 @@ case "cancelled": return "已取消"; case "timed_out": return "超时"; case "unavailable": return "不可用"; + case "incomplete": return "事件流不完整"; default: return String(state || "未知"); } } function isTerminalState(state) { - return ["succeeded", "failed", "cancelled", "timed_out", "unavailable"].indexOf(state) >= 0; + return ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "incomplete"].indexOf(state) >= 0; } function runPanel() { @@ -650,6 +651,7 @@ setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。"); return; } + var decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() }; var source = new EventSource(job.events_url, { withCredentials: true }); activeRun.source = source; function apply(event) { @@ -668,9 +670,13 @@ return; } activeRun.lastSeq = data.seq; + if (data.observation) { + renderObservation(data.observation, decoders); + return; + } updateRunView(data); } - ["run.state", "run.complete", "run.error", "run.snapshot"].forEach(function (kind) { + ["run.state", "run.complete", "run.error", "run.snapshot", "run.observation"].forEach(function (kind) { source.addEventListener(kind, apply); }); source.onerror = function () { @@ -680,6 +686,26 @@ }; } + function renderObservation(observation, decoders) { + var stream = observation.kind === "stdout.chunk" ? "stdout" + : observation.kind === "stderr.chunk" ? "stderr" : null; + if (stream) { + var output = $("#mq-run-" + stream); + if (!output) return; + var bytes = Uint8Array.from(atob(observation.data_base64), function (value) { + return value.charCodeAt(0); + }); + output.append(document.createTextNode(decoders[stream].decode(bytes, { stream: true }))); + output.hidden = false; + } else if (/^(branch|loop|control|call)\./.test(observation.kind)) { + var events = $("#mq-run-events"); + if (events && events.childElementCount < 100) { + appendLine(events, "li", "", observation.kind + + (observation.decision === undefined ? "" : " · " + observation.decision)); + } + } + } + function updateRunView(data) { var panel = runPanel(); if (panel) { diff --git a/src/core_client.rs b/src/core_client.rs index 8d684c4..49cc3f6 100644 --- a/src/core_client.rs +++ b/src/core_client.rs @@ -66,6 +66,7 @@ pub struct CheckOptions { #[derive(Debug, Clone)] pub struct RunOptions { + pub event_stream: bool, pub mode: SandboxMode, pub grants: Grants, pub fuel: Option, @@ -80,6 +81,7 @@ pub struct RunOptions { impl Default for RunOptions { fn default() -> Self { Self { + event_stream: false, mode: SandboxMode::Pure, grants: Grants::default(), fuel: None, @@ -481,7 +483,13 @@ fn append_common_args(args: &mut Vec, trace_path: &Path, options: &Run } args.push(OsString::from("--mode")); args.push(OsString::from(options.mode.as_str())); - args.push(OsString::from("--json")); + if options.event_stream { + push_pair(args, "--event-stream", "jsonl"); + push_pair(args, "--observe-max-events", "10000"); + push_pair(args, "--observe-max-bytes", "4194304"); + } else { + args.push(OsString::from("--json")); + } args.push(OsString::from("--trace-file")); args.push(trace_path.as_os_str().to_os_string()); for glob in &options.grants.allow_read { @@ -758,6 +766,7 @@ mod tests { Path::new("/p/index.mq.md"), Path::new("/t/trace.json"), &RunOptions { + event_stream: false, mode: SandboxMode::Pure, grants: Grants { allow_read: vec!["data/**".into()], diff --git a/src/execution/controller.rs b/src/execution/controller.rs index 8106699..810b9ef 100644 --- a/src/execution/controller.rs +++ b/src/execution/controller.rs @@ -8,8 +8,11 @@ use crate::core_client::{build_call_args, build_run_args, RunOptions, SandboxMode, ScratchDir}; use crate::error::{ViewError, ViewResult}; use crate::execution::events::{EventLog, RunEvent, RunState, Subscription}; -use crate::execution::process::{run_bounded_with_hook, ProcessBudget, ProcessOutcome}; +use crate::execution::process::{ + run_bounded_with_hook, Captured, ProcessBudget, ProcessHooks, ProcessOutcome, +}; use crate::execution::request::{self, payload_digest, ExecutionPlan, ExecutionTarget, RunMode}; +use crate::protocol::execution_events_v1 as core_events; use crate::protocol::trace_v2::{verify_trace, TraceVerificationInput}; use crate::reader::assemble::{DocumentService, StaticDocument}; use crate::reader::source::{sha256_hex, sha256_prefixed}; @@ -171,6 +174,12 @@ struct ControllerState { dedupe: HashMap, } +struct CoreRun { + process: ProcessOutcome, + trace: Option>, + stream: Option, +} + pub struct ExecutionController { service: Arc, config: ExecutionConfig, @@ -282,7 +291,7 @@ impl ExecutionController { plan: ExecutionPlan, ) { let started = Instant::now(); - let outcome = self.run_core(&job, &plan); + let outcome = self.run_core(&job, &plan, &static_doc); let cancel_requested = job.cancel.load(Ordering::SeqCst); eprintln!( "JOB_DEBUG id={} run_core elapsed={:?} cancel={cancel_requested}", @@ -336,7 +345,8 @@ impl ExecutionController { &self, job: &Arc, plan: &ExecutionPlan, - ) -> Result<(ProcessOutcome, Option>), ViewError> { + static_doc: &StaticDocument, + ) -> ViewResult { let client = self .service .core_client() @@ -346,7 +356,13 @@ impl ExecutionController { let entry = self.service.project().absolute_for(&plan.document)?; let scratch = ScratchDir::create("run")?; let trace_path = scratch.file("trace.json"); - let options = self.run_options(plan); + let mut options = self.run_options(plan); + let projection = &static_doc.verified.projection; + options.event_stream = + semver::Version::parse(&projection.producer_version).is_ok_and(|version| { + version >= semver::Version::new(3, 0, 0) + || version >= semver::Version::parse("3.0.0-rc.2").expect("valid Core version") + }); let args = match &plan.target { ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options), ExecutionTarget::Function { cli_name, .. } => { @@ -365,20 +381,60 @@ impl ExecutionController { wall_clock: self.config.run_timeout, ..self.config.budget.clone() }; + let (send_stream, receive_stream) = std::sync::mpsc::channel(); + let mut hooks = ProcessHooks { + on_spawn: Some(Box::new(hook)), + ..Default::default() + }; + if options.event_stream { + let entry = match &plan.target { + ExecutionTarget::Entry => "main", + ExecutionTarget::Function { cli_name, .. } => cli_name, + }; + let binding = core_events::Binding { + digest: static_doc.analysis_digest.clone(), + root: projection.project_root_id.clone(), + entry: format!("{}::{entry}", projection.module_id), + function: plan.function_id.clone(), + mode: plan.mode.as_str().to_string(), + producer: projection.producer_version.clone(), + modules: projection + .modules + .iter() + .map(|module| module.id.clone()) + .collect(), + max_output: DEFAULT_MAX_OUTPUT as usize, + }; + let observed_job = Arc::clone(job); + hooks.stdout = Some(Box::new(move |stdout| { + let stream = core_events::read(stdout, &binding, |observation| { + if let Ok(mut inner) = observed_job.inner.lock() { + inner.log.publish_observation(observation); + } + }); + let _ = send_stream.send(stream); + Captured::default() + })); + } let outcome = run_bounded_with_hook( client.bin(), &args, self.service.project().root(), &budget, Some(Arc::clone(&job.cancel)), - Box::new(hook), + hooks, )?; let trace = read_trace_limited(&trace_path)?; - Ok((outcome, trace)) + Ok(CoreRun { + process: outcome, + trace, + stream: receive_stream.try_recv().ok(), + }) } fn run_options(&self, plan: &ExecutionPlan) -> RunOptions { RunOptions { + event_stream: false, mode: match plan.mode { RunMode::Pure => SandboxMode::Pure, RunMode::Project => SandboxMode::Project, @@ -399,7 +455,7 @@ impl ExecutionController { plan: &ExecutionPlan, static_doc: &StaticDocument, started: Instant, - outcome: Result<(ProcessOutcome, Option>), ViewError>, + outcome: ViewResult, cancel_requested: bool, ) -> ( RunState, @@ -410,7 +466,11 @@ impl ExecutionController { Option, ) { let duration_ms = started.elapsed().as_millis() as u64; - let (outcome, trace_bytes) = match outcome { + let CoreRun { + process: outcome, + trace: trace_bytes, + stream, + } = match outcome { Ok(value) => value, Err(err) => { let state = match err.code() { @@ -486,7 +546,40 @@ impl ExecutionController { )), ); } - let json: serde_json::Value = + let json: serde_json::Value = if let Some(stream) = &stream { + let Some(mut terminal) = stream + .terminal + .clone() + .filter(|terminal| terminal["success"].as_bool() == Some(outcome.status_ok())) + else { + let mut result = base_result(plan, static_doc, duration_ms); + result["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout)); + result["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr)); + result["output_complete"] = serde_json::json!(false); + return ( + RunState::Incomplete, + result, + None, + "unavailable".into(), + Some("view.core_protocol".into()), + Some( + if stream.invalid { + "CLI 事件流无效" + } else { + "CLI 事件流缺少可信终态" + } + .into(), + ), + ); + }; + terminal["command"] = serde_json::json!(match plan.target { + ExecutionTarget::Entry => "run", + ExecutionTarget::Function { .. } => "call", + }); + terminal["stdout"] = serde_json::json!(String::from_utf8_lossy(&stream.stdout)); + terminal["stderr"] = serde_json::json!(String::from_utf8_lossy(&stream.stderr)); + terminal + } else { match serde_json::from_slice::(&outcome.stdout.bytes) { Ok(value) if value.is_object() => value, Ok(_) => { @@ -512,7 +605,8 @@ impl ExecutionController { )), ) } - }; + } + }; // Re-read the source after the run: a changed source makes the result // stale and forbids anchoring events to the current text. @@ -523,7 +617,7 @@ impl ExecutionController { .unwrap_or_default(); let stale = sha256_hex(¤t_source) != static_doc.source_sha256; - let (trace, trace_status) = build_trace_summary( + let (mut trace, mut trace_status) = build_trace_summary( trace_bytes.as_deref(), static_doc, &json, @@ -532,6 +626,26 @@ impl ExecutionController { ); let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome); result["stale"] = serde_json::json!(stale); + if let Some(stream) = stream { + result["event_protocol"] = serde_json::json!(1); + result["core_run_id"] = serde_json::json!(stream.id); + result["source_verified"] = serde_json::json!(stream.verified && !stale); + result["observation_truncated"] = serde_json::json!(stream.truncated); + result["stdout_bytes"] = serde_json::json!(stream.stdout.len()); + result["stderr_bytes"] = serde_json::json!(stream.stderr.len()); + result["output_complete"] = serde_json::json!(!json["error"]["code"] + .as_str() + .is_some_and(|code| code.contains("output_limit"))); + if trace_status == "verified" + && trace + .as_ref() + .and_then(|trace| trace["core_run_id"].as_str()) + != Some(&stream.id) + { + trace = None; + trace_status = "invalid".into(); + } + } let success = json .get("success") .and_then(serde_json::Value::as_bool) @@ -692,6 +806,7 @@ fn base_result( ) -> serde_json::Value { serde_json::json!({ "document": plan.document.as_str(), + "function_id": plan.function_id, "target": match &plan.target { ExecutionTarget::Entry => serde_json::json!({"kind": "entry"}), ExecutionTarget::Function { cli_name, label } => serde_json::json!({ diff --git a/src/execution/events.rs b/src/execution/events.rs index f7f2993..6462c35 100644 --- a/src/execution/events.rs +++ b/src/execution/events.rs @@ -26,6 +26,7 @@ pub enum RunState { Cancelled, TimedOut, Unavailable, + Incomplete, } impl RunState { @@ -39,6 +40,7 @@ impl RunState { RunState::Cancelled => "cancelled", RunState::TimedOut => "timed_out", RunState::Unavailable => "unavailable", + RunState::Incomplete => "incomplete", } } @@ -52,6 +54,7 @@ impl RunState { RunState::Cancelled => "已取消", RunState::TimedOut => "超时", RunState::Unavailable => "不可用", + RunState::Incomplete => "事件流不完整", } } @@ -63,6 +66,7 @@ impl RunState { | RunState::Cancelled | RunState::TimedOut | RunState::Unavailable + | RunState::Incomplete ) } } @@ -73,6 +77,7 @@ pub enum EventKind { Complete, Error, Snapshot, + Observation, } impl EventKind { @@ -82,6 +87,7 @@ impl EventKind { EventKind::Complete => "run.complete", EventKind::Error => "run.error", EventKind::Snapshot => "run.snapshot", + EventKind::Observation => "run.observation", } } } @@ -98,6 +104,7 @@ pub struct RunEvent { pub trace: Option, /// `{code, message}` for terminal failures. pub error: Option, + pub observation: Option, } impl RunEvent { @@ -119,6 +126,9 @@ impl RunEvent { if let Some(error) = &self.error { data["error"] = error.clone(); } + if let Some(observation) = &self.observation { + data["observation"] = observation.clone(); + } data } @@ -180,6 +190,7 @@ impl EventLog { result: None, trace: None, error: None, + observation: None, }; self.next_seq += 1; self.last_state = state; @@ -213,6 +224,12 @@ impl EventLog { self.record(event) } + pub fn publish_observation(&mut self, observation: serde_json::Value) { + let mut event = self.next_event(EventKind::Observation, self.last_state); + event.observation = Some(observation); + self.record(event); + } + pub fn publish_complete( &mut self, result: serde_json::Value, @@ -276,6 +293,7 @@ impl EventLog { result: None, trace: None, error: None, + observation: None, } } diff --git a/src/execution/process.rs b/src/execution/process.rs index 3fcfd6d..5862003 100644 --- a/src/execution/process.rs +++ b/src/execution/process.rs @@ -85,7 +85,15 @@ pub fn run_bounded( budget: &ProcessBudget, cancel: Option>, ) -> ViewResult { - run_bounded_with_hook(bin, args, cwd, budget, cancel, Box::new(|| {})) + run_bounded_with_hook(bin, args, cwd, budget, cancel, ProcessHooks::default()) +} + +type StdoutReader = Box Captured + Send>; + +#[derive(Default)] +pub struct ProcessHooks { + pub on_spawn: Option>, + pub stdout: Option, } /// Same as [`run_bounded`], with a hook invoked exactly once **after** the @@ -96,7 +104,7 @@ pub fn run_bounded_with_hook( cwd: &Path, budget: &ProcessBudget, cancel: Option>, - on_spawn: Box, + hooks: ProcessHooks, ) -> ViewResult { let started = Instant::now(); let mut command = Command::new(bin); @@ -122,12 +130,17 @@ pub fn run_bounded_with_hook( let mut child = command.spawn().map_err(|err| ViewError::CoreSpawn { detail: format!("spawn {}: {err}", bin.display()), })?; - on_spawn(); + if let Some(on_spawn) = hooks.on_spawn { + on_spawn(); + } let stdout = child.stdout.take().expect("piped stdout"); let stderr = child.stderr.take().expect("piped stderr"); let stdout_cap = budget.max_stdout; let stderr_cap = budget.max_stderr; - let stdout_thread = std::thread::spawn(move || read_bounded(stdout, stdout_cap)); + let stdout_thread = std::thread::spawn(move || match hooks.stdout { + Some(read_stdout) => read_stdout(stdout), + None => read_bounded(stdout, stdout_cap), + }); let stderr_thread = std::thread::spawn(move || read_bounded(stderr, stderr_cap)); let deadline = started + budget.wall_clock; diff --git a/src/execution/request.rs b/src/execution/request.rs index 64de16d..bd483ca 100644 --- a/src/execution/request.rs +++ b/src/execution/request.rs @@ -111,6 +111,7 @@ pub enum ExecutionTarget { pub struct ExecutionPlan { pub document: SafeRelativePath, pub target: ExecutionTarget, + pub function_id: String, pub arguments: Vec<(String, String)>, pub mode: RunMode, pub grants: Grants, @@ -122,17 +123,17 @@ impl ValidatedRequest { /// Resolve the target and parameter names against the verified entry-module /// Analysis. Never accepts a dependency-module function id (RFC §6.3). pub fn plan_against(self, projection: &SemanticProjection) -> ViewResult { - let target = match &self.target { + let (target, function_id) = match &self.target { RunTarget::Entry => { - if resolve_main(projection).is_none() { + let Some(function) = resolve_main(projection) else { return Err(ViewError::NoEntryFunction { detail: format!( "{} 没有可调用的 main;请从函数面板选择一个 H2 Exec 函数", self.document ), }); - } - ExecutionTarget::Entry + }; + (ExecutionTarget::Entry, function.id.clone()) } RunTarget::Function { function_id } => { let function = projection @@ -153,12 +154,16 @@ impl ValidatedRequest { }; let label = canonical; validate_parameters(&self.parameters, projection, &function.id)?; - ExecutionTarget::Function { cli_name, label } + ( + ExecutionTarget::Function { cli_name, label }, + function.id.clone(), + ) } }; Ok(ExecutionPlan { document: self.document, target, + function_id, arguments: self .parameters .into_iter() @@ -201,7 +206,7 @@ pub fn validate_request(body: &[u8]) -> ViewResult { || function_id.chars().any(|ch| ch.is_control() || ch == '\0') { return Err(ViewError::RunInvalid { - detail: "function_id 必须来自 Analysis v2 且长度为 1..=512".to_string(), + detail: "function_id 必须来自 Analysis 且长度为 1..=512".to_string(), }); } } @@ -364,17 +369,21 @@ fn validate_glob(glob: &str) -> ViewResult<()> { /// Resolve `main` exactly like the frozen CLI does for `run`: canonical name /// first, then a unique local name. No fallback to any other function. -fn resolve_main(projection: &SemanticProjection) -> Option<(String, String)> { - if let Some(function) = projection.functions.iter().find(|function| { - canonical_name(&function.id, &projection.module_id) == "main" - || function.local_name == "main" - }) { - return Some(( - canonical_name(&function.id, &projection.module_id), - function.local_name.clone(), - )); - } - None +fn resolve_main( + projection: &SemanticProjection, +) -> Option<&crate::protocol::analysis_v2::SemanticFunction> { + projection + .functions + .iter() + .find(|function| canonical_name(&function.id, &projection.module_id) == "main") + .or_else(|| { + let mut candidates = projection + .functions + .iter() + .filter(|function| function.local_name == "main"); + let first = candidates.next()?; + candidates.next().is_none().then_some(first) + }) } fn unique_local_name(projection: &SemanticProjection, local_name: &str, id: &str) -> bool { diff --git a/src/protocol/execution_events_v1.rs b/src/protocol/execution_events_v1.rs new file mode 100644 index 0000000..0d7ba4c --- /dev/null +++ b/src/protocol/execution_events_v1.rs @@ -0,0 +1,355 @@ +//! Decode the CLI's bounded, source-bound NDJSON stream. The browser only +//! receives projections selected by this decoder. + +use base64::{engine::general_purpose::STANDARD, Engine}; +use serde::Deserialize; +use serde_json::{json, Value}; +use std::io::{BufRead, BufReader, Read}; + +const SCHEMA: &str = "marqdo.execution-events"; +const MAX_LINE: usize = 4 * 1024 * 1024; +const MAX_CHUNK: usize = 64 * 1024; +const MAX_TRANSPORT: usize = 16 * 1024 * 1024; + +pub struct Binding { + pub digest: String, + pub root: String, + pub entry: String, + pub function: String, + pub mode: String, + pub producer: String, + pub modules: Vec, + pub max_output: usize, +} + +#[derive(Default)] +pub struct Stream { + pub id: String, + pub verified: bool, + pub truncated: bool, + pub stdout: Vec, + pub stderr: Vec, + pub terminal: Option, + pub invalid: bool, +} + +#[derive(Deserialize)] +struct Event { + schema: String, + schema_version: u32, + run_id: String, + seq: u64, + kind: String, + payload: serde_json::Map, +} + +pub fn read(input: impl Read, binding: &Binding, mut publish: impl FnMut(Value)) -> Stream { + let mut input = BufReader::new(input); + let mut stream = Stream::default(); + let mut line = Vec::new(); + let mut total = 0; + let mut seq = 0; + let mut entry_frame_seen = false; + loop { + line.clear(); + let size = match input + .by_ref() + .take(MAX_LINE as u64 + 1) + .read_until(b'\n', &mut line) + { + Ok(0) => break, + Ok(size) => size, + Err(_) => { + stream.invalid = true; + break; + } + }; + total += size; + if total > MAX_TRANSPORT || size > MAX_LINE { + stream.invalid = true; + break; + } + if line.last() != Some(&b'\n') { + stream.invalid = true; + break; + } + let Ok(event) = serde_json::from_slice::(&line) else { + stream.invalid = true; + break; + }; + match consume(&mut stream, binding, event, seq, &mut entry_frame_seen) { + Ok(Some(projection)) => publish(projection), + Ok(None) => {} + Err(()) => { + stream.invalid = true; + break; + } + } + seq += 1; + } + if stream.invalid { + // Drain without keeping bytes so a malformed child cannot block on its pipe. + let _ = std::io::copy(&mut input, &mut std::io::sink()); + stream.terminal = None; + } + stream +} + +fn consume( + stream: &mut Stream, + binding: &Binding, + event: Event, + seq: u64, + entry_frame_seen: &mut bool, +) -> Result, ()> { + if event.schema != SCHEMA + || event.schema_version != 1 + || event.seq != seq + || event.run_id.is_empty() + || event.run_id.len() > 128 + || stream.terminal.is_some() + { + return Err(()); + } + let payload = &event.payload; + let kind = event.kind.as_str(); + if seq == 0 { + if kind != "stream.opened" + || payload.get("protocol") != Some(&json!({"name": SCHEMA, "schema_version": 1})) + || payload + .get("producer") + .and_then(|value| value["name"].as_str()) + != Some("marqdo") + || payload + .get("producer") + .and_then(|value| value["version"].as_str()) + != Some(&binding.producer) + || !payload.get("limits").is_some_and(Value::is_object) + || !payload.get("observation").is_some_and(Value::is_object) + { + return Err(()); + } + stream.id = event.run_id; + return Ok(Some(json!({"seq": seq, "kind": kind}))); + } + if stream.id != event.run_id { + return Err(()); + } + let mut projection = json!({"seq": seq, "kind": kind}); + if seq == 1 { + match kind { + "run.rejected" => { + if text(payload, "status") != Some("rejected") || text(payload, "phase").is_none() { + return Err(()); + } + stream.terminal = Some(failure(payload)?); + return Ok(None); + } + "run.started" => { + let source = payload.get("source").ok_or(())?; + if source["analysis_digest"].as_str() != Some(&binding.digest) + || source["root_id"].as_str() != Some(&binding.root) + || text(payload, "entry") != Some(&binding.entry) + || text(payload, "mode") != Some(&binding.mode) + { + return Err(()); + } + stream.verified = true; + return Ok(Some(projection)); + } + _ => return Err(()), + } + } + match kind { + "stream.opened" | "run.started" | "run.rejected" => return Err(()), + "stdout.chunk" | "stderr.chunk" => { + let data = text(payload, "data_base64").ok_or(())?; + if text(payload, "encoding") != Some("base64") || data.len() > MAX_CHUNK.div_ceil(3) * 4 + { + return Err(()); + } + let bytes = STANDARD.decode(data).map_err(|_| ())?; + if bytes.len() > MAX_CHUNK + || payload.get("byte_count").and_then(Value::as_u64) != Some(bytes.len() as u64) + { + return Err(()); + } + if stream.stdout.len() + stream.stderr.len() + bytes.len() > binding.max_output { + return Err(()); + } + if kind == "stdout.chunk" { + stream.stdout.extend_from_slice(&bytes); + } else { + stream.stderr.extend_from_slice(&bytes); + } + projection["data_base64"] = json!(data); + } + "run.completed" => { + let value = payload + .get("value") + .filter(|value| value["type"].is_string()) + .ok_or(())?; + if text(payload, "status") != Some("ok") || (!*entry_frame_seen && !stream.truncated) { + return Err(()); + } + stream.terminal = Some(json!({"success": true, "value": value})); + return Ok(None); + } + "run.failed" => { + if text(payload, "status") != Some("error") { + return Err(()); + } + stream.terminal = Some(failure(payload)?); + return Ok(None); + } + "observation.truncated" => { + if stream.truncated + || !matches!( + text(payload, "reason"), + Some("event_budget" | "byte_budget") + ) + || payload.get("limit").and_then(Value::as_u64).is_none() + || payload.get("written").and_then(Value::as_u64).is_none() + || !payload + .get("dropped") + .is_some_and(|value| value.is_null() || value.is_u64()) + { + return Err(()); + } + stream.truncated = true; + } + "call.enter" | "call.exit" | "return" | "branch.eval" | "loop.iteration" + | "control.break" | "control.continue" | "effect" => { + let module = text(payload, "module_id").ok_or(())?; + let span = payload.get("span").ok_or(())?; + let span_ok = span["start"] + .as_u64() + .zip(span["end"].as_u64()) + .is_some_and(|(start, end)| start < end); + if !binding.modules.iter().any(|known| known == module) + || !(span_ok + || span.is_null() && !matches!(kind, "control.break" | "control.continue")) + || kind != "effect" && text(payload, "frame_id").is_none() + { + return Err(()); + } + match kind { + "call.enter" => { + let function = text(payload, "function_id").ok_or(())?; + match payload.get("parent_frame_id") { + Some(Value::Null) if !*entry_frame_seen && function == binding.function => { + *entry_frame_seen = true + } + Some(Value::String(_)) if *entry_frame_seen => {} + _ => return Err(()), + } + } + "call.exit" if text(payload, "status").is_none() => return Err(()), + "return" if text(payload, "value_type").is_none() => return Err(()), + "branch.eval" => { + projection["decision"] = + json!(payload.get("result").and_then(Value::as_bool).ok_or(())?) + } + "loop.iteration" => { + let decision = text(payload, "decision") + .filter(|decision| matches!(*decision, "continue" | "exit")) + .ok_or(())?; + projection["decision"] = json!(decision); + } + "effect" + if text(payload, "operation").is_none() + || text(payload, "result_code").is_none() => + { + return Err(()) + } + _ => {} + } + } + // Values and additive kinds are never emitted as browser observations. + _ => return Ok(None), + } + Ok(Some(projection)) +} + +fn text<'a>(payload: &'a serde_json::Map, key: &str) -> Option<&'a str> { + payload + .get(key)? + .as_str() + .filter(|text| !text.is_empty() && text.len() <= MAX_LINE) +} + +fn failure(payload: &serde_json::Map) -> Result { + let error = payload.get("error").ok_or(())?; + let code = error["code"].as_str().ok_or(())?; + let message = error["message"].as_str().ok_or(())?; + Ok(json!({"success": false, "error": {"code": code, "message": message}})) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sample() -> (Binding, Vec) { + let binding = Binding { + digest: "sha256:expected".into(), + root: "root:p".into(), + entry: "root:p::index.mq.md::main".into(), + function: "root:p::index.mq.md::main".into(), + mode: "pure".into(), + producer: "3.0.0-rc.2".into(), + modules: vec!["root:p::index.mq.md".into()], + max_output: 100, + }; + let event = |seq, kind, payload| { + json!({"schema": SCHEMA, "schema_version": 1, "run_id": "r", "seq": seq, + "kind": kind, "payload": payload}) + }; + let events = vec![ + event( + 0, + "stream.opened", + json!({"protocol": {"name": SCHEMA, "schema_version": 1}, + "producer": {"name": "marqdo", "version": binding.producer}, "limits": {}, "observation": {}}), + ), + event( + 1, + "run.started", + json!({"entry": binding.entry, "mode": binding.mode, + "source": {"analysis_digest": binding.digest, "root_id": binding.root}}), + ), + event( + 2, + "stdout.chunk", + json!({"data_base64": "NAo=", "encoding": "base64", "byte_count": 2}), + ), + event( + 3, + "run.failed", + json!({"status": "error", "error": {"code": "runtime.test", "message": "test"}}), + ), + ]; + (binding, events) + } + + fn decode(binding: &Binding, events: &[Value]) -> Stream { + let ndjson = events + .iter() + .map(|value| format!("{value}\n")) + .collect::(); + read(ndjson.as_bytes(), binding, |_| {}) + } + + #[test] + fn validates_stream_identity_bytes_and_terminal_boundary() { + let (binding, mut events) = sample(); + let stream = decode(&binding, &events); + assert!(stream.verified && !stream.invalid); + assert_eq!(stream.stdout, b"4\n"); + assert!(stream.terminal.is_some()); + assert!(decode(&binding, &events[..3]).terminal.is_none()); + events[2]["payload"]["byte_count"] = json!(1); + assert!(decode(&binding, &events).invalid); + events[1]["payload"]["source"]["analysis_digest"] = json!("wrong"); + assert!(!decode(&binding, &events).verified); + } +} diff --git a/src/protocol/mod.rs b/src/protocol/mod.rs index 0c932d7..a2f68e9 100644 --- a/src/protocol/mod.rs +++ b/src/protocol/mod.rs @@ -4,5 +4,6 @@ //! second publisher or implementation of them (RFC-VIEW-0002 §5.3). pub mod analysis_v2; +pub mod execution_events_v1; pub mod tool_v1; pub mod trace_v2; diff --git a/src/server/mod.rs b/src/server/mod.rs index 09dae9c..6e5e38a 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -62,7 +62,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult { .unwrap_or(0) ); if let Some(version) = state.service.core_version() { - eprintln!("core: marqdo {version} (Analysis v2, Trace v2)"); + eprintln!("core: marqdo {version} (Analysis v2/v3, Trace v2)"); } else if let Some(note) = state.service.core_note() { eprintln!("core: unavailable ({note})"); } diff --git a/tests/contract/core_contract.rs b/tests/contract/core_contract.rs index da42b04..54dcb2a 100644 --- a/tests/contract/core_contract.rs +++ b/tests/contract/core_contract.rs @@ -249,13 +249,13 @@ fn cli_verify_end_to_end_against_fake_core() { } #[test] -fn cli_verify_rejects_schema_v3_and_digest_mismatch() { +fn cli_verify_rejects_schema_v4_and_digest_mismatch() { let (project, core) = fixture("verify_negative"); let source = std::fs::read(project.path("index.mq.md")).unwrap(); let script = core.script.to_str().unwrap().to_string(); let dir = project.dir.to_str().unwrap().to_string(); - core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); + core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4)); let output = common::run_view( &["verify", "index.mq.md", "--marqdo-bin", &script], std::path::Path::new(&dir), diff --git a/tests/contract/presentation_states.rs b/tests/contract/presentation_states.rs index 7479158..ac1fbe1 100644 --- a/tests/contract/presentation_states.rs +++ b/tests/contract/presentation_states.rs @@ -58,7 +58,7 @@ fn source_digest_mismatch_degrades_instead_of_misbinding() { fn unknown_analysis_schema_is_a_hard_protocol_error() { let (project, core) = project("state-protocol"); let source = std::fs::read(project.path("index.mq.md")).unwrap(); - core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 3)); + core.set_analysis(&minimal_analysis("index.mq.md", &sha256_hex(&source), 4)); let context = DocumentService::open(&project.dir, Some(&core.script)).unwrap(); let relative = context.project().entry().relative.clone(); let err = context.load(&relative).unwrap_err();