fix(runtime): resolve runtime errors against their logical module (B-08)

RuntimeError and CallFrame now carry a logical ModuleId and an origin
(source/callsite). Errors are attributed at function/body boundaries so the
innermost callee module wins; argument-binding errors and host/plugin/foreign
boundaries are attributed to the caller callsite without fabricating a foreign
stack.

The CLI resolves (module_id, span) through LoadedProject::locate instead of
indexing every span against the entry file. Unknown modules and out-of-range
spans keep the module id and byte span but emit null line/file. Human output and
frames now point at the correct file.

Record the decision in ADR-0017 and supersede the ADR-0006 limitation. Add an
end-to-end imported-module division-by-zero test.
This commit is contained in:
cflmy committed 2026-11-20 12:57:44 +08:00
1 parent 6fed396d20
commit 509bdb1bf6
8 files changed
+390 -38

No files matched your search

+77 -16
View File
@@ -897,22 +897,52 @@ fn load_plugin_into_host(
.map_err(|error| format!("{}: {}", error.code(), error.message))
}
fn runtime_error_json(error: &RuntimeError, project: &LoadedProject) -> serde_json::Value {
let entry = project.entry_file();
let span = error.span.map(|span| {
let position = marqdo_span::LineIndex::new(&entry.source).line_col(span.start);
json!({"line": position.line, "column": position.column, "file": entry.path.display().to_string()})
fn runtime_location_json(
project: &LoadedProject,
module_id: Option<&str>,
span: Option<marqdo_span::Span>,
) -> serde_json::Value {
let mut location = json!({
"module_id": module_id,
"span": span.map(|span| json!({"start": span.start, "end": span.end})),
});
if let (Some(module_id), Some(span)) = (module_id, span) {
if let Some(located) = project.locate(module_id, span) {
location["line"] = json!(located.line);
location["column"] = json!(located.column);
location["file"] = json!(located.file.path.display().to_string());
location["relative_path"] = json!(located.file.module_id.relative_path);
}
}
location
}
fn runtime_error_json(error: &RuntimeError, project: &LoadedProject) -> serde_json::Value {
let location = runtime_location_json(project, error.module_id.as_deref(), error.span);
let frames: Vec<serde_json::Value> = error
.frames
.iter()
.map(|frame| {
let mut value = runtime_location_json(project, frame.module_id.as_deref(), frame.span);
value["function"] = json!(frame.function);
value
})
.collect();
json!({
"code": error.code(),
"origin": error.origin,
"message": error.message,
"span": span,
"frames": error.frames,
"module_id": error.module_id,
"span": location["span"],
"line": location["line"],
"column": location["column"],
"file": location["file"],
"relative_path": location["relative_path"],
"frames": frames,
})
}
fn render_runtime_error(error: &RuntimeError, project: &LoadedProject) -> String {
let entry = project.entry_file();
let mut out = String::new();
out.push_str(&format!(
"runtime error[{}]: {}\n",
@@ -920,16 +950,47 @@ fn render_runtime_error(error: &RuntimeError, project: &LoadedProject) -> String
error.message
));
if let Some(span) = error.span {
let position = marqdo_span::LineIndex::new(&entry.source).line_col(span.start);
out.push_str(&format!(
" at {}:{}:{}\n",
entry.path.display(),
position.line,
position.column
));
match error
.module_id
.as_deref()
.and_then(|module| project.locate(module, span))
{
Some(located) => out.push_str(&format!(
" at {}:{}:{}\n",
located.file.path.display(),
located.line,
located.column
)),
None => out.push_str(&format!(
" at {}@{}..{}\n",
error.module_id.as_deref().unwrap_or("<unknown>"),
span.start,
span.end
)),
}
}
for frame in &error.frames {
out.push_str(&format!(" in function `{}`\n", frame.function));
out.push_str(&format!(" in function `{}`", frame.function));
if let Some(span) = frame.span {
match frame
.module_id
.as_deref()
.and_then(|module| project.locate(module, span))
{
Some(located) => out.push_str(&format!(
" at {}:{}:{}",
located.file.path.display(),
located.line,
located.column
)),
None => {
if let Some(module) = &frame.module_id {
out.push_str(&format!(" at {module}@{}..{}", span.start, span.end));
}
}
}
}
out.push('\n');
}
out
}
+28
View File
@@ -63,6 +63,16 @@ impl FileDiagnostic {
}
}
/// A resolved source location inside a loaded file.
pub struct LocatedSource<'a> {
/// The owning file.
pub file: &'a LoadedFile,
/// 1-based line.
pub line: usize,
/// 1-based column.
pub column: usize,
}
/// A fully loaded project ready for checking or running.
pub struct LoadedProject {
/// Project root.
@@ -92,6 +102,24 @@ impl LoadedProject {
&self.files[&self.entry]
}
/// Resolve a logical `(module_id, span)` location to a loaded file.
///
/// Returns `None` for an unknown module or an out-of-range span; callers
/// must not guess or fall back to the entry file.
pub fn locate(&self, module_id: &str, span: marqdo_span::Span) -> Option<LocatedSource<'_>> {
let module = ModuleId::parse(module_id).ok()?;
let file = self.files.get(&module)?;
if span.start > span.end || span.end > file.source.len() {
return None;
}
let position = marqdo_span::LineIndex::new(&file.source).line_col(span.start);
Some(LocatedSource {
file,
line: position.line,
column: position.column,
})
}
/// Resolve a physical path to its loaded or statically addressable module.
pub fn module_id_for_path(&self, path: &Path) -> Option<ModuleId> {
let canonical = path.canonicalize().ok()?;
+56
View File
@@ -683,3 +683,59 @@ fn plugin_inspect_and_explicit_trusted_invocation() {
assert!(stderr_text(&bad_args).contains("call.arity"));
assert!(stderr_text(&bad_args).contains("missing required argument `b`"));
}
#[test]
fn runtime_error_in_imported_module_reports_that_module() {
let dir = TempDir::new("cross-module-error");
dir.write(
"index.mq.md",
"---\nimport:\n physics: \"./physics.mq.md\"\n---\n\n## main\n\n> 打印(physics.boom())\n",
);
dir.write(
"physics.mq.md",
"## boom\n\n说明文字。\n\n**x = 1 / 0**\n\n*x*\n",
);
let output = cli(dir.path(), &["run", "index.mq.md", "--json"]);
assert_exit(&output, 1, "division by zero is a runtime error");
let value: serde_json::Value =
serde_json::from_str(&stdout_text(&output)).expect("run --json emits JSON");
let error = &value["error"];
assert_eq!(error["code"], "runtime.division_by_zero");
assert!(
error["module_id"]
.as_str()
.unwrap_or_default()
.ends_with("::physics.mq.md"),
"{}",
error["module_id"]
);
assert_eq!(error["relative_path"], "physics.mq.md");
assert!(
error["file"]
.as_str()
.unwrap_or_default()
.ends_with("physics.mq.md"),
"{}",
error["file"]
);
let line = error["line"].as_u64().unwrap_or(0);
assert!(line >= 5, "expected the failing statement line, got {line}");
assert!(
!error["file"]
.as_str()
.unwrap_or_default()
.ends_with("index.mq.md"),
"must not blame the entry file"
);
let human = cli(dir.path(), &["run", "index.mq.md"]);
assert_exit(&human, 1, "human rendering also fails");
let stderr = stderr_text(&human);
assert!(stderr.contains("physics.mq.md"), "{stderr}");
let primary = stderr
.lines()
.find(|line| line.trim_start().starts_with("at "))
.unwrap_or_default();
assert!(primary.contains("physics.mq.md"), "{primary}");
}
+74 -11
View File
@@ -95,6 +95,17 @@ impl<'a> Interpreter<'a> {
name: &str,
args: Vec<EvaluatedArg>,
call_span: Option<Span>,
) -> Result<Value, RuntimeError> {
self.call_by_name_from(module, name, args, call_span, None)
}
fn call_by_name_from(
&mut self,
module: &ModuleId,
name: &str,
args: Vec<EvaluatedArg>,
call_span: Option<Span>,
caller_module: Option<&ModuleId>,
) -> Result<Value, RuntimeError> {
let program = self.program;
let Some(target_module) = program.module(module) else {
@@ -111,7 +122,7 @@ impl<'a> Interpreter<'a> {
format!("unknown function `{name}` in module `{module}`"),
));
};
self.call_function(program, function, args, call_span)
self.call_function(program, function, args, call_span, caller_module)
}
fn call_function(
@@ -120,6 +131,7 @@ impl<'a> Interpreter<'a> {
function: &'a Function,
args: Vec<EvaluatedArg>,
call_span: Option<Span>,
caller_module: Option<&ModuleId>,
) -> Result<Value, RuntimeError> {
let display = function.id.name.clone();
let trace_id = function.id.to_string();
@@ -128,7 +140,15 @@ impl<'a> Interpreter<'a> {
}
self.host
.record_semantic("call.enter", Some(&trace_id), call_span, None);
let locals = self.bind_args(function, args, call_span)?;
let locals = match self.bind_args(function, args, call_span) {
Ok(locals) => locals,
Err(mut error) => {
if let Some(module) = caller_module {
error.attribute_module(module.canonical());
}
return Err(error);
}
};
let mut frame = Frame {
function: function.id.clone(),
namespace: function.namespace.clone(),
@@ -148,7 +168,12 @@ impl<'a> Interpreter<'a> {
Ok(Flow::Next) => Ok(Value::Unit),
Ok(Flow::Return(value)) => Ok(value),
Err(mut error) => {
error.push_frame(display, call_span);
error.attribute_module(function.id.module.canonical());
error.push_frame(
display,
call_span,
caller_module.map(|module| module.canonical()),
);
Err(error)
}
}
@@ -245,6 +270,20 @@ impl<'a> Interpreter<'a> {
program: &'a Program,
stmts: &'a [Stmt],
frame: &mut Frame,
) -> Result<Flow, RuntimeError> {
let module = frame.function.module.clone();
self.exec_stmts_inner(program, stmts, frame)
.map_err(|mut error| {
error.attribute_module(module.canonical());
error
})
}
fn exec_stmts_inner(
&mut self,
program: &'a Program,
stmts: &'a [Stmt],
frame: &mut Frame,
) -> Result<Flow, RuntimeError> {
for stmt in stmts {
self.host.consume_fuel(1, Some(stmt.span()))?;
@@ -357,7 +396,8 @@ impl<'a> Interpreter<'a> {
}
CallTarget::Resolved { module, function } => (module.clone(), function.clone()),
};
self.call_by_name(&module, &name, args, Some(span))
let caller = frame.function.module.clone();
self.call_by_name_from(&module, &name, args, Some(span), Some(&caller))
}
fn eval_args(
@@ -484,11 +524,12 @@ impl<'a> Interpreter<'a> {
span: Span,
frame: &mut Frame,
) -> Result<Value, RuntimeError> {
let caller_module = frame.function.module.clone();
match callee {
Expr::Ident(ident) => {
if let Some(value) = frame.locals.get(&ident.name).cloned() {
let args = self.eval_args(args, frame)?;
return self.call_value(program, value, args, Some(span));
return self.call_value(program, value, args, Some(span), Some(&caller_module));
}
if let Some(builtin) = builtins::find(&ident.name) {
let args = self.eval_args(args, frame)?;
@@ -505,7 +546,7 @@ impl<'a> Interpreter<'a> {
format!("unknown function `{}`", ident.name),
));
};
self.call_function(program, function, args, Some(span))
self.call_function(program, function, args, Some(span), Some(&caller_module))
}
Expr::Member { base, name, .. } => {
if let Expr::Ident(alias) = base.as_ref() {
@@ -521,7 +562,13 @@ impl<'a> Interpreter<'a> {
format!("unknown function `{name}` in module `{target_module}`"),
));
};
return self.call_function(program, function, args, Some(span));
return self.call_function(
program,
function,
args,
Some(span),
Some(&caller_module),
);
}
let qualified = format!("{}.{name}", alias.name);
if let Some(builtin) = builtins::find(&qualified) {
@@ -567,12 +614,24 @@ impl<'a> Interpreter<'a> {
}
let callee_value = self.eval_expr(callee, frame)?;
let args = self.eval_args(args, frame)?;
self.call_value(program, callee_value, args, Some(span))
self.call_value(
program,
callee_value,
args,
Some(span),
Some(&caller_module),
)
}
other => {
let callee_value = self.eval_expr(other, frame)?;
let args = self.eval_args(args, frame)?;
self.call_value(program, callee_value, args, Some(span))
self.call_value(
program,
callee_value,
args,
Some(span),
Some(&caller_module),
)
}
}
}
@@ -583,6 +642,7 @@ impl<'a> Interpreter<'a> {
callee: Value,
args: Vec<EvaluatedArg>,
span: Option<Span>,
caller_module: Option<&ModuleId>,
) -> Result<Value, RuntimeError> {
match callee {
Value::FunctionRef(reference) => {
@@ -597,7 +657,7 @@ impl<'a> Interpreter<'a> {
format!("function reference `{id}` does not exist"),
));
};
self.call_function(program, function, args, span)
self.call_function(program, function, args, span, caller_module)
}
other => Err(RuntimeError::new(
ErrorCategory::NotCallable,
@@ -633,7 +693,10 @@ impl<'a> Interpreter<'a> {
module: &ModuleId,
) -> Result<Value, RuntimeError> {
let context = ExecutionContext::new(module.to_string(), span);
self.host.invoke(op, args, &context)
self.host.invoke(op, args, &context).map_err(|mut error| {
error.mark_callsite();
error
})
}
}
+46 -4
View File
@@ -74,11 +74,27 @@ impl ErrorCategory {
}
}
/// Whether an error location points at Marqdo source or a host/plugin
/// callsite with no trustworthy internal stack.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorOrigin {
/// The error points at the Marqdo module and span.
#[default]
Source,
/// The error occurred at the Marqdo callsite of a host/plugin/foreign
/// operation; the callee's internal stack is unavailable.
Callsite,
}
/// One entry of the Marqdo call stack.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct CallFrame {
/// Canonical function name (or `<main>` for the entry function).
pub function: String,
/// Logical module containing the call site.
#[serde(skip_serializing_if = "Option::is_none")]
pub module_id: Option<Box<str>>,
/// Source location of the call site in the caller.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
@@ -89,11 +105,17 @@ pub struct CallFrame {
pub struct RuntimeError {
/// Failure category.
pub category: ErrorCategory,
/// Logical module containing [`Self::span`].
#[serde(skip_serializing_if = "Option::is_none")]
pub module_id: Option<Box<str>>,
/// Location in the source that caused the failure.
#[serde(skip_serializing_if = "Option::is_none")]
pub span: Option<Span>,
/// Whether the location is Marqdo source or a callsite.
#[serde(default)]
pub origin: ErrorOrigin,
/// Human readable message.
pub message: String,
pub message: Box<str>,
/// Call frames from innermost to outermost.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub frames: Vec<CallFrame>,
@@ -110,8 +132,10 @@ impl RuntimeError {
pub fn new(category: ErrorCategory, span: Option<Span>, message: impl Into<String>) -> Self {
Self {
category,
module_id: None,
span,
message: message.into(),
origin: ErrorOrigin::Source,
message: message.into().into_boxed_str(),
frames: Vec::new(),
cause: None,
effect_trace: Vec::new(),
@@ -123,10 +147,28 @@ impl RuntimeError {
Self::new(ErrorCategory::Type, span, message)
}
/// Attach a module identity if the error does not have one yet.
pub fn attribute_module(&mut self, module_id: impl Into<String>) {
if self.module_id.is_none() {
self.module_id = Some(module_id.into().into_boxed_str());
}
}
/// Mark this error as occurring at a host/plugin/foreign callsite.
pub fn mark_callsite(&mut self) {
self.origin = ErrorOrigin::Callsite;
}
/// Record a call frame (called while unwinding).
pub fn push_frame(&mut self, function: impl Into<String>, span: Option<Span>) {
pub fn push_frame(
&mut self,
function: impl Into<String>,
span: Option<Span>,
module_id: Option<String>,
) {
self.frames.push(CallFrame {
function: function.into(),
module_id: module_id.map(String::into_boxed_str),
span,
});
}
@@ -170,7 +212,7 @@ mod tests {
#[test]
fn frames_are_rendered_as_related_diagnostics() {
let mut err = RuntimeError::type_error(Some(Span::new(1, 2)), "expected Bool");
err.push_frame("阶乘", None);
err.push_frame("阶乘", None, None);
let diag = err.to_diagnostic();
assert_eq!(diag.code, "runtime.type");
assert_eq!(diag.related.len(), 1);
+18
View File
@@ -89,12 +89,30 @@ missing-edge fail-closed, root-manifest invalidation, strict sync without
`--locked`, full-closure env materialization, missing-lock and deleted-edge CLI
failures.
### S2-A/H1-B record (current)
Runtime errors now carry a logical source location (ADR-0017):
* `RuntimeError.module_id`, `origin` (`source`/`callsite`), and
`CallFrame.module_id`; attribution happens at function/module boundaries so
the innermost callee module wins.
* Host/plugin/foreign errors are marked as callsite errors without fabricating
a foreign stack.
* `LoadedProject::locate(module_id, span)` resolves the owning file and line;
the CLI no longer falls back to the entry file. Unknown modules or
out-of-range spans emit module/span with null line/file.
* Human and JSON output report the failing module; caller frames resolve their
own callsite modules.
* CLI test `runtime_error_in_imported_module_reports_that_module` reproduces
B-08 end to end with the real binary.
### M0.6 implementation progress
| Step | State | Evidence |
|---|---|---|
| S0/H0 CI baseline | **Done locally** | B-01 fixed in `crates/cli/tests/properties.rs`; fresh-clone path no longer needs an empty directory; full local gate green (see §S0/H0) |
| S1/H1-A lock v3 graph | **Done** | ADR-0016; full-closure `marqdo.lock` v3; fail-closed edge lookup; strict non-rewriting `sync`; verified Git cache; unified file-set profile (see §S1/H1-A) |
| S2-A/H1-B source locations | **Done** | ADR-0017; `RuntimeError`/`CallFrame` carry `module_id`; callsite origin; CLI module-aware resolution with no entry fallback (see §S2-A/H1-B) |
| R0 baseline + ADRs | **Done** | this section; `docs/adr/0008`–`0012`; full workspace gate |
| R1 package-aware identity + callable registry | **Done for statics; superseded by S1 lock v3** | `ModuleId { instance, relative_path }`; `PackageResolver` path sources; lock v3 transitive graph (ADR-0016) replaces the flat v2 lock; `CallableRegistry` for builtins/marqdo/declared ABI exports; external manifest wiring is R2 |
| R2 ABI/Kernel/Broker | **Done (worker = crash isolation)** | `KernelRegistry` external providers; complete-name export routing; `CapabilityBroker`; static `check --plugin`; multi-export C test; isolated worker with timeout/crash tests; host handle table. Native/worker are not an OS sandbox |
+9 -7
View File
@@ -108,11 +108,12 @@ implementation). Consumers should accept both names or key on the presence of
`diagnostics`/`value`; this is a known quirk.
`run`/`call` (failure): `{"command":"run","success":false,"stdout":...,
"error":{"code":"...","message":"...","span":{"line":..,"column":..,"file":..},
"frames":[...]},"trace":[...]}`. Runtime error spans are currently resolved
against the **entry file** only, even when the error came from an imported
module; frames carry function names, not module ids. This is a known precision
limitation.
"error":{"code":"...","origin":"source|callsite","module_id":"...",
"span":{"start":..,"end":..},"line":..,"column":..,"file":..,
"frames":[...]},"trace":[...]}`. Runtime locations are resolved against the
logical module that produced the error (ADR-0017); there is no entry-file
fallback. Unknown modules or invalid spans leave line/column/file null while
keeping the module id and byte span.
`plugin inspect`:
@@ -209,8 +210,9 @@ The CLI itself does not change the AST. What it exposes:
* `crates/cli/src/output.rs` has no unit tests; diagnostic JSON is exercised
through check/run smoke tests.
* Add contract tests for: exit codes per failure class, stdout/stderr
separation, JSON key presence, `call --json` command naming, and runtime
error span from a non-entry module before calling the schema "final".
separation, JSON key presence, `call --json` command naming. Runtime errors
from a non-entry module are covered by
`runtime_error_in_imported_module_reports_that_module` (ADR-0017).
## Migration & rollout
@@ -0,0 +1,82 @@
# ADR-0017: Runtime errors carry logical source locations
Status: **Accepted**
Date: 2026-11-20
Supersedes: the entry-file-only runtime span rule in ADR-0006
## Context
`Span` is a byte range in one source file. The interpreter produced spans in the
module where the failure occurred, but `RuntimeError` did not record which
module. The CLI therefore rendered every runtime error against the entry file
(`crates/cli/src/commands.rs`), so an error on line 5 of an imported module
could be reported at line 5 of `index.mq.md`, or with a meaningless column.
Span alone is not a source location. With package-aware `ModuleId`s (ADR-0008)
the logical location `(ModuleId, Span)` is available and stable across physical
paths and package instances.
## Decision
### 1. `RuntimeError` and `CallFrame` carry a logical module
`marqdo-value::RuntimeError` gains:
* `module_id: Option<String>` — canonical `ModuleId` containing `span`;
* `origin: ErrorOrigin` — `source` (Marqdo source) or `callsite` (host, plugin
or foreign boundary where no callee-internal stack exists).
`CallFrame` gains `module_id: Option<String>` for the callsite in the caller.
`push_frame(function, span, module_id)` records both.
### 2. Attribution happens at module boundaries, not at every constructor
* Every function body is executed with a known `FunctionId.module`. Errors
escaping `exec_stmts` get that module if they do not already have one, so
innermost callee attribution is preserved.
* Argument-binding errors are attributed to the caller module at the call site.
* Errors crossing a host/plugin/foreign boundary are marked `origin: callsite`
and attributed to the Marqdo callsite module. No foreign-internal stack is
fabricated.
* Existing `RuntimeError::new(category, span, message)` call sites remain valid;
attribution is additive.
### 3. CLI resolution has no entry-file fallback
`LoadedProject::locate(module_id, span)` parses the logical module, finds the
loaded file, rejects out-of-range spans, and derives line/column with that
file's `LineIndex`.
Runtime error JSON keeps `span: {start, end}` and adds `module_id`, `origin`,
`line`, `column`, `file`, `relative_path`. Each frame carries `function`,
`module_id`, `span`, and resolved line/column/file when available. If the
module is unknown or the span is invalid, the fields are absent/null and the
original module id and byte span are still emitted. Never clamp a span or fall
back to the entry file.
Human rendering prints the primary location from the located module. Frames
print their callsite file/line or the logical `module@start..end` when it cannot
be resolved.
Physical `file` fields are local convenience for humans; they are not part of
the versioned Analysis/Trace protocols and may differ across machines.
## Consequences
* Cross-module runtime diagnostics now point at the module that failed and
keep caller frames resolvable, including two package instances that share a
relative path.
* Span offsets remain UTF-8 byte offsets into that module's exact source.
* The JSON shape is additive for existing consumers; `span.line`/`span.file`
move to top-level `line`/`file` and are also duplicated per frame.
* Compile-time diagnostics already carried a module; this change brings runtime
errors to the same model.
* Any code constructing a synthetic `RuntimeError` without a module still
renders with an explicit `<unknown>` location rather than a guess.
## Tests
* `runtime_error_in_imported_module_reports_that_module` (CLI, real binary):
division by zero in an imported module reports that module's file and line,
both in JSON and human output; the callsite frame points at the entry file.
* Existing runtime/conformance tests continue to pass with additive fields.