observation: deliver one execution event sequence to stream and snapshot
This commit is contained in:
1 parent
f83d992c61
commit
404d559b86
97 files changed
+2672
-3128
No files matched your search
+22
-150
@@ -7,7 +7,7 @@
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::net::{TcpListener, TcpStream, ToSocketAddrs, UdpSocket};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_plugin_abi::{
|
||||
ErrorKind as PluginErrorKind, LoadedPlugin, PluginError, PluginKind, PluginManifest,
|
||||
@@ -31,11 +31,9 @@ use crate::provider_worker::WorkerResourceProvider;
|
||||
use crate::resource::{
|
||||
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
|
||||
};
|
||||
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
|
||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
||||
|
||||
mod dispatch;
|
||||
mod effects;
|
||||
mod providers;
|
||||
mod resource_ops;
|
||||
mod resource_requests;
|
||||
@@ -182,29 +180,10 @@ pub trait Host {
|
||||
/// Take the buffered program output.
|
||||
fn take_output(&mut self) -> Vec<u8>;
|
||||
|
||||
/// Recorded effects.
|
||||
fn trace(&self) -> &[TraceEntry];
|
||||
|
||||
/// Record one semantic event (Trace v1). Default: ignored.
|
||||
fn record_semantic(
|
||||
&mut self,
|
||||
_kind: &str,
|
||||
_function_id: Option<&str>,
|
||||
_module_id: Option<&str>,
|
||||
_span: Option<Span>,
|
||||
_detail: Option<&str>,
|
||||
) {
|
||||
}
|
||||
|
||||
/// Recorded semantic events. Default: empty.
|
||||
fn semantic_events(&self) -> &[SemanticEvent] {
|
||||
&[]
|
||||
}
|
||||
|
||||
/// Whether the host has an installed observation sink.
|
||||
///
|
||||
/// The default host is inert; the interpreter uses this to skip building
|
||||
/// any observation event when the run has no `--event-stream`.
|
||||
/// any observation event when there is no capture destination.
|
||||
fn observation_enabled(&self) -> bool {
|
||||
false
|
||||
}
|
||||
@@ -252,8 +231,6 @@ pub struct StdHost {
|
||||
pub budget: Budget,
|
||||
/// Filesystem view.
|
||||
pub fs: ProjectFs,
|
||||
/// Effect trace.
|
||||
pub trace: EffectTrace,
|
||||
/// Maximum wall-clock time for one foreign kernel call.
|
||||
pub foreign_timeout: Duration,
|
||||
/// Maximum captured bytes per foreign stream.
|
||||
@@ -280,9 +257,6 @@ pub struct StdHost {
|
||||
resources: ResourceTable,
|
||||
/// Registered in-process providers keyed by resource kind (ADR-0033).
|
||||
resource_providers: BTreeMap<String, (String, SharedResourceProvider)>,
|
||||
semantic_events: Vec<SemanticEvent>,
|
||||
next_event_seq: u64,
|
||||
trace_state: TraceState,
|
||||
observation: Option<ObservationState>,
|
||||
observation_error: Option<String>,
|
||||
}
|
||||
@@ -331,7 +305,6 @@ impl StdHost {
|
||||
capabilities,
|
||||
budget: Budget::default(),
|
||||
fs: ProjectFs::new(project_root),
|
||||
trace: EffectTrace::default(),
|
||||
foreign_timeout: Duration::from_secs(10),
|
||||
foreign_output_limit: 1024 * 1024,
|
||||
kernel_registry: marqdo_foreign::KernelRegistry::builtin(),
|
||||
@@ -346,9 +319,6 @@ impl StdHost {
|
||||
stderr: Vec::new(),
|
||||
resources: ResourceTable::new(),
|
||||
resource_providers: BTreeMap::new(),
|
||||
semantic_events: Vec::new(),
|
||||
next_event_seq: 0,
|
||||
trace_state: TraceState::default(),
|
||||
observation: None,
|
||||
observation_error: None,
|
||||
}
|
||||
@@ -502,22 +472,6 @@ impl StdHost {
|
||||
exports
|
||||
}
|
||||
|
||||
/// Recorded semantic events (Trace v1).
|
||||
pub fn semantic_events(&self) -> &[SemanticEvent] {
|
||||
&self.semantic_events
|
||||
}
|
||||
|
||||
/// Trace capacity state for the writer.
|
||||
pub fn trace_state(&self) -> &TraceState {
|
||||
&self.trace_state
|
||||
}
|
||||
|
||||
/// Override the trace event/byte budget.
|
||||
pub fn with_trace_budget(mut self, budget: TraceBudget) -> Self {
|
||||
self.trace_state.budget = budget;
|
||||
self
|
||||
}
|
||||
|
||||
/// Audited plugin capability decisions.
|
||||
pub fn capability_audit(&self) -> Vec<CapabilityAudit> {
|
||||
self.broker_audit
|
||||
@@ -536,13 +490,6 @@ impl StdHost {
|
||||
})
|
||||
}
|
||||
|
||||
/// Enable effect tracing.
|
||||
pub fn with_trace(mut self) -> Self {
|
||||
self.trace = EffectTrace::enabled();
|
||||
self.trace_state.enabled = true;
|
||||
self
|
||||
}
|
||||
|
||||
/// Install the typed observation sink and policy (RFC-OBS-0001).
|
||||
///
|
||||
/// Without this call the host has no observation state: it does not
|
||||
@@ -617,8 +564,13 @@ impl StdHost {
|
||||
result_code: &str,
|
||||
ctx: &ExecutionContext,
|
||||
) {
|
||||
let frame_id = self
|
||||
.observation
|
||||
.as_ref()
|
||||
.and_then(ObservationState::parent_frame);
|
||||
let result = self.emit_observation(
|
||||
ObservationEvent::Effect {
|
||||
frame_id,
|
||||
operation,
|
||||
result_code,
|
||||
module_id: &ctx.module_id,
|
||||
@@ -777,26 +729,8 @@ impl Host for StdHost {
|
||||
max_bytes: usize,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<ResourceRead, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let read = self.resources.read(handle, max_bytes, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.read",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!(
|
||||
"kind={kind} count={} eof={}",
|
||||
read.bytes.len(),
|
||||
read.eof
|
||||
)),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.read",
|
||||
ctx,
|
||||
started,
|
||||
&format!("kind={kind} count={}", read.bytes.len()),
|
||||
);
|
||||
self.observe_effect("resource.read", "ok", ctx);
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
@@ -806,7 +740,6 @@ impl Host for StdHost {
|
||||
bytes: &[u8],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<usize, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let kind = self.resources.kind(handle, ctx.span)?;
|
||||
let stdio = self.resources.stdio_name(handle, ctx.span)?;
|
||||
let count = self.resources.write(handle, bytes, ctx.span)?;
|
||||
@@ -829,19 +762,7 @@ impl Host for StdHost {
|
||||
self.emit_observation(event, true)?;
|
||||
}
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.write",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind={kind} count={count}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.write",
|
||||
ctx,
|
||||
started,
|
||||
&format!("kind={kind} count={count}"),
|
||||
);
|
||||
self.observe_effect("resource.write", "ok", ctx);
|
||||
Ok(count)
|
||||
}
|
||||
|
||||
@@ -850,29 +771,11 @@ impl Host for StdHost {
|
||||
handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let pending = self.resources.pending_file_write(handle, ctx.span)?;
|
||||
let count = match pending {
|
||||
Some((relative, bytes)) => {
|
||||
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
|
||||
bytes.len()
|
||||
}
|
||||
None => 0,
|
||||
};
|
||||
if let Some((relative, bytes)) = self.resources.pending_file_write(handle, ctx.span)? {
|
||||
self.fs.write_bytes(&relative, &bytes, ctx.span)?;
|
||||
}
|
||||
self.resources.close(handle, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.close",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("flushed_bytes={count}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.close",
|
||||
ctx,
|
||||
started,
|
||||
&format!("flushed_bytes={count}"),
|
||||
);
|
||||
self.observe_effect("resource.close", "ok", ctx);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -881,16 +784,8 @@ impl Host for StdHost {
|
||||
handle: ResourceHandle,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let accepted = self.resources.accept(handle, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.accept",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=tcp-listener"),
|
||||
);
|
||||
self.record_resource_effect("resource.accept", ctx, started, "ok");
|
||||
self.observe_effect("resource.accept", "ok", ctx);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::Resource(accepted));
|
||||
@@ -990,6 +885,14 @@ impl Host for StdHost {
|
||||
return Ok(());
|
||||
}
|
||||
match event {
|
||||
RuntimeObservation::Effect {
|
||||
operation,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
self.observe_effect(operation, "ok", &ExecutionContext::new(module_id, span));
|
||||
Ok(())
|
||||
}
|
||||
RuntimeObservation::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
@@ -1130,37 +1033,6 @@ impl Host for StdHost {
|
||||
fn take_output(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.output)
|
||||
}
|
||||
|
||||
fn trace(&self) -> &[TraceEntry] {
|
||||
self.trace.entries()
|
||||
}
|
||||
|
||||
fn record_semantic(
|
||||
&mut self,
|
||||
kind: &str,
|
||||
function_id: Option<&str>,
|
||||
module_id: Option<&str>,
|
||||
span: Option<Span>,
|
||||
detail: Option<&str>,
|
||||
) {
|
||||
let estimate = TraceState::estimate(kind, function_id, module_id, detail, None);
|
||||
if !self.trace_state.accept(estimate) {
|
||||
return;
|
||||
}
|
||||
let seq = self.next_seq();
|
||||
self.semantic_events.push(SemanticEvent {
|
||||
seq,
|
||||
kind: kind.to_string(),
|
||||
function_id: function_id.map(str::to_string),
|
||||
module_id: module_id.map(str::to_string),
|
||||
span,
|
||||
detail: detail.map(str::to_string),
|
||||
});
|
||||
}
|
||||
|
||||
fn semantic_events(&self) -> &[SemanticEvent] {
|
||||
&self.semantic_events
|
||||
}
|
||||
}
|
||||
|
||||
fn map_plugin_error(error: PluginError) -> RuntimeError {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! `Host::invoke` dispatch table.
|
||||
//!
|
||||
//! Child module of `host`: it may call the parent's private capability,
|
||||
//! resource and trace helpers. `StdHost` remains the only host implementation.
|
||||
//! resource and observation helpers. `StdHost` remains the only host implementation.
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -36,30 +36,12 @@ pub(crate) fn invoke(
|
||||
),
|
||||
));
|
||||
}
|
||||
let started = Instant::now();
|
||||
let result = host.dispatch(op, args, ctx);
|
||||
let summary = match &result {
|
||||
Ok(_) => "ok".to_string(),
|
||||
Err(error) => error.code().to_string(),
|
||||
let result_code = match &result {
|
||||
Ok(_) => "ok",
|
||||
Err(error) => error.code(),
|
||||
};
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(&summary),
|
||||
Some(op.name()),
|
||||
);
|
||||
if host.trace_state.accept(estimate) {
|
||||
let seq = host.next_seq();
|
||||
host.trace.record(
|
||||
seq,
|
||||
op.name(),
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
host.observe_effect(op.name(), result_code, ctx);
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
//! Trace/effect bookkeeping helpers for `StdHost`.
|
||||
//!
|
||||
//! Child module of `host`; it may use the parent's private trace state.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl StdHost {
|
||||
pub(crate) fn next_seq(&mut self) -> u64 {
|
||||
let seq = self.next_event_seq;
|
||||
self.next_event_seq += 1;
|
||||
seq
|
||||
}
|
||||
|
||||
pub(crate) fn record_resource_effect(
|
||||
&mut self,
|
||||
op: &str,
|
||||
ctx: &ExecutionContext,
|
||||
started: Instant,
|
||||
summary: &str,
|
||||
) {
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(summary),
|
||||
Some(op),
|
||||
);
|
||||
if !self.trace_state.accept(estimate) {
|
||||
return;
|
||||
}
|
||||
let seq = self.next_seq();
|
||||
self.trace.record(
|
||||
seq,
|
||||
op,
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary.to_string(),
|
||||
);
|
||||
// Executed regardless of Trace v2 being enabled: the two writers are
|
||||
// independent observation outputs (RFC-OBS-0001 §4.6).
|
||||
self.observe_effect(op, summary, ctx);
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,6 @@ impl StdHost {
|
||||
rights: &[String],
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let requested: BTreeSet<&str> = rights.iter().map(String::as_str).collect();
|
||||
if self.mode == SandboxMode::Strict {
|
||||
// stdio/stdout is the existing console channel already permitted by
|
||||
@@ -89,14 +88,7 @@ impl StdHost {
|
||||
"stdout" => self.resources.open_stdout(),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=stdio descriptor={descriptor}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"file" => {
|
||||
@@ -105,28 +97,14 @@ impl StdHost {
|
||||
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
|
||||
let bytes = self.fs.read_bytes(descriptor, ctx.span)?;
|
||||
let handle = self.resources.open_file(relative, bytes);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=file rights=read"),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
if requested == BTreeSet::from(["write"]) {
|
||||
self.capabilities.check_write(descriptor, ctx.span)?;
|
||||
let (_, relative) = self.fs.resolve(descriptor, ctx.span)?;
|
||||
let handle = self.resources.open_file_writer(relative);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("kind=file rights=write"),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
return Ok(Value::Resource(handle));
|
||||
}
|
||||
Err(RuntimeError::new(
|
||||
@@ -184,14 +162,7 @@ impl StdHost {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
|
||||
let handle = self.resources.open_tcp(stream);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tcp host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"tls" => {
|
||||
@@ -284,14 +255,7 @@ impl StdHost {
|
||||
})?;
|
||||
let stream = rustls::StreamOwned::new(connection, tcp);
|
||||
let handle = self.resources.open_tls(stream);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tls host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"tcp-listener" => {
|
||||
@@ -348,14 +312,7 @@ impl StdHost {
|
||||
)
|
||||
})?;
|
||||
let handle = self.resources.open_tcp_listener(listener);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=tcp-listener host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
"udp" => {
|
||||
@@ -416,14 +373,7 @@ impl StdHost {
|
||||
let _ = socket.set_read_timeout(Some(Duration::from_secs(5)));
|
||||
let _ = socket.set_write_timeout(Some(Duration::from_secs(5)));
|
||||
let handle = self.resources.open_udp(socket);
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind=udp host={host} port={port}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
other => {
|
||||
@@ -447,14 +397,7 @@ impl StdHost {
|
||||
let handle = self
|
||||
.resources
|
||||
.open_provider(provider, other, descriptor, rights, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.open",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("kind={other} provider={provider_name}")),
|
||||
);
|
||||
self.record_resource_effect("resource.open", ctx, started, "ok");
|
||||
self.observe_effect("resource.open", "ok", ctx);
|
||||
Ok(Value::Resource(handle))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::io::{Read, Write};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use super::{ErrorCategory, ExecutionContext, Host, RuntimeError, SandboxMode, StdHost, Value};
|
||||
use super::{ErrorCategory, ExecutionContext, RuntimeError, SandboxMode, StdHost, Value};
|
||||
|
||||
impl StdHost {
|
||||
pub(super) fn request_compatibility_operation(
|
||||
@@ -13,7 +13,6 @@ impl StdHost {
|
||||
args: Vec<Value>,
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
if self.mode != SandboxMode::Project {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::PermissionDenied,
|
||||
@@ -72,14 +71,7 @@ impl StdHost {
|
||||
self.capabilities.check_process(&program, ctx.span)?;
|
||||
let result =
|
||||
crate::process::run_process(self.fs.root(), &program, &program_args, ctx)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=process.run"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "process.run");
|
||||
self.observe_effect("process.run", "ok", ctx);
|
||||
Ok(result)
|
||||
}
|
||||
"regex.match" | "regex.captures" => {
|
||||
@@ -116,14 +108,7 @@ impl StdHost {
|
||||
))
|
||||
}
|
||||
};
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(operation),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, operation);
|
||||
self.observe_effect(operation, "ok", ctx);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
if operation == "regex.match" {
|
||||
@@ -192,14 +177,7 @@ impl StdHost {
|
||||
.into_iter()
|
||||
.map(|byte| Value::int(byte as i64))
|
||||
.collect();
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=compress.gzip"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "compress.gzip");
|
||||
self.observe_effect("compress.gzip", "ok", ctx);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::List(values));
|
||||
@@ -274,14 +252,7 @@ impl StdHost {
|
||||
))
|
||||
}
|
||||
};
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=compress.gunzip"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "compress.gunzip");
|
||||
self.observe_effect("compress.gunzip", "ok", ctx);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::text(text));
|
||||
@@ -326,14 +297,7 @@ impl StdHost {
|
||||
.into_iter()
|
||||
.map(|byte| Value::int(byte as i64))
|
||||
.collect();
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=random.bytes"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "random.bytes");
|
||||
self.observe_effect("random.bytes", "ok", ctx);
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::List(values));
|
||||
@@ -385,14 +349,7 @@ impl StdHost {
|
||||
);
|
||||
}
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=env.get"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "env.get");
|
||||
self.observe_effect("env.get", "ok", ctx);
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"clock.now" => {
|
||||
@@ -420,14 +377,7 @@ impl StdHost {
|
||||
let mut map = BTreeMap::new();
|
||||
map.insert("ok".to_string(), Value::Bool(true));
|
||||
map.insert("value".to_string(), Value::int(millis));
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=clock.now"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "clock.now");
|
||||
self.observe_effect("clock.now", "ok", ctx);
|
||||
Ok(Value::Map(map))
|
||||
}
|
||||
"fs.read_at" => {
|
||||
@@ -470,14 +420,7 @@ impl StdHost {
|
||||
let result = self
|
||||
.fs
|
||||
.request("read_at", &[path, offset, length], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.read_at"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.read_at");
|
||||
self.observe_effect("fs.read_at", "ok", ctx);
|
||||
Ok(result)
|
||||
}
|
||||
"fs.append" => {
|
||||
@@ -507,14 +450,7 @@ impl StdHost {
|
||||
};
|
||||
self.capabilities.check_write(&path, ctx.span)?;
|
||||
let result = self.fs.request("append", &[path, text], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.append"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.append");
|
||||
self.observe_effect("fs.append", "ok", ctx);
|
||||
Ok(result)
|
||||
}
|
||||
"fs.walk" => {
|
||||
@@ -537,14 +473,7 @@ impl StdHost {
|
||||
};
|
||||
self.capabilities.check_read(&path, ctx.span)?;
|
||||
let result = self.fs.request("walk", &[path], ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some("op=fs.walk"),
|
||||
);
|
||||
self.record_resource_effect("resource.request", ctx, started, "fs.walk");
|
||||
self.observe_effect("fs.walk", "ok", ctx);
|
||||
Ok(result)
|
||||
}
|
||||
"fs.exists" | "fs.metadata" | "fs.list" | "fs.mkdir" | "fs.remove" | "fs.rename" => {
|
||||
@@ -587,19 +516,7 @@ impl StdHost {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let result = self.fs.request(name, &paths, ctx.span)?;
|
||||
self.record_semantic(
|
||||
"resource.request",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
ctx.span,
|
||||
Some(&format!("op=fs.{name}")),
|
||||
);
|
||||
self.record_resource_effect(
|
||||
"resource.request",
|
||||
ctx,
|
||||
started,
|
||||
&format!("fs.{name}"),
|
||||
);
|
||||
self.observe_effect("resource.request", "ok", ctx);
|
||||
Ok(result)
|
||||
}
|
||||
_ => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! CapabilityHost: capability checks, resource budgets, effect tracing and the
|
||||
//! CapabilityHost: capability checks, resource budgets, observation and the
|
||||
//! only bridge to math, foreign kernels, files and plugins.
|
||||
//!
|
||||
//! Blueprint §9 and §7.3: every side effect goes through this boundary, checks
|
||||
@@ -17,7 +17,6 @@ mod process;
|
||||
mod provider_c;
|
||||
mod provider_worker;
|
||||
pub mod resource;
|
||||
pub mod trace;
|
||||
|
||||
pub use budget::{Budget, DEFAULT_FUEL, DEFAULT_OUTPUT_BYTES, DEFAULT_STACK_LIMIT};
|
||||
pub use capability::{
|
||||
@@ -39,4 +38,3 @@ pub use resource::{
|
||||
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
|
||||
CORE_RESOURCE_KINDS,
|
||||
};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
|
||||
@@ -4,7 +4,7 @@
|
||||
//! interpreter and host emit at real commit points, the optional sink the CLI
|
||||
//! installs, the run-scoped frame identity and the bounded observation budget.
|
||||
//! It does **not** know JSONL, HTTP, SSE, View, agents or the public envelope;
|
||||
//! the CLI composes the public Execution Events v1 protocol from these events.
|
||||
//! the CLI composes the public Observation protocol from these events.
|
||||
//!
|
||||
//! Defaults are deliberately inert: no sink means no allocation and no
|
||||
//! serialization. The facade never exposes `Frame.locals`, the whole
|
||||
@@ -202,6 +202,7 @@ pub enum ObservationEvent<'a> {
|
||||
},
|
||||
/// The host completed a controlled effect attempt.
|
||||
Effect {
|
||||
frame_id: Option<FrameId>,
|
||||
operation: &'a str,
|
||||
result_code: &'a str,
|
||||
module_id: &'a str,
|
||||
@@ -247,7 +248,7 @@ pub enum LoopTransfer {
|
||||
}
|
||||
|
||||
impl LoopTransfer {
|
||||
/// The event kind in Trace and Execution Events.
|
||||
/// The event kind in Observation.
|
||||
pub fn event_kind(self) -> &'static str {
|
||||
match self {
|
||||
Self::Break => "control.break",
|
||||
@@ -258,10 +259,15 @@ impl LoopTransfer {
|
||||
|
||||
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
|
||||
///
|
||||
/// Every variant carries an `Option<FrameId>`; observation of values and
|
||||
/// structural events only happens while a frame identity exists.
|
||||
/// Value and control observations carry the owning call frame.
|
||||
#[derive(Debug)]
|
||||
pub enum RuntimeObservation<'a> {
|
||||
/// A local memory operation committed.
|
||||
Effect {
|
||||
operation: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A `return` statement committed (before the call exits).
|
||||
Return {
|
||||
frame_id: Option<FrameId>,
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
//! Effect tracing.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use marqdo_span::Span;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// One recorded host effect.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct TraceEntry {
|
||||
/// Global event sequence within the run.
|
||||
#[serde(default)]
|
||||
pub seq: u64,
|
||||
/// Operation name (`print`, `fs.read`, `foreign.call`, ...).
|
||||
pub op: String,
|
||||
/// Module that initiated it.
|
||||
pub module: String,
|
||||
/// Source span of the call site.
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub span: Option<Span>,
|
||||
/// Wall-clock duration.
|
||||
pub duration_micros: u64,
|
||||
/// Result summary (`ok`, or a diagnostic code). Never contains secrets.
|
||||
pub result: String,
|
||||
}
|
||||
|
||||
/// Collected effects for one run.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct EffectTrace {
|
||||
entries: Vec<TraceEntry>,
|
||||
/// Whether tracing is enabled.
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl EffectTrace {
|
||||
/// Enable tracing.
|
||||
pub fn enabled() -> Self {
|
||||
Self {
|
||||
entries: Vec::new(),
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record an effect.
|
||||
pub fn record(
|
||||
&mut self,
|
||||
seq: u64,
|
||||
op: impl Into<String>,
|
||||
module: impl Into<String>,
|
||||
span: Option<Span>,
|
||||
duration: Duration,
|
||||
result: impl Into<String>,
|
||||
) {
|
||||
if !self.enabled {
|
||||
return;
|
||||
}
|
||||
self.entries.push(TraceEntry {
|
||||
seq,
|
||||
op: op.into(),
|
||||
module: module.into(),
|
||||
span,
|
||||
duration_micros: duration.as_micros() as u64,
|
||||
result: result.into(),
|
||||
});
|
||||
}
|
||||
|
||||
/// Recorded entries.
|
||||
pub fn entries(&self) -> &[TraceEntry] {
|
||||
&self.entries
|
||||
}
|
||||
}
|
||||
|
||||
/// Default maximum number of trace events.
|
||||
pub const DEFAULT_MAX_TRACE_EVENTS: usize = 100_000;
|
||||
/// Default approximate maximum serialized trace bytes.
|
||||
pub const DEFAULT_MAX_TRACE_BYTES: usize = 32 * 1024 * 1024;
|
||||
|
||||
/// Trace capacity budget. A zero value means unlimited.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct TraceBudget {
|
||||
/// Maximum events (including the terminal truncation marker).
|
||||
pub max_events: usize,
|
||||
/// Approximate maximum serialized bytes.
|
||||
pub max_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for TraceBudget {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_events: DEFAULT_MAX_TRACE_EVENTS,
|
||||
max_bytes: DEFAULT_MAX_TRACE_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why and where a trace stopped recording.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct TraceTruncation {
|
||||
/// `event_budget` or `byte_budget`.
|
||||
pub reason: String,
|
||||
/// The configured limit that was reached.
|
||||
pub limit: u64,
|
||||
/// Events written before truncation.
|
||||
pub written: u64,
|
||||
}
|
||||
|
||||
/// Mutable trace capacity state for one run.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct TraceState {
|
||||
/// Whether trace recording is enabled.
|
||||
pub enabled: bool,
|
||||
/// Configured budget.
|
||||
pub budget: TraceBudget,
|
||||
/// Events accepted so far.
|
||||
pub written: usize,
|
||||
/// Estimated accepted bytes.
|
||||
pub bytes: usize,
|
||||
/// Truncation marker, set once.
|
||||
pub truncation: Option<TraceTruncation>,
|
||||
}
|
||||
|
||||
impl TraceState {
|
||||
/// Accept one event if it fits the budget.
|
||||
pub fn accept(&mut self, estimate: usize) -> bool {
|
||||
if !self.enabled || self.truncation.is_some() {
|
||||
return false;
|
||||
}
|
||||
if self.budget.max_events > 0 && self.written >= self.budget.max_events {
|
||||
self.truncation = Some(TraceTruncation {
|
||||
reason: "event_budget".to_string(),
|
||||
limit: self.budget.max_events as u64,
|
||||
written: self.written as u64,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
if self.budget.max_bytes > 0 && self.bytes + estimate > self.budget.max_bytes {
|
||||
self.truncation = Some(TraceTruncation {
|
||||
reason: "byte_budget".to_string(),
|
||||
limit: self.budget.max_bytes as u64,
|
||||
written: self.written as u64,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
self.written += 1;
|
||||
self.bytes += estimate;
|
||||
true
|
||||
}
|
||||
|
||||
/// Estimate one semantic/effect event envelope.
|
||||
pub fn estimate(
|
||||
kind: &str,
|
||||
function_id: Option<&str>,
|
||||
module_id: Option<&str>,
|
||||
detail: Option<&str>,
|
||||
operation: Option<&str>,
|
||||
) -> usize {
|
||||
96 + kind.len()
|
||||
+ function_id.map(str::len).unwrap_or(0)
|
||||
+ module_id.map(str::len).unwrap_or(0)
|
||||
+ detail.map(str::len).unwrap_or(0)
|
||||
+ operation.map(str::len).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// One semantic event emitted by the interpreter (Trace v2).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SemanticEvent {
|
||||
/// Global event sequence within the run.
|
||||
pub seq: u64,
|
||||
/// Stable event kind (`call.enter`, `call.exit`, `branch.eval`, ...).
|
||||
pub kind: String,
|
||||
/// Canonical function id, when inside a call.
|
||||
pub function_id: Option<String>,
|
||||
/// Logical module owning `span`.
|
||||
pub module_id: Option<String>,
|
||||
/// Source span, when known.
|
||||
pub span: Option<Span>,
|
||||
/// Non-sensitive detail (`ok`, `true`, `int`, an error code).
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
Reference in new issue
Block a user