observation: deliver one execution event sequence to stream and snapshot

This commit is contained in:
Codex committed 2026-11-24 15:30:18 +08:00
1 parent f83d992c61
commit 404d559b86
97 files changed
+2672 -3128

No files matched your search

+3 -5
View File
@@ -76,11 +76,9 @@ fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
.map_err(|error| format!("cannot encode analysis: {error}"))
}
/// SHA-256 of the exact emitted Analysis bytes (Trace binds to this digest).
pub fn digest(project: &LoadedProject) -> String {
encode(project)
.map(|bytes| sha256_hex(&bytes))
.unwrap_or_else(|_| sha256_hex(b""))
/// SHA-256 of the exact emitted Analysis bytes.
pub fn digest(project: &LoadedProject) -> Result<String, String> {
encode(project).map(|bytes| format!("sha256:{}", sha256_hex(&bytes)))
}
/// Atomically write the projection. An error must not leave a stale success
+44 -57
View File
@@ -29,6 +29,7 @@ pub use tool::{fmt, plugin_inspect};
use crate::args;
use crate::extension_descriptors::{self, StaticPluginSet};
use crate::loader::{FileDiagnostic, LoadedProject};
use crate::observation::ObservationSession;
use crate::output;
use crate::project_prepare::{self, PrepareOptions, PreparedProgram};
@@ -217,25 +218,6 @@ fn resolve_link(
}
}
/// Re-execute this CLI inside the strict Linux supervisor.
/// Emit one CLI error through the requested channel.
///
/// `--json` consumers require exactly one JSON document; human mode keeps the
/// conventional `error:` line on stderr. This helper is shared with the run
/// assembly so every strict control-plane failure follows one contract.
pub(super) fn emit_error(json: bool, command_name: &str, code: &str, message: &str) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": message,
"code": code,
}));
} else {
eprintln!("error: {message}");
}
}
/// Machine-readable routing decision for one captured strict execution.
#[derive(Debug, PartialEq, Eq)]
enum StrictRoute {
@@ -247,17 +229,15 @@ enum StrictRoute {
/// Classify a captured strict execution.
///
/// A strict child in `--json` mode must produce exactly one JSON document on
/// stdout. Anything else is a control-plane failure: forwarding bwrap text or
/// an empty stream would break the CLI protocol (the GitHub-hosted Linux CI
/// failure that motivated this contract).
fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
/// Machine output is forwarded only if the child emitted one complete
/// current Observation snapshot whose terminal agrees with the exit status.
fn classify_strict_outcome(outcome: &StrictOutcome, snapshot: bool) -> StrictRoute {
let exit_code = outcome.exit_code.unwrap_or(1);
if !json {
if !snapshot {
return StrictRoute::Forward { exit_code };
}
if !outcome.stdout.is_empty()
&& serde_json::from_slice::<serde_json::Value>(&outcome.stdout).is_ok()
if outcome.exit_code.is_some()
&& crate::observation::is_complete_snapshot(&outcome.stdout, exit_code)
{
return StrictRoute::Forward { exit_code };
}
@@ -277,33 +257,39 @@ fn classify_strict_outcome(outcome: &StrictOutcome, json: bool) -> StrictRoute {
}
StrictRoute::Failure {
code: "strict.child_invalid",
message: "the strict child did not produce exactly one JSON document; refusing to forward partial output"
message: "the strict child did not produce exactly one JSON observation snapshot"
.to_string(),
}
}
/// Route one captured strict execution to stdout/stderr or one error document.
fn route_strict_outcome(outcome: StrictOutcome, json: bool, command_name: &str) -> i32 {
/// Route captured child bytes through the selected output contract.
fn route_strict_outcome(outcome: StrictOutcome, observation: Option<&ObservationSession>) -> i32 {
use std::io::Write;
match classify_strict_outcome(&outcome, json) {
match classify_strict_outcome(&outcome, observation.is_some()) {
StrictRoute::Forward { exit_code } => {
let _ = std::io::stdout().write_all(&outcome.stdout);
let _ = std::io::stdout().flush();
let mut stdout = std::io::stdout().lock();
if let Err(error) = stdout
.write_all(&outcome.stdout)
.and_then(|()| stdout.flush())
{
return run::transport_failure(&error.to_string());
}
let _ = std::io::stderr().write_all(&outcome.stderr);
let _ = std::io::stderr().flush();
exit_code
}
StrictRoute::Failure { code, message } => {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": message,
"code": code,
}));
match outcome.exit_code {
Some(code) if code != 0 => code,
_ => 1,
eprintln!("error[{code}]: {message}");
if let Some(observation) = observation {
let result = if code == "strict.namespace_failure" {
observation.rejected("strict", code, &message)
} else {
observation.incomplete()
};
if let Err(error) = result {
return run::transport_failure(&error);
}
}
outcome.exit_code.filter(|code| *code != 0).unwrap_or(1)
}
}
}
@@ -312,22 +298,26 @@ fn launch_strict_process(
project_root: &Path,
document: Option<&Path>,
settings: &SandboxSettings,
json: bool,
command_name: &str,
observation: Option<&ObservationSession>,
) -> i32 {
let program = match std::env::current_exe() {
Ok(path) => path,
Err(error) => {
let message = format!("cannot locate the marqdo executable: {error}");
emit_error(json, command_name, "strict.launch_failed", &message);
return 1;
return run::fail(observation, "strict", "strict.launch_failed", &message, 1);
}
};
let args: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let output_limit = settings
let program_output_limit = settings
.max_output
.unwrap_or(1024 * 1024)
.min(64 * 1024 * 1024);
.unwrap_or(marqdo_host::DEFAULT_OUTPUT_BYTES);
let output_limit = if observation.is_some() {
// Allow framing and runtime observations within the existing
// supervisor capture ceiling. The child's program budget still applies.
64 * 1024 * 1024
} else {
program_output_limit.min(64 * 1024 * 1024)
};
let timeout = Duration::from_secs(settings.timeout.unwrap_or(30));
let stdlib_dir = crate::stdlib::StdlibBundle::discover()
.ok()
@@ -344,11 +334,8 @@ fn launch_strict_process(
stdlib_dir: stdlib_dir.as_deref(),
};
match marqdo_sandbox::launch_strict_capture(&command) {
Ok(outcome) => route_strict_outcome(outcome, json, command_name),
Err(error) => {
emit_error(json, command_name, error.code(), &error.to_string());
1
}
Ok(outcome) => route_strict_outcome(outcome, observation),
Err(error) => run::fail(observation, "strict", error.code(), &error.to_string(), 1),
}
}
@@ -544,7 +531,7 @@ mod tests {
#[test]
fn strict_json_success_is_forwarded_once() {
let route = classify_strict_outcome(
&outcome(Some(0), None, br#"{"command":"run","success":true}"#, b""),
&outcome(Some(0), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"ok"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.completed","payload":{"status":"ok"}}]}"#, b""),
true,
);
assert_eq!(route, StrictRoute::Forward { exit_code: 0 });
@@ -553,7 +540,7 @@ mod tests {
#[test]
fn strict_json_program_error_is_forwarded_unchanged() {
let route = classify_strict_outcome(
&outcome(Some(2), None, br#"{"command":"run","success":false}"#, b""),
&outcome(Some(2), None, br#"{"schema":"marqdo.observation","schema_version":1,"run":{"id":"r","status":"error"},"capture":{},"events":[{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":0,"kind":"stream.opened","payload":{}},{"schema":"marqdo.observation","schema_version":1,"run_id":"r","seq":1,"kind":"run.failed","payload":{"status":"error"}}]}"#, b""),
true,
);
assert_eq!(route, StrictRoute::Forward { exit_code: 2 });
+97 -301
View File
@@ -4,46 +4,59 @@
//! runtime helpers, but keeps the run session out of the command table.
use super::*;
use crate::execution_events::{EventStream, ObservationOptions};
use crate::observation::{ObservationOptions, ObservationSession, OutputFormat};
use crate::provider_manifest;
use marqdo_sandbox::StrictChildState;
pub fn execute(
file: Option<&Path>,
function: Option<&str>,
named_args: &[(String, Value)],
named_args: Result<Vec<(String, Value)>, String>,
settings: &SandboxSettings,
json: bool,
trace: bool,
observation: Option<&ObservationOptions>,
observation: &ObservationOptions,
) -> i32 {
let command_name = if function.is_some() { "call" } else { "run" };
// Open the dedicated protocol channel before any project work so prepare
// and authorization failures can still produce `run.rejected`.
let events = match observation {
Some(options) => match EventStream::open(options) {
Ok(stream) => Some(stream),
Err(error) => {
eprintln!("error[observe.transport_failed]: {error}");
return 1;
}
},
None => None,
};
let stream = events.as_ref();
let prepared = if stream.is_some() {
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, json, command_name, "prepare", &error),
if !observation.enabled() && observation.has_capture_overrides() {
eprintln!(
"error: capture options require --output json, --output jsonl or --observation-file"
);
return 2;
}
// Open before preparation so option, compile and authorization failures
// can still publish a rejection on the requested observation destination.
let strict_destination_rejected = settings.mode == "strict"
&& (observation.output == OutputFormat::Jsonl || observation.file.is_some());
let mut destinations = observation.clone();
if strict_destination_rejected {
destinations.file = None;
}
let events = if destinations.enabled() {
match ObservationSession::open(&destinations) {
Ok(events) => Some(events),
Err(error) => return transport_failure(&error),
}
} else {
match prepare_project(file, json, &settings.plugins) {
Ok(prepared) => prepared,
Err(code) => return code,
}
None
};
let stream = events.as_ref();
if strict_destination_rejected {
return fail(
stream,
"strict",
"strict.unsupported_grant",
"strict mode supports text and JSON snapshots on stdout; it rejects live or file destinations",
2,
);
}
let named_args = match named_args {
Ok(args) => args,
Err(message) => return fail(stream, "prepare", "cli.invalid_argument", &message, 2),
};
let options = PrepareOptions {
plugins: settings.plugins.clone(),
};
let prepared = match project_prepare::prepare(file, &options) {
Ok(prepared) => prepared,
Err(error) => return fail_prepare(stream, "prepare", &error),
};
let extension_sources = prepared.loaded.extension_sources.clone();
let project = prepared.loaded;
@@ -64,16 +77,8 @@ pub fn execute(
return transport_failure(&error);
}
}
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"diagnostics": output::diagnostics_json(&project.diagnostics),
}));
} else {
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
}
eprint!("{}", output::render_text(&project.diagnostics));
eprintln!("error: refusing to run a project with compile errors");
return 1;
}
let warnings: Vec<FileDiagnostic> = project
@@ -82,21 +87,13 @@ pub fn execute(
.filter(|item| !item.diagnostic.is_error())
.cloned()
.collect();
if !json && !warnings.is_empty() {
if !warnings.is_empty() {
eprint!("{}", output::render_text(&warnings));
}
let mode = match settings.sandbox_mode() {
Ok(mode) => mode,
Err(error) => {
return fail(
stream,
json,
command_name,
"authorization",
"cli.invalid_mode",
&error,
2,
);
return fail(stream, "authorization", "cli.invalid_mode", &error, 2);
}
};
// A project-declared extension is activation, not authorization, but it is
@@ -115,15 +112,7 @@ pub fn execute(
marqdo_package::MANIFEST_FILE,
settings.mode
);
return fail(
stream,
json,
command_name,
"authorization",
code,
&message,
2,
);
return fail(stream, "authorization", code, &message, 2);
}
let mut kernel_paths = settings.kernels.clone();
kernel_paths.extend(
@@ -144,28 +133,8 @@ pub fn execute(
provider_paths.sort();
provider_paths.dedup();
if mode == SandboxMode::Strict {
if stream.is_some() {
return fail(
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
"--event-stream jsonl is not supported under --mode strict; strict refuses \
trace/event artifacts and never downgrades to project mode",
2,
);
}
if let Err(error) = settings.strict_preflight() {
return fail(
stream,
json,
command_name,
"strict",
"strict.unsupported_grant",
&error,
2,
);
return fail(stream, "strict", "strict.unsupported_grant", &error, 2);
}
match marqdo_sandbox::inspect_strict_child() {
// A verified supervisor child may run project code.
@@ -174,32 +143,16 @@ pub fn execute(
Ok(StrictChildState::NotChild) => {
let platform = PlatformCapabilities::detect();
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(
stream,
json,
command_name,
"strict",
error.code(),
&error.to_string(),
1,
);
return fail(stream, "strict", error.code(), &error.to_string(), 1);
}
return launch_strict_process(&project.root, file, settings, json, command_name);
return launch_strict_process(&project.root, file, settings, stream);
}
// A marker without a verified identity is never trusted, and the
// platform-neutral inspection keeps Linux-only symbols out of this
// module so macOS/Windows builds compile.
Err(reason) => {
let message = format!("strict isolation verification failed: {reason}");
return fail(
stream,
json,
command_name,
"strict",
"strict.identity_invalid",
&message,
1,
);
return fail(stream, "strict", "strict.identity_invalid", &message, 1);
}
}
}
@@ -207,8 +160,6 @@ pub fn execute(
if let Err(error) = marqdo_sandbox::enforce(mode, &platform) {
return fail(
stream,
json,
command_name,
"authorization",
"sandbox.unavailable",
&error.to_string(),
@@ -218,15 +169,7 @@ pub fn execute(
let capabilities = match settings.capabilities() {
Ok(capabilities) => capabilities,
Err(error) => {
return fail(
stream,
json,
command_name,
"authorization",
"cli.invalid_grants",
&error,
2,
);
return fail(stream, "authorization", "cli.invalid_grants", &error, 2);
}
};
let stdin = read_stdin();
@@ -234,18 +177,6 @@ pub fn execute(
if let Some(stream) = stream {
host = host.with_observation(stream.config(), Box::new(stream.host_sink()));
}
if trace || json || settings.trace_file.is_some() {
host = host
.with_trace()
.with_trace_budget(marqdo_host::TraceBudget {
max_events: settings
.trace_max_events
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_EVENTS),
max_bytes: settings
.trace_max_bytes
.unwrap_or(marqdo_host::trace::DEFAULT_MAX_TRACE_BYTES),
});
}
if let Some(fuel) = settings.fuel {
host.budget.fuel = fuel;
}
@@ -260,15 +191,7 @@ pub fn execute(
}
for kernel_path in &kernel_paths {
if let Err(error) = load_kernel_descriptor(&mut host, kernel_path) {
return fail(
stream,
json,
command_name,
"prepare",
"ext.kernel_load_failed",
&error,
2,
);
return fail(stream, "prepare", "ext.kernel_load_failed", &error, 2);
}
}
// T6: verify every selected artifact/path/hash before starting a worker or
@@ -282,7 +205,7 @@ pub fn execute(
let providers = match provider_manifest::read_provider_manifests(&provider_paths) {
Ok(providers) => providers,
Err(error) => {
return fail_prepare(stream, json, command_name, "prepare", &error);
return fail_prepare(stream, "prepare", &error);
}
};
// `--provider` alone never authorizes; the exact `--allow-provider NAME`
@@ -302,7 +225,7 @@ pub fn execute(
provider.name, provider.name
),
);
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
// A grant that matches no selected provider is a deterministic option
@@ -317,7 +240,7 @@ pub fn execute(
providers are never discovered automatically"
),
);
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
for plugin in &static_plugins.plugins {
@@ -325,17 +248,16 @@ pub fn execute(
&plugin.base_dir,
&plugin.artifact_relative,
) {
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
let artifact = plugin.artifact_path();
if let Err(error) = extension_descriptors::verify_sha256(&artifact, &plugin.artifact_sha256)
{
return fail_prepare(stream, json, command_name, "authorization", &error);
return fail_prepare(stream, "authorization", &error);
}
}
// A native plugin shares this process and can write fd 1 directly, so it
// can pollute the JSONL channel. Fail closed rather than presenting
// untrusted raw bytes as program stdout (RFC-OBS-0001 §4.4/§9.2, T26).
// An in-process native plugin can write directly to the inherited fds.
// Require a controlled channel before publishing observed program bytes.
if stream.is_some()
&& static_plugins
.plugins
@@ -344,12 +266,9 @@ pub fn execute(
{
return fail(
stream,
json,
command_name,
"authorization",
"ext.event_stream_unsupported_native_plugin",
"--event-stream jsonl cannot guarantee a clean channel with an in-process native \
plugin; use a worker plugin or disable event mode",
"ext.observation_unsupported_native_plugin",
"observation requires a controlled output channel; use a worker plugin or text output without a snapshot",
2,
);
}
@@ -362,8 +281,6 @@ pub fn execute(
) {
return fail(
stream,
json,
command_name,
"authorization",
"ext.plugin_load_failed",
&message,
@@ -376,8 +293,6 @@ pub fn execute(
if let Err(message) = reconcile_plugin_exports(&static_plugins, &host) {
return fail(
stream,
json,
command_name,
"authorization",
"ext.plugin_binding_mismatch",
&message,
@@ -393,7 +308,7 @@ pub fn execute(
provider,
&settings.allow_provider,
) {
return fail_prepare(stream, json, command_name, "prepare", &error);
return fail_prepare(stream, "prepare", &error);
}
}
let function_name = function.unwrap_or("main").to_string();
@@ -411,15 +326,7 @@ pub fn execute(
project.entry_file().path.display()
)
};
return fail(
stream,
json,
command_name,
"compile",
"sem.no_entry_function",
&message,
1,
);
return fail(stream, "compile", "sem.no_entry_function", &message, 1);
}
let runtime_args: Vec<EvaluatedArg> = named_args
.iter()
@@ -435,7 +342,10 @@ pub fn execute(
};
if let Some(stream) = stream {
let entry = format!("{}::{}", project.entry, function_name);
let analysis_digest = format!("sha256:{}", crate::analysis::digest(&project));
let analysis_digest = match crate::analysis::digest(&project) {
Ok(digest) => digest,
Err(error) => return fail(Some(stream), "prepare", "cli.analysis_failed", &error, 1),
};
if let Err(error) = stream.started(
&entry,
mode.as_str(),
@@ -445,7 +355,7 @@ pub fn execute(
return transport_failure(&error);
}
}
let mut result = run_with_limits(
let result = run_with_limits(
&project.program,
&mut host,
&project.entry,
@@ -453,128 +363,45 @@ pub fn execute(
runtime_args,
memory_limits,
);
// A dead event pipe is a run failure even if the program itself returned.
if result.is_ok() {
if let Some(message) = host.observation_failure() {
result = Err(RuntimeError::new(
marqdo_value::ErrorCategory::Observation,
None,
format!("observe.transport_failed: {message}"),
));
}
}
let trace_run_id = stream.map(EventStream::run_id);
if let Some(path) = &settings.trace_file {
let status = match &result {
Ok(_) => "ok",
Err(error) => error.code(),
};
let entry = format!("{}::{}", project.entry, function_name);
if let Err(error) = crate::trace::write(
&project,
&host,
&entry,
status,
path,
trace_run_id.as_deref(),
) {
if let Some(stream) = stream {
let _ = stream.failed_error("cli.trace_failed", &error);
} else {
emit_error(json, command_name, "cli.trace_failed", &error);
}
return 1;
}
}
if let Some(stream) = stream {
// The program's stdout/stderr were already emitted as chunk events at
// their real host commit points; never replay them on this channel.
match &result {
Ok(outcome) => {
if let Err(error) = stream.completed(&outcome.value) {
return transport_failure(&error);
}
}
Err(error) => {
if let Err(write_error) = stream.failed(error) {
eprintln!("error[observe.transport_failed]: {write_error}");
}
eprint!("{}", render_runtime_error(error, &project));
return 1;
}
if let Some(error) = host.observation_failure() {
return transport_failure(error);
}
let delivered = match &result {
Ok(outcome) => stream.completed(&outcome.value),
Err(error) => stream.failed(runtime_error_json(error, &project)),
};
if let Err(error) = delivered {
return transport_failure(&error);
}
return 0;
}
let stdout = host.take_output();
let stdout_text = String::from_utf8_lossy(&stdout).to_string();
let stderr = host.take_error();
let stderr_text = String::from_utf8_lossy(&stderr).to_string();
let trace_entries = host.trace().to_vec();
match result {
Ok(outcome) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": true,
"value": marqdo_value::to_wire(&outcome.value),
"stdout": stdout_text,
"stderr": stderr_text,
"diagnostics": output::diagnostics_json(&project.diagnostics),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
if function.is_some() && outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
if trace {
for entry in &trace_entries {
eprintln!(
"trace: {} {} {}us {}",
entry.op, entry.module, entry.duration_micros, entry.result
);
}
}
if observation.output == OutputFormat::Text {
use std::io::Write;
let _ = std::io::stderr().write_all(&host.take_error());
let _ = std::io::stdout().write_all(&host.take_output());
if let (Some(_), Ok(outcome)) = (function, &result) {
if outcome.value != Value::Unit {
println!("{}", outcome.value.display());
}
0
}
}
match result {
Ok(_) => 0,
Err(error) => {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"stdout": stdout_text,
"stderr": stderr_text,
"error": runtime_error_json(&error, &project),
"trace": trace_entries,
}));
} else {
use std::io::Write;
if !stderr.is_empty() {
let _ = std::io::stderr().write_all(&stderr);
}
let _ = std::io::stdout().write_all(&stdout);
eprint!("{}", render_runtime_error(&error, &project));
}
eprint!("{}", render_runtime_error(&error, &project));
1
}
}
}
fn transport_failure(error: &str) -> i32 {
pub(super) fn transport_failure(error: &str) -> i32 {
eprintln!("error[observe.transport_failed]: {error}");
1
}
/// Emit one pre-execution rejection (or the legacy non-event error form).
fn fail(
stream: Option<&EventStream>,
json: bool,
command_name: &str,
/// Report a failure before the interpreter starts.
pub(super) fn fail(
stream: Option<&ObservationSession>,
phase: &str,
code: &str,
message: &str,
@@ -585,47 +412,16 @@ fn fail(
return transport_failure(&error);
}
}
if json && stream.is_none() {
emit_error(json, command_name, code, message);
} else {
eprintln!("error[{code}]: {message}");
}
eprintln!("error[{code}]: {message}");
exit
}
/// Emit one prepare/authorization rejection using a `PrepareError`.
fn fail_prepare(
stream: Option<&EventStream>,
json: bool,
command_name: &str,
stream: Option<&ObservationSession>,
phase: &str,
error: &crate::extension_descriptors::PrepareError,
) -> i32 {
if let Some(stream) = stream {
if let Err(write_error) = stream.rejected(phase, &error.code, &error.message) {
return transport_failure(&write_error);
}
eprintln!("error[{}]: {}", error.code, error.message);
} else {
emit_prepare_error(json, command_name, error);
}
error.exit_code
}
fn emit_prepare_error(
json: bool,
command_name: &str,
error: &crate::extension_descriptors::PrepareError,
) {
if json {
output::print_json(&json!({
"command": command_name,
"success": false,
"error": {"code": error.code, "message": error.message},
}));
} else {
eprintln!("error[{}]: {}", error.code, error.message);
}
fail(stream, phase, &error.code, &error.message, error.exit_code)
}
/// Compare the Host's actual plugin exports with the static manifest set.
+3 -10
View File
@@ -49,12 +49,6 @@ pub struct SandboxSettings {
pub allow_provider: Vec<String>,
/// Explicit trust decision for in-process native plugin loading.
pub trust_native_plugin: bool,
/// Optional Trace v2 output path.
pub trace_file: Option<PathBuf>,
/// Trace event budget override (0 = unlimited).
pub trace_max_events: Option<usize>,
/// Trace approximate byte budget override (0 = unlimited).
pub trace_max_bytes: Option<usize>,
/// External foreign-kernel descriptor paths.
pub kernels: Vec<PathBuf>,
}
@@ -72,7 +66,7 @@ impl SandboxSettings {
/// Reject strict-mode requests that this L1 isolation level does not
/// support. Strict currently covers pure Marqdo and native Math only;
/// granting Foreign, ABI plugins, resource providers, tools or trace files
/// granting Foreign, ABI plugins, resource providers or tools
/// would require extending the supervisor contract first.
pub fn strict_preflight(&self) -> Result<(), String> {
let requested = self.allow_foreign
@@ -87,14 +81,13 @@ impl SandboxSettings {
|| !self.providers.is_empty()
|| !self.allow_provider.is_empty()
|| self.trust_native_plugin
|| !self.kernels.is_empty()
|| self.trace_file.is_some();
|| !self.kernels.is_empty();
if requested {
return Err(
"strict mode currently supports pure Marqdo and native Math only; \
--allow-read/--allow-write/--allow-env/--allow-process/--allow-random/\
--allow-foreign/--allow-plugin/--plugin/--provider/--allow-provider/\
--trust-native-plugin/--kernel/--trace-file are rejected. \
--trust-native-plugin/--kernel are rejected. \
Use --mode project for those capabilities."
.to_string(),
);
+34 -100
View File
@@ -7,16 +7,15 @@
mod analysis;
mod args;
mod commands;
mod execution_events;
mod extension_descriptors;
mod extension_selection;
mod loader;
mod observation;
mod output;
mod project_prepare;
mod provider_manifest;
mod stdlib;
mod tool;
mod trace;
use std::ffi::OsString;
use std::path::PathBuf;
@@ -35,69 +34,44 @@ struct Cli {
command: Command,
}
/// Execution Events v1 options (RFC-OBS-0001).
///
/// `--event-stream jsonl` makes the CLI stdout a dedicated NDJSON channel;
/// program stdout/stderr become events. It is mutually exclusive with
/// `--json` and is not accepted by static commands.
/// Output and capture options for run and call.
#[derive(Args, Clone)]
struct ObserveArgs {
/// Stream Execution Events v1 as JSON Lines on stdout (only `jsonl`).
#[arg(
long = "event-stream",
value_name = "FORMAT",
value_parser = [execution_events::FORMAT_JSONL],
conflicts_with = "json"
)]
event_stream: Option<String>,
/// Select terminal text, a JSON observation snapshot or live JSON Lines.
#[arg(long, value_enum, default_value = "text")]
output: observation::OutputFormat,
/// Atomically save a private observation snapshot of this run.
#[arg(long, value_name = "PATH")]
observation_file: Option<PathBuf>,
/// Publish the value of one exactly named local variable (repeatable).
#[arg(
long = "observe-variable",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-variable", value_name = "NAME")]
observe_variable: Vec<String>,
/// Publish the value of one exactly named parameter (repeatable).
#[arg(
long = "observe-parameter",
value_name = "NAME",
requires = "event_stream"
)]
#[arg(long = "observe-parameter", value_name = "NAME")]
observe_parameter: Vec<String>,
/// Allow selected Text values to be published (second explicit consent).
#[arg(long = "observe-text-values", requires = "event_stream")]
#[arg(long = "observe-text-values")]
observe_text_values: bool,
/// Maximum encoded source bytes for one observed value (0 = unlimited).
#[arg(
long = "observe-max-value-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-value-bytes", value_name = "BYTES")]
observe_max_value_bytes: Option<usize>,
/// Override the structural/value event budget (0 = unlimited).
#[arg(
long = "observe-max-events",
value_name = "COUNT",
requires = "event_stream"
)]
#[arg(long = "observe-max-events", value_name = "COUNT")]
observe_max_events: Option<u64>,
/// Override the approximate structural/value byte budget (0 = unlimited).
#[arg(
long = "observe-max-bytes",
value_name = "BYTES",
requires = "event_stream"
)]
#[arg(long = "observe-max-bytes", value_name = "BYTES")]
observe_max_bytes: Option<u64>,
}
impl ObserveArgs {
fn options(&self) -> Option<execution_events::ObservationOptions> {
self.event_stream.as_ref()?;
let mut options = execution_events::ObservationOptions {
fn options(&self) -> observation::ObservationOptions {
let mut options = observation::ObservationOptions {
output: self.output,
file: self.observation_file.clone(),
variables: self.observe_variable.clone(),
parameters: self.observe_parameter.clone(),
allow_text_values: self.observe_text_values,
..execution_events::ObservationOptions::default()
..observation::ObservationOptions::default()
};
if let Some(bytes) = self.observe_max_value_bytes {
options.max_value_bytes = bytes;
@@ -108,7 +82,7 @@ impl ObserveArgs {
if let Some(bytes) = self.observe_max_bytes {
options.max_bytes = bytes;
}
Some(options)
options
}
}
@@ -220,15 +194,6 @@ struct SandboxArgs {
/// (repeatable; wildcards are not supported).
#[arg(long = "allow-provider", value_name = "NAME")]
allow_provider: Vec<String>,
/// Write a versioned Trace v2 file for this run.
#[arg(long = "trace-file", value_name = "PATH")]
trace_file: Option<PathBuf>,
/// Override the trace event budget (0 = unlimited).
#[arg(long = "trace-max-events")]
trace_max_events: Option<usize>,
/// Override the approximate trace byte budget (0 = unlimited).
#[arg(long = "trace-max-bytes")]
trace_max_bytes: Option<usize>,
/// Register an external foreign-kernel provider (repeatable).
#[arg(long = "kernel", value_name = "PATH")]
kernel: Vec<PathBuf>,
@@ -259,9 +224,6 @@ impl SandboxArgs {
providers: self.provider.clone(),
allow_provider: self.allow_provider.clone(),
trust_native_plugin: self.trust_native_plugin,
trace_file: self.trace_file.clone(),
trace_max_events: self.trace_max_events,
trace_max_bytes: self.trace_max_bytes,
kernels: self.kernel.clone(),
}
}
@@ -273,12 +235,6 @@ struct RunArgs {
file: Option<PathBuf>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output; program stdout is embedded, never mixed.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -294,12 +250,6 @@ struct CallArgs {
args: Vec<String>,
#[command(flatten)]
sandbox: SandboxArgs,
/// Machine readable JSON output.
#[arg(long)]
json: bool,
/// Include the host effect trace.
#[arg(long)]
trace: bool,
#[command(flatten)]
observe: ObserveArgs,
}
@@ -514,36 +464,20 @@ fn dispatch() -> i32 {
};
commands::inspect(args.file.as_deref(), &flags, args.json, &args.plugin)
}
Command::Run(args) => {
let observation = args.observe.options();
commands::execute(
args.file.as_deref(),
None,
&[],
&args.sandbox.settings(),
args.json,
args.trace,
observation.as_ref(),
)
}
Command::Call(args) => match commands::parse_named_args(&args.args) {
Ok(named) => {
let observation = args.observe.options();
commands::execute(
Some(&args.file),
Some(&args.function),
&named,
&args.sandbox.settings(),
args.json,
args.trace,
observation.as_ref(),
)
}
Err(error) => {
eprintln!("error: {error}");
2
}
},
Command::Run(args) => commands::execute(
args.file.as_deref(),
None,
Ok(Vec::new()),
&args.sandbox.settings(),
&args.observe.options(),
),
Command::Call(args) => commands::execute(
Some(&args.file),
Some(&args.function),
commands::parse_named_args(&args.args),
&args.sandbox.settings(),
&args.observe.options(),
),
Command::Fmt(args) => commands::fmt(args.file.as_deref(), args.check),
Command::Plugin(args) => match args.command {
PluginCommand::Inspect(args) => commands::plugin_inspect(&args.target, args.json),
@@ -1,15 +1,9 @@
//! Execution Events v1 JSONL writer and public envelope.
//!
//! Normative contract: `spec/execution-events-v1.md`; decision record:
//! ADR-0059. The host owns the typed events; this module only assigns the
//! public envelope/sequence, encodes bytes as base64 and writes one flushed
//! line per event to the CLI protocol stdout.
//!
//! There is no HTTP, SSE, WebSocket, View or Agent branch here.
//! Deliver the Host observation sequence to JSONL or atomic JSON snapshots.
use std::cell::RefCell;
use std::collections::BTreeSet;
use std::io::{self, Write};
use std::io::{self, Seek, Write};
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -18,19 +12,27 @@ use marqdo_host::{
ParameterSource, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES,
};
use marqdo_value::{RuntimeError, Value};
use marqdo_value::Value;
use serde_json::{json, Value as Json};
/// Public schema name.
pub const SCHEMA: &str = "marqdo.execution-events";
pub const SCHEMA: &str = "marqdo.observation";
/// Public schema major version.
pub const SCHEMA_VERSION: u32 = 1;
/// The only accepted `--event-stream` format in v1.
pub const FORMAT_JSONL: &str = "jsonl";
/// Delivery format on stdout.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
#[default]
Text,
Json,
Jsonl,
}
/// CLI observation options.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ObservationOptions {
pub output: OutputFormat,
pub file: Option<PathBuf>,
/// Exact local-variable names selected with `--observe-variable`.
pub variables: Vec<String>,
/// Exact parameter names selected with `--observe-parameter`.
@@ -48,6 +50,8 @@ pub struct ObservationOptions {
impl Default for ObservationOptions {
fn default() -> Self {
Self {
output: OutputFormat::Text,
file: None,
variables: Vec::new(),
parameters: Vec::new(),
allow_text_values: false,
@@ -59,6 +63,20 @@ impl Default for ObservationOptions {
}
impl ObservationOptions {
pub fn enabled(&self) -> bool {
self.output != OutputFormat::Text || self.file.is_some()
}
pub fn has_capture_overrides(&self) -> bool {
let defaults = Self::default();
!self.variables.is_empty()
|| !self.parameters.is_empty()
|| self.allow_text_values
|| self.max_value_bytes != defaults.max_value_bytes
|| self.max_events != defaults.max_events
|| self.max_bytes != defaults.max_bytes
}
/// Typed host policy for this run.
pub fn config(&self) -> ObservationConfig {
ObservationConfig {
@@ -73,15 +91,15 @@ impl ObservationOptions {
}
}
/// One run's JSONL writer, shared with the host sink.
/// One run and event sequence, shared with the host observation sink.
#[derive(Clone)]
pub struct EventStream {
inner: Rc<RefCell<JsonlWriter>>,
pub struct ObservationSession {
inner: Rc<RefCell<EventWriter>>,
config: ObservationConfig,
}
impl EventStream {
/// Open the protocol channel and write `stream.opened` as `seq: 0`.
impl ObservationSession {
/// Set up all destinations and publish the first event.
pub fn open(options: &ObservationOptions) -> Result<Self, String> {
let run_id = new_run_id();
let config = options.config();
@@ -90,10 +108,6 @@ impl EventStream {
"name": "marqdo",
"version": env!("CARGO_PKG_VERSION"),
},
"protocol": {
"name": SCHEMA,
"schema_version": SCHEMA_VERSION,
},
"observation": {
"level": config.level(),
"values": config.values_enabled(),
@@ -107,10 +121,15 @@ impl EventStream {
"max_value_bytes": config.max_value_bytes,
},
});
let mut writer = JsonlWriter {
out: Box::new(io::stdout()),
run_id: run_id.clone(),
let mut writer = EventWriter {
output: options.output,
snapshot: Snapshot::open(options)?,
run_id,
seq: 0,
source: Json::Null,
truncated: Json::Null,
capture: opened["observation"].clone(),
failed: false,
};
writer.emit("stream.opened", opened)?;
Ok(Self {
@@ -119,11 +138,6 @@ impl EventStream {
})
}
/// Opaque run identity shared with Trace v2 when both are requested.
pub fn run_id(&self) -> String {
self.inner.borrow().run_id.clone()
}
/// Typed policy (used to install the host sink).
pub fn config(&self) -> ObservationConfig {
self.config.clone()
@@ -163,40 +177,26 @@ impl EventStream {
)
}
/// Write the successful terminal event.
/// Write the successful terminal event and its explicitly returned result.
pub fn completed(&self, value: &Value) -> Result<(), String> {
let transferable = !value.contains_memory()
&& !value.contains_resource()
&& !marqdo_host::contains_plugin_handle(value);
let wire = transferable.then(|| marqdo_value::to_wire(value));
self.emit(
"run.completed",
json!({"status": "ok", "value": marqdo_value::to_wire(value)}),
json!({"status": "ok", "value": wire, "value_type": value.type_name()}),
)
}
/// Write the failed terminal event.
pub fn failed(&self, error: &RuntimeError) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {
"code": error.code(),
"message": error.message,
"module_id": error.module_id.as_deref(),
"span": error.span.map(span_json),
}
}),
)
pub fn failed(&self, error: Json) -> Result<(), String> {
self.emit("run.failed", json!({"status": "error", "error": error}))
}
/// Write a failed terminal event for a CLI-level failure that still has a
/// stable code (for example `cli.trace_failed`).
pub fn failed_error(&self, code: &str, message: &str) -> Result<(), String> {
self.emit(
"run.failed",
json!({
"status": "error",
"error": {"code": code, "message": message},
}),
)
/// Deliver a snapshot without a terminal event when isolation interrupted a run.
pub fn incomplete(&self) -> Result<(), String> {
self.inner.borrow_mut().finish_snapshot("incomplete")
}
/// Write the pre-execution rejection terminal event.
@@ -220,7 +220,7 @@ impl EventStream {
/// `ObservationSink` adapter installed into `StdHost`.
pub struct HostEventSink {
stream: EventStream,
stream: ObservationSession,
}
impl ObservationSink for HostEventSink {
@@ -231,14 +231,105 @@ impl ObservationSink for HostEventSink {
}
}
struct JsonlWriter {
out: Box<dyn Write>,
run_id: String,
seq: u64,
struct Snapshot {
staging: tempfile::NamedTempFile,
path: Option<PathBuf>,
}
impl JsonlWriter {
impl Snapshot {
fn open(options: &ObservationOptions) -> Result<Option<Self>, String> {
if options.output != OutputFormat::Json && options.file.is_none() {
return Ok(None);
}
let staging = if let Some(path) = &options.file {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create observation directory: {error}"))?;
tempfile::NamedTempFile::new_in(parent)
} else {
tempfile::NamedTempFile::new()
}
.map_err(|error| format!("cannot stage observation snapshot: {error}"))?;
let mut snapshot = Self {
staging,
path: options.file.clone(),
};
snapshot.write(b"{\"events\":[")?;
Ok(Some(snapshot))
}
fn write(&mut self, bytes: &[u8]) -> Result<(), String> {
self.staging
.write_all(bytes)
.map_err(|error| format!("cannot write observation snapshot: {error}"))
}
fn finish(mut self, metadata: Json, stdout: bool) -> Result<(), String> {
let suffix = serde_json::to_vec(&metadata)
.map_err(|error| format!("cannot encode observation metadata: {error}"))?;
self.write(b"],")?;
self.write(&suffix[1..])?;
self.write(b"\n")?;
if let Some(path) = &self.path {
self.staging
.as_file()
.sync_all()
.map_err(|error| format!("cannot sync observation snapshot: {error}"))?;
let mut file = self
.staging
.persist(path)
.map_err(|error| format!("cannot publish observation snapshot: {error}"))?;
if stdout {
write_snapshot_stdout(&mut file)?;
}
} else {
write_snapshot_stdout(self.staging.as_file_mut())?;
}
Ok(())
}
}
fn write_snapshot_stdout(file: &mut std::fs::File) -> Result<(), String> {
let mut out = io::stdout().lock();
file.rewind()
.and_then(|()| io::copy(file, &mut out))
.and_then(|_| out.flush())
.map_err(|error| format!("cannot write observation snapshot to stdout: {error}"))
}
struct EventWriter {
output: OutputFormat,
snapshot: Option<Snapshot>,
run_id: String,
seq: u64,
source: Json,
truncated: Json,
capture: Json,
failed: bool,
}
impl EventWriter {
fn emit(&mut self, kind: &str, payload: Json) -> Result<(), String> {
if self.failed {
return Err("observation transport already failed".into());
}
let result = self.deliver(kind, payload);
if result.is_err() {
self.failed = true;
self.snapshot.take();
}
result
}
fn deliver(&mut self, kind: &str, payload: Json) -> Result<(), String> {
match kind {
"run.started" => self.source = payload["source"].clone(),
"observation.truncated" => self.truncated = payload.clone(),
_ => {}
}
let event = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
@@ -247,18 +338,78 @@ impl JsonlWriter {
"kind": kind,
"payload": payload,
});
let mut line = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode execution event: {error}"))?;
line.push(b'\n');
// Flush each line: line-buffered batching would hide real-time output
// behind the run duration (RFC-OBS-0001 §5.2).
self.out
.write_all(&line)
.and_then(|()| self.out.flush())
.map_err(|error| format!("cannot write execution event stream: {error}"))?;
let mut bytes = serde_json::to_vec(&event)
.map_err(|error| format!("cannot encode observation event: {error}"))?;
if let Some(snapshot) = &mut self.snapshot {
if self.seq != 0 {
snapshot.write(b",")?;
}
snapshot.write(&bytes)?;
}
if matches!(kind, "run.completed" | "run.failed" | "run.rejected") {
self.finish_snapshot(payload["status"].as_str().expect("terminal status"))?;
}
if self.output == OutputFormat::Jsonl {
let mut out = io::stdout().lock();
bytes.push(b'\n');
out.write_all(&bytes)
.and_then(|()| out.flush())
.map_err(|error| format!("cannot write observation stream: {error}"))?;
}
self.seq += 1;
Ok(())
}
fn finish_snapshot(&mut self, status: &str) -> Result<(), String> {
let Some(snapshot) = self.snapshot.take() else {
return Ok(());
};
let mut capture = self.capture.clone();
capture["truncated"] = self.truncated.clone();
snapshot.finish(
json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": self.run_id, "status": status, "source": self.source},
"capture": capture,
}),
self.output == OutputFormat::Json,
)
}
}
/// The strict supervisor forwards only a complete current snapshot.
pub fn is_complete_snapshot(bytes: &[u8], exit_code: i32) -> bool {
let Ok(snapshot) = serde_json::from_slice::<Json>(bytes) else {
return false;
};
let Some(events) = snapshot["events"].as_array() else {
return false;
};
let Some(run_id) = snapshot["run"]["id"].as_str() else {
return false;
};
let Some(last) = events.last() else {
return false;
};
let status = match last["kind"].as_str() {
Some("run.completed") if exit_code == 0 => "ok",
Some("run.failed") if exit_code != 0 => "error",
Some("run.rejected") if exit_code != 0 => "rejected",
_ => return false,
};
snapshot["schema"] == SCHEMA
&& snapshot["schema_version"] == SCHEMA_VERSION
&& snapshot["run"]["status"] == status
&& snapshot["capture"].is_object()
&& last["payload"]["status"] == status
&& events[0]["kind"] == "stream.opened"
&& events.iter().enumerate().all(|(seq, event)| {
event["schema"] == SCHEMA
&& event["schema_version"] == SCHEMA_VERSION
&& event["run_id"] == run_id
&& event["seq"] == seq
})
}
fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
@@ -365,6 +516,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
}),
),
ObservationEvent::Effect {
frame_id,
operation,
result_code,
module_id,
@@ -372,6 +524,7 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
} => (
"effect",
json!({
"frame_id": frame_id.map(FrameId::as_wire),
"operation": operation,
"result_code": result_code,
"module_id": module_id,
+1 -1
View File
@@ -252,7 +252,7 @@ fn validate_requirements(requires: &Requirements) -> Result<(), String> {
(
"observation",
requires.observation,
crate::execution_events::SCHEMA_VERSION,
crate::observation::SCHEMA_VERSION,
),
] {
if let Some(requested) = requested {
-144
View File
@@ -1,144 +0,0 @@
//! Public Trace v2 writer (spec/trace-v2.md).
//!
//! Events come from the interpreter (semantic) and the capability host
//! (effects). No argument values, secrets or handles are recorded.
use std::path::Path;
use marqdo_host::{Host, SemanticEvent, StdHost, TraceEntry};
use serde_json::{json, Value};
use crate::loader::LoadedProject;
/// Schema name and version.
pub const SCHEMA: &str = "marqdo.trace";
pub const SCHEMA_VERSION: u32 = 2;
/// Write a trace atomically for one run.
pub fn write(
project: &LoadedProject,
host: &StdHost,
entry: &str,
status: &str,
path: &Path,
run_id: Option<&str>,
) -> Result<(), String> {
// A combined `--event-stream` run shares the CLI-generated opaque run id
// with Execution Events v1; Trace v2 keeps its schema and field types.
let run_id = run_id.map(str::to_string).unwrap_or_else(|| {
format!(
"{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|duration| duration.as_nanos())
.unwrap_or(0)
)
});
let analysis_digest = crate::analysis::digest(project);
let root_id = project.identity.root_id();
let state = host.trace_state();
let mut events: Vec<Value> = host
.semantic_events()
.iter()
.map(semantic_json)
.chain(host.trace().iter().map(effect_json))
.collect();
events.sort_by_key(|event| event.get("seq").and_then(Value::as_u64).unwrap_or(u64::MAX));
let mut truncation = state.truncation.clone();
let max_bytes = state.budget.max_bytes;
let bytes = loop {
let mut all = events.clone();
if let Some(truncation) = &truncation {
let seq = all
.last()
.and_then(|event| event.get("seq"))
.and_then(Value::as_u64)
.unwrap_or(0)
+ 1;
all.push(json!({
"seq": seq,
"kind": "trace.truncated",
"module_id": null,
"span": null,
"detail": truncation.reason,
}));
}
let trace = json!({
"schema": SCHEMA,
"schema_version": SCHEMA_VERSION,
"run": {"id": run_id, "entry": entry, "status": status},
"source": {
"root_id": root_id,
"analysis_digest": format!("sha256:{analysis_digest}"),
},
"limits": {
"max_events": state.budget.max_events,
"max_bytes": state.budget.max_bytes,
},
"truncated": truncation,
"events": all,
});
let bytes = serde_json::to_vec_pretty(&trace)
.map_err(|error| format!("cannot encode trace: {error}"))?;
if max_bytes == 0 || bytes.len() <= max_bytes || events.is_empty() {
break bytes;
}
events.pop();
if truncation.is_none() {
truncation = Some(marqdo_host::TraceTruncation {
reason: "byte_budget".to_string(),
limit: max_bytes as u64,
written: events.len() as u64,
});
}
};
atomic_write(path, &bytes)
}
fn semantic_json(event: &SemanticEvent) -> Value {
json!({
"seq": event.seq,
"kind": event.kind,
"function_id": event.function_id,
"module_id": event.module_id,
"span": event.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": event.detail,
})
}
fn effect_json(entry: &TraceEntry) -> Value {
json!({
"seq": entry.seq,
"kind": "effect",
"module_id": entry.module,
"span": entry.span.map(|span| json!({"start": span.start, "end": span.end})),
"detail": entry.result,
"operation": entry.op,
"duration_micros": entry.duration_micros,
})
}
fn atomic_write(path: &Path, bytes: &[u8]) -> Result<(), String> {
let parent = path
.parent()
.filter(|parent| !parent.as_os_str().is_empty())
.unwrap_or_else(|| Path::new("."));
std::fs::create_dir_all(parent)
.map_err(|error| format!("cannot create `{}`: {error}", parent.display()))?;
let temporary = parent.join(format!(
".{}.tmp-{}",
path.file_name()
.map(|name| name.to_string_lossy().to_string())
.unwrap_or_else(|| "trace.json".to_string()),
std::process::id()
));
std::fs::write(&temporary, bytes)
.map_err(|error| format!("cannot write `{}`: {error}", temporary.display()))?;
if let Err(error) = std::fs::rename(&temporary, path) {
let _ = std::fs::remove_file(&temporary);
return Err(format!("cannot publish `{}`: {error}", path.display()));
}
Ok(())
}