Expose loop transfers through versioned public observations

This commit is contained in:
Codex committed 2026-11-23 19:47:24 +08:00
1 parent 69c5dc8d20
commit 71d29261a8
21 files changed
+486 -35

No files matched your search

+13
View File
@@ -351,6 +351,19 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
"span": span.map(span_json),
}),
),
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => (
transfer.event_kind(),
json!({
"frame_id": frame_id.as_wire(),
"module_id": module_id,
"span": span_json(span),
}),
),
ObservationEvent::Effect {
operation,
result_code,
+1 -1
View File
@@ -314,7 +314,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>,
/// Write the public Analysis v2 projection (only on successful check).
/// Write public Analysis JSON, using v3 for projects with loop transfers.
#[arg(long, value_name = "PATH")]
emit: Option<PathBuf>,
/// Machine readable JSON output.
+21 -10
View File
@@ -31,7 +31,10 @@ struct SupportedProtocols {
const SUPPORTED: SupportedProtocols = SupportedProtocols {
tool: PROTOCOL_VERSION,
analysis: &[2],
analysis: &[
crate::analysis::BASE_VERSION,
crate::analysis::LOOP_CONTROL_VERSION,
],
trace: &[2],
};
@@ -297,7 +300,7 @@ fn negotiate_protocol(
let Some(requested) = requested else {
return Ok(());
};
if requested.is_empty() || !requested.iter().any(|version| supported.contains(version)) {
if shared_version(requested, supported).is_none() {
return Err(format!(
"tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}"
));
@@ -305,6 +308,14 @@ fn negotiate_protocol(
Ok(())
}
fn shared_version(requested: &[u32], supported: &[u32]) -> Option<u32> {
requested
.iter()
.copied()
.filter(|version| supported.contains(version))
.max()
}
fn is_valid_command(command: &str) -> bool {
let mut bytes = command.bytes();
matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase())
@@ -623,21 +634,21 @@ pub fn dispatch(args: &[OsString]) -> i32 {
process.env("MARQDO_BIN", bin);
}
process.env("MARQDO_TOOL_PROTOCOL", "1");
if record
if let Some(version) = record
.compatibility
.analysis
.as_ref()
.is_some_and(|versions| versions.contains(&2))
.as_deref()
.and_then(|versions| shared_version(versions, SUPPORTED.analysis))
{
process.env("MARQDO_PROTOCOL_ANALYSIS", "2");
process.env("MARQDO_PROTOCOL_ANALYSIS", version.to_string());
}
if record
if let Some(version) = record
.compatibility
.trace
.as_ref()
.is_some_and(|versions| versions.contains(&2))
.as_deref()
.and_then(|versions| shared_version(versions, SUPPORTED.trace))
{
process.env("MARQDO_PROTOCOL_TRACE", "2");
process.env("MARQDO_PROTOCOL_TRACE", version.to_string());
}
match process.status() {
Ok(status) => status.code().unwrap_or(1),
+75
View File
@@ -460,3 +460,78 @@ fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
assert_eq!(result["value"]["decimal"], expected);
}
}
#[test]
fn an_imported_loop_transfer_selects_v3_and_keeps_the_else_if_call_edge() {
let dir = TempDir::new("imported-loop");
write(
dir.path(),
"gate.mq.md",
"## @exec enabled\n\n`while true`\n\n`break`\n\n`end`\n\n`return true`\n",
);
write(
dir.path(),
"index.mq.md",
r#"---
import:
gate: "./gate.mq.md"
---
## @exec main
`if false`
`return 0`
`else if gate.enabled()`
`return 1`
`end`
"#,
);
let result = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(result.status.success(), "{result:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 3);
let root = analysis["modules"]
.as_array()
.unwrap()
.iter()
.find(|module| module["relative_path"] == "index.mq.md")
.unwrap();
let calls = root["calls"].as_array().unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0]["state"], "function");
assert!(calls[0]["target"]
.as_str()
.unwrap()
.ends_with("::gate.mq.md::enabled"));
}
#[test]
fn invalid_loop_control_rejects_check_and_does_not_execute_the_function() {
let dir = TempDir::new("invalid-loop");
write(
dir.path(),
"index.mq.md",
"## @exec main\n\n`打印(\"unreachable output\")`\n\n`break`\n",
);
write(dir.path(), "stale.json", "previous output");
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "stale.json", "--json"],
);
assert_eq!(checked.status.code(), Some(1), "{checked:?}");
assert!(String::from_utf8_lossy(&checked.stdout).contains("sem.break_outside_loop"));
assert!(!String::from_utf8_lossy(&checked.stdout).contains("unreachable output"));
assert!(!dir.path().join("stale.json").exists());
let run = cli(dir.path(), &["run", "index.mq.md"]);
assert_eq!(run.status.code(), Some(1), "{run:?}");
assert!(run.stdout.is_empty());
}
+106
View File
@@ -765,3 +765,109 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
"expected a transport diagnostic on stderr: {stderr}"
);
}
#[test]
fn loop_transfers_are_ordered_structural_events_with_source_spans() {
use sha2::{Digest, Sha256};
let dir = TempDir::new("loop-transfers");
let source = r#"## @exec main
`索引 = 0`
`while true`
`索引 = 索引 + 1`
`if 索引 == 1`
`continue`
`else if 索引 == 2`
`break`
`end`
`end`
`return 索引`
"#;
dir.write("index.mq.md", source);
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(checked.status.success(), "{checked:?}");
let analysis_bytes = fs::read(dir.path().join("analysis.json")).unwrap();
let analysis: Value = serde_json::from_slice(&analysis_bytes).unwrap();
assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0];
let branch = &module["functions"][0]["body"][1]["body"][1];
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--mode",
"pure",
"--event-stream",
"jsonl",
"--trace-file",
"trace.json",
],
);
assert!(output.status.success(), "{output:?}");
let events = parse_events(&output.stdout);
assert_envelope(&events);
assert_eq!(events.last().unwrap()["kind"], "run.completed");
let trace: Value =
serde_json::from_slice(&fs::read(dir.path().join("trace.json")).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2);
assert_eq!(
trace["source"]["analysis_digest"],
format!("sha256:{:x}", Sha256::digest(analysis_bytes))
);
let kinds = |events: &[Value]| {
events
.iter()
.filter_map(|event| match event["kind"].as_str() {
Some("loop.iteration") => Some("loop.iteration"),
Some("control.continue") => Some("control.continue"),
Some("control.break") => Some("control.break"),
Some("return") => Some("return"),
_ => None,
})
.collect::<Vec<_>>()
};
let expected = [
"loop.iteration",
"control.continue",
"loop.iteration",
"control.break",
"return",
];
assert_eq!(kinds(&events), expected);
let trace_events = trace["events"].as_array().unwrap();
assert_eq!(kinds(trace_events), expected);
let frame = &events_of(&events, "call.enter")[0]["payload"]["frame_id"];
for (index, keyword) in ["continue", "break"].iter().enumerate() {
let kind = format!("control.{keyword}");
let carrier = format!("`{keyword}`");
let start = source.find(&carrier).unwrap();
let span = serde_json::json!({"start": start, "end": start + carrier.len()});
let payload = &events_of(&events, &kind)[0]["payload"];
assert_eq!(payload["frame_id"], *frame);
assert_eq!(payload["module_id"], module["id"]);
assert_eq!(payload["span"], span);
assert_eq!(payload.as_object().unwrap().len(), 3);
let event = &events_of(trace_events, &kind)[0];
assert_eq!(event["module_id"], module["id"]);
assert_eq!(event["span"], span);
assert!(event["detail"].is_null());
let statement = &branch["arms"][index]["body"][0];
assert_eq!(statement["kind"], *keyword);
assert_eq!(statement["span"], span);
}
}
+11
View File
@@ -376,6 +376,17 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
assert!(text.contains("analysis=2"), "{text}");
assert!(text.contains("trace=2"), "{text}");
let manifest = write_tool(dir.path(), "proto-v3", "");
let mut declared: serde_json::Value =
serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
declared["compatibility"]["analysis"] = serde_json::json!([2, 3]);
std::fs::write(&manifest, declared.to_string()).unwrap();
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let output = cli(&home, &["proto-v3"]);
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output));
assert!(stdout(&output).contains("analysis=3"));
for (compat, tag) in [
("\"analysis\":[99]", "analysis-disjoint"),
("\"analysis\":[]", "analysis-empty"),
+19
View File
@@ -1047,6 +1047,25 @@ impl Host for StdHost {
false,
)
}
RuntimeObservation::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => {
let Some(frame_id) = frame_id else {
return Ok(());
};
self.emit_observation(
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
},
false,
)
}
RuntimeObservation::VariableAssigned {
frame_id,
name,
+1 -1
View File
@@ -30,7 +30,7 @@ pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use observe::{
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
+34
View File
@@ -193,6 +193,13 @@ pub enum ObservationEvent<'a> {
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: FrameId,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// The host completed a controlled effect attempt.
Effect {
operation: &'a str,
@@ -230,6 +237,25 @@ pub enum ObservationEvent<'a> {
},
}
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Trace and Execution Events.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
///
/// Every variant carries an `Option<FrameId>`; observation of values and
@@ -257,6 +283,13 @@ pub enum RuntimeObservation<'a> {
module_id: &'a str,
span: Option<Span>,
},
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed.
VariableAssigned {
frame_id: Option<FrameId>,
@@ -498,6 +531,7 @@ pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
}
ObservationEvent::BranchEval { module_id, .. }
| ObservationEvent::LoopIteration { module_id, .. }
| ObservationEvent::LoopTransfer { module_id, .. }
| ObservationEvent::Effect { module_id, .. } => {
add_text(module_id);
if let ObservationEvent::LoopIteration { decision, .. } = event {
+10
View File
@@ -58,6 +58,10 @@ enum Recorded {
state: ValueState,
value: Option<serde_json::Value>,
},
LoopTransfer {
frame: FrameId,
kind: &'static str,
},
Effect {
operation: String,
result_code: String,
@@ -110,6 +114,12 @@ impl From<ObservationEvent<'_>> for Recorded {
frame: frame_id,
decision: decision.to_string(),
},
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Recorded::LoopTransfer {
frame: frame_id,
kind: transfer.event_kind(),
},
ObservationEvent::Effect {
operation,
result_code,
+31 -8
View File
@@ -4,7 +4,8 @@ use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{
ExecutionContext, FrameId, Host, HostOp, ParameterSource, ResourceRead, RuntimeObservation,
ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
RuntimeObservation,
};
use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt};
use marqdo_span::Span;
@@ -71,8 +72,7 @@ struct BoundArgs {
enum Flow {
Next,
Return(Value),
Break(Span),
Continue(Span),
LoopTransfer(LoopTransfer, Span),
}
/// Marqdo tree-walk interpreter.
@@ -232,7 +232,7 @@ impl<'a> Interpreter<'a> {
.and_then(|flow| match flow {
Flow::Next => Ok(None),
Flow::Return(value) => Ok(Some(value)),
Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new(
Flow::LoopTransfer(_, span) => Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
"loop control escaped its enclosing function",
@@ -420,8 +420,31 @@ impl<'a> Interpreter<'a> {
Stmt::Eval { expr, .. } => {
self.eval_expr(expr, frame)?;
}
Stmt::Break { span } => return Ok(Flow::Break(*span)),
Stmt::Continue { span } => return Ok(Flow::Continue(*span)),
Stmt::Break { span } | Stmt::Continue { span } => {
let transfer = if matches!(stmt, Stmt::Break { .. }) {
LoopTransfer::Break
} else {
LoopTransfer::Continue
};
let module = frame.function.module.canonical();
self.host.record_semantic(
transfer.event_kind(),
Some(&frame.function.to_string()),
Some(&module),
Some(*span),
None,
);
if self.observe {
self.host
.observe_runtime(RuntimeObservation::LoopTransfer {
frame_id: frame.id,
transfer,
module_id: &module,
span: *span,
})?;
}
return Ok(Flow::LoopTransfer(transfer, *span));
}
Stmt::Return { value, span } => {
let value = self.eval_expr(value, frame)?;
let module = frame.function.module.canonical();
@@ -515,8 +538,8 @@ impl<'a> Interpreter<'a> {
break;
}
match self.exec_stmts(program, body, frame)? {
Flow::Next | Flow::Continue(_) => {}
Flow::Break(_) => break,
Flow::Next | Flow::LoopTransfer(LoopTransfer::Continue, _) => {}
Flow::LoopTransfer(LoopTransfer::Break, _) => break,
flow @ Flow::Return(_) => return Ok(flow),
}
},
@@ -249,3 +249,46 @@ fn memory_budget_is_enforced_without_changing_the_region() {
.unwrap_err();
assert_eq!(error.code(), "resource.exhausted");
}
#[test]
fn continue_obeys_fuel_and_wall_clock_budgets() {
use std::time::{Duration, Instant};
let source = "## @exec main\n\n`while true`\n\n`continue`\n\n`end`\n";
let program = build(source);
let module = ModuleId::from("index.mq.md");
let mut fuel_host = host();
fuel_host.budget.fuel = 20;
let fuel = run(&program, &mut fuel_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(fuel.code(), "resource.exhausted");
assert!(fuel.message.contains("fuel exhausted"));
let mut deadline_host = host();
deadline_host.budget.fuel = u64::MAX;
deadline_host.budget.deadline = Some(Instant::now() + Duration::from_millis(25));
let timeout = run(&program, &mut deadline_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(timeout.code(), "resource.exhausted");
assert!(timeout.message.contains("wall-clock time limit"));
}
#[test]
fn malformed_ir_cannot_transfer_into_the_callers_loop() {
let source =
"## @exec child\n\n`return 1`\n\n## @exec main\n\n`while true`\n\n`child()`\n\n`end`\n";
let mut program = build(source);
let module = ModuleId::from("index.mq.md");
let child = program
.modules
.get_mut(&module)
.unwrap()
.functions
.iter_mut()
.find(|function| function.id.name == "child")
.unwrap();
let span = child.body[0].span();
child.body[0] = marqdo_ir::Stmt::Break { span };
let error = run(&program, &mut host(), &module, "main", Vec::new()).unwrap_err();
assert_eq!(error.category, marqdo_value::ErrorCategory::Internal);
assert_eq!(error.span, Some(span));
}
@@ -93,6 +93,18 @@ impl ObservationSink for Recorder {
source: None,
decision: decision.to_string(),
},
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Seen {
kind: transfer.event_kind(),
frame: Some(frame_id.0),
name: String::new(),
value_type: String::new(),
state: None,
wire: None,
source: None,
decision: String::new(),
},
ObservationEvent::VariableAssigned {
frame_id,
name,