feat(trace): Trace v2 identity, module-owned events and capacity bounds (B-16)
- bind traces to the logical project identity and the exact emitted Analysis digest; every span-bearing event carries module_id - add host TraceState budgets (100k events / 32 MiB defaults), CLI --trace-max-events/--trace-max-bytes, terminal trace.truncated events, and a final serialized byte cap; budgets never change run.status - disable semantic recording when no trace is requested - cap worker frames at 8 MiB, align request/result/capability wire caps, make clean EOF distinct from protocol errors, and mark/kill a worker after a transport failure instead of reusing it - add trace-v2 spec/schema, independent trace consumer, CI check and tests - record the S2/C state in STATUS
This commit is contained in:
1 parent
55dcb57553
commit
d890686a2b
21 files changed
+732
-84
No files matched your search
@@ -20,7 +20,7 @@ use crate::context::ExecutionContext;
|
||||
use crate::fs::ProjectFs;
|
||||
use crate::handles::{contains_plugin_handle, PluginHandleTable};
|
||||
use crate::plugin_worker::WorkerPlugin;
|
||||
use crate::trace::{EffectTrace, SemanticEvent, TraceEntry};
|
||||
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
|
||||
use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
|
||||
|
||||
/// Host operations reachable from the language surface.
|
||||
@@ -99,6 +99,7 @@ pub trait Host {
|
||||
&mut self,
|
||||
_kind: &str,
|
||||
_function_id: Option<&str>,
|
||||
_module_id: Option<&str>,
|
||||
_span: Option<Span>,
|
||||
_detail: Option<&str>,
|
||||
) {
|
||||
@@ -144,6 +145,7 @@ pub struct StdHost {
|
||||
pub handles: PluginHandleTable,
|
||||
semantic_events: Vec<SemanticEvent>,
|
||||
next_event_seq: u64,
|
||||
trace_state: TraceState,
|
||||
}
|
||||
|
||||
struct PluginSlot {
|
||||
@@ -203,6 +205,7 @@ impl StdHost {
|
||||
handles: PluginHandleTable::default(),
|
||||
semantic_events: Vec::new(),
|
||||
next_event_seq: 0,
|
||||
trace_state: TraceState::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -338,6 +341,17 @@ impl StdHost {
|
||||
seq
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -359,6 +373,7 @@ impl StdHost {
|
||||
/// Enable effect tracing.
|
||||
pub fn with_trace(mut self) -> Self {
|
||||
self.trace = EffectTrace::enabled();
|
||||
self.trace_state.enabled = true;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -504,20 +519,29 @@ impl Host for StdHost {
|
||||
ctx: &ExecutionContext,
|
||||
) -> Result<Value, RuntimeError> {
|
||||
let started = Instant::now();
|
||||
let seq = self.next_seq();
|
||||
let result = self.dispatch(op, args, ctx);
|
||||
let summary = match &result {
|
||||
Ok(_) => "ok".to_string(),
|
||||
Err(error) => error.code().to_string(),
|
||||
};
|
||||
self.trace.record(
|
||||
seq,
|
||||
op.name(),
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary,
|
||||
let estimate = TraceState::estimate(
|
||||
"effect",
|
||||
None,
|
||||
Some(&ctx.module_id),
|
||||
Some(&summary),
|
||||
Some(op.name()),
|
||||
);
|
||||
if self.trace_state.accept(estimate) {
|
||||
let seq = self.next_seq();
|
||||
self.trace.record(
|
||||
seq,
|
||||
op.name(),
|
||||
ctx.module_id.clone(),
|
||||
ctx.span,
|
||||
started.elapsed(),
|
||||
summary,
|
||||
);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -545,14 +569,20 @@ impl Host for StdHost {
|
||||
&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),
|
||||
});
|
||||
|
||||
@@ -21,4 +21,4 @@ pub use fs::ProjectFs;
|
||||
pub use handles::{contains_plugin_handle, PluginHandleTable};
|
||||
pub use host::{arity, expect_text, Host, HostOp, StdHost};
|
||||
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceEntry};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
|
||||
@@ -22,6 +22,7 @@ pub struct WorkerPlugin {
|
||||
stdin: ChildStdin,
|
||||
frames: Receiver<Result<serde_json::Value, PluginError>>,
|
||||
exports: BTreeMap<String, String>,
|
||||
dead: bool,
|
||||
}
|
||||
|
||||
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||
@@ -94,6 +95,7 @@ impl WorkerPlugin {
|
||||
};
|
||||
let Some(mut stdout) = child.stdout.take() else {
|
||||
let _ = child.kill();
|
||||
let _ = std::fs::remove_file(&manifest_path);
|
||||
return Err(PluginError::load(
|
||||
"worker_spawn_failed",
|
||||
"worker stdout unavailable",
|
||||
@@ -103,10 +105,23 @@ impl WorkerPlugin {
|
||||
thread::Builder::new()
|
||||
.name("marqdo-plugin-worker-reader".to_string())
|
||||
.spawn(move || loop {
|
||||
let frame = read_frame(&mut stdout);
|
||||
let failed = frame.is_err();
|
||||
if sender.send(frame).is_err() || failed {
|
||||
break;
|
||||
match read_frame(&mut stdout) {
|
||||
Ok(Some(frame)) => {
|
||||
if sender.send(Ok(frame)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
let _ = sender.send(Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed its output stream",
|
||||
)));
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
let _ = sender.send(Err(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|error| {
|
||||
@@ -169,21 +184,35 @@ impl WorkerPlugin {
|
||||
stdin,
|
||||
frames,
|
||||
exports,
|
||||
dead: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// Invoke one export in the worker.
|
||||
pub fn invoke(&mut self, request: &WireRequest) -> Result<WireResponse, PluginError> {
|
||||
if self.dead {
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker is no longer usable after a transport failure",
|
||||
));
|
||||
}
|
||||
let request_value: serde_json::Value = serde_json::from_slice(&request.to_json_bytes()?)
|
||||
.map_err(|error| PluginError::wire("worker_encode_failed", error.to_string()))?;
|
||||
write_frame(
|
||||
if let Err(error) = write_frame(
|
||||
&mut self.stdin,
|
||||
&json!({"kind": "invoke", "request": request_value}),
|
||||
)?;
|
||||
) {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
let frame = match self.frames.recv_timeout(CALL_TIMEOUT) {
|
||||
Ok(frame) => frame?,
|
||||
Ok(Ok(frame)) => frame,
|
||||
Ok(Err(error)) => {
|
||||
self.mark_dead();
|
||||
return Err(error);
|
||||
}
|
||||
Err(_) => {
|
||||
let _ = self.child.kill();
|
||||
self.mark_dead();
|
||||
return Err(PluginError::invoke(
|
||||
"plugin.timeout",
|
||||
"plugin worker exceeded its invocation timeout",
|
||||
@@ -202,12 +231,20 @@ impl WorkerPlugin {
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.unwrap_or("worker reported an error"),
|
||||
)),
|
||||
_ => Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed or violated the frame protocol",
|
||||
)),
|
||||
_ => {
|
||||
self.mark_dead();
|
||||
Err(PluginError::invoke(
|
||||
"plugin.crashed",
|
||||
"plugin worker closed or violated the frame protocol",
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn mark_dead(&mut self) {
|
||||
self.dead = true;
|
||||
let _ = self.child.kill();
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerPlugin {
|
||||
|
||||
@@ -70,7 +70,99 @@ impl EffectTrace {
|
||||
}
|
||||
}
|
||||
|
||||
/// One semantic event emitted by the interpreter (Trace v1).
|
||||
/// 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.
|
||||
@@ -79,6 +171,8 @@ pub struct SemanticEvent {
|
||||
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).
|
||||
|
||||
Reference in new issue
Block a user