feat: stream verified Core execution events over the View SSE channel
This commit is contained in:
1 parent
4cf500fb58
commit
37291137eb
13 files changed
+593
-39
No files matched your search
+10
-1
@@ -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<u64>,
|
||||
@@ -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<OsString>, 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()],
|
||||
|
||||
+126
-11
@@ -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<String, DedupeEntry>,
|
||||
}
|
||||
|
||||
struct CoreRun {
|
||||
process: ProcessOutcome,
|
||||
trace: Option<Vec<u8>>,
|
||||
stream: Option<core_events::Stream>,
|
||||
}
|
||||
|
||||
pub struct ExecutionController {
|
||||
service: Arc<DocumentService>,
|
||||
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<Job>,
|
||||
plan: &ExecutionPlan,
|
||||
) -> Result<(ProcessOutcome, Option<Vec<u8>>), ViewError> {
|
||||
static_doc: &StaticDocument,
|
||||
) -> ViewResult<CoreRun> {
|
||||
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<Vec<u8>>), ViewError>,
|
||||
outcome: ViewResult<CoreRun>,
|
||||
cancel_requested: bool,
|
||||
) -> (
|
||||
RunState,
|
||||
@@ -410,7 +466,11 @@ impl ExecutionController {
|
||||
Option<String>,
|
||||
) {
|
||||
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::<serde_json::Value>(&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!({
|
||||
|
||||
@@ -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<serde_json::Value>,
|
||||
/// `{code, message}` for terminal failures.
|
||||
pub error: Option<serde_json::Value>,
|
||||
pub observation: Option<serde_json::Value>,
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -85,7 +85,15 @@ pub fn run_bounded(
|
||||
budget: &ProcessBudget,
|
||||
cancel: Option<Arc<AtomicBool>>,
|
||||
) -> ViewResult<ProcessOutcome> {
|
||||
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<dyn FnOnce(std::process::ChildStdout) -> Captured + Send>;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ProcessHooks {
|
||||
pub on_spawn: Option<Box<dyn FnOnce() + Send>>,
|
||||
pub stdout: Option<StdoutReader>,
|
||||
}
|
||||
|
||||
/// 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<Arc<AtomicBool>>,
|
||||
on_spawn: Box<dyn FnOnce() + Send>,
|
||||
hooks: ProcessHooks,
|
||||
) -> ViewResult<ProcessOutcome> {
|
||||
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;
|
||||
|
||||
+26
-17
@@ -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<ExecutionPlan> {
|
||||
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<ValidatedRequest> {
|
||||
|| 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 {
|
||||
|
||||
@@ -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<String>,
|
||||
pub max_output: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Stream {
|
||||
pub id: String,
|
||||
pub verified: bool,
|
||||
pub truncated: bool,
|
||||
pub stdout: Vec<u8>,
|
||||
pub stderr: Vec<u8>,
|
||||
pub terminal: Option<Value>,
|
||||
pub invalid: bool,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Event {
|
||||
schema: String,
|
||||
schema_version: u32,
|
||||
run_id: String,
|
||||
seq: u64,
|
||||
kind: String,
|
||||
payload: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
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::<Event>(&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<Option<Value>, ()> {
|
||||
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<String, Value>, 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<String, Value>) -> Result<Value, ()> {
|
||||
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<Value>) {
|
||||
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::<String>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
+1
-1
@@ -62,7 +62,7 @@ pub fn serve(service: DocumentService, opts: &RuntimeOpts) -> ViewResult<i32> {
|
||||
.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})");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user