obs(01): typed host observation facade, real stdio chunks, frame identity and budgets
This commit is contained in:
1 parent
d38736c0a0
commit
d78faaf8e4
8 files changed
+1817
-12
No files matched your search
@@ -22,6 +22,10 @@ use crate::capability::{Capabilities, CapabilityAudit, CapabilityBroker};
|
||||
use crate::context::ExecutionContext;
|
||||
use crate::fs::ProjectFs;
|
||||
use crate::handles::{contains_plugin_handle, PluginHandleTable};
|
||||
use crate::observe::{
|
||||
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
|
||||
ObservationEvent, ObservationSink, ObservationState, RuntimeObservation,
|
||||
};
|
||||
use crate::plugin_worker::WorkerPlugin;
|
||||
use crate::provider_c::{load_package, CResourceProvider};
|
||||
use crate::provider_worker::WorkerResourceProvider;
|
||||
@@ -209,6 +213,44 @@ pub trait Host {
|
||||
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`.
|
||||
fn observation_enabled(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// Announce a successfully bound call frame.
|
||||
///
|
||||
/// Returns the run-unique frame identity, or `None` when observation is
|
||||
/// disabled. Argument binding must have completed before this is called;
|
||||
/// a binding failure never produces a frame.
|
||||
fn observation_begin_frame(
|
||||
&mut self,
|
||||
_function_id: &str,
|
||||
_module_id: &str,
|
||||
_span: Option<Span>,
|
||||
) -> Result<Option<FrameId>, RuntimeError> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Close a previously announced frame, including failure paths.
|
||||
fn observation_end_frame(
|
||||
&mut self,
|
||||
_frame_id: Option<FrameId>,
|
||||
_status: &str,
|
||||
_module_id: &str,
|
||||
_span: Option<Span>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Emit one borrowed runtime observation event. Default: ignored.
|
||||
fn observe_runtime(&mut self, _event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Default capability host implementation.
|
||||
@@ -254,6 +296,8 @@ pub struct StdHost {
|
||||
semantic_events: Vec<SemanticEvent>,
|
||||
next_event_seq: u64,
|
||||
trace_state: TraceState,
|
||||
observation: Option<ObservationState>,
|
||||
observation_error: Option<String>,
|
||||
}
|
||||
|
||||
struct PluginSlot {
|
||||
@@ -318,6 +362,8 @@ impl StdHost {
|
||||
semantic_events: Vec::new(),
|
||||
next_event_seq: 0,
|
||||
trace_state: TraceState::default(),
|
||||
observation: None,
|
||||
observation_error: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,6 +556,95 @@ impl StdHost {
|
||||
self
|
||||
}
|
||||
|
||||
/// Install the typed observation sink and policy (RFC-OBS-0001).
|
||||
///
|
||||
/// Without this call the host has no observation state: it does not
|
||||
/// allocate events, clone values or serialize anything.
|
||||
pub fn with_observation(
|
||||
mut self,
|
||||
config: ObservationConfig,
|
||||
sink: Box<dyn ObservationSink>,
|
||||
) -> Self {
|
||||
self.observation = Some(ObservationState::new(config, sink));
|
||||
self
|
||||
}
|
||||
|
||||
/// The installed observation policy, when event mode is active.
|
||||
pub fn observation_config(&self) -> Option<&ObservationConfig> {
|
||||
self.observation.as_ref().map(|state| &state.config)
|
||||
}
|
||||
|
||||
/// A saved observation transport failure (if any).
|
||||
///
|
||||
/// The interpreter surfaces this at the next budget boundary; the CLI also
|
||||
/// checks it after the run so a successful return cannot mask a dead
|
||||
/// event pipe.
|
||||
pub fn observation_failure(&self) -> Option<&str> {
|
||||
self.observation_error.as_deref()
|
||||
}
|
||||
|
||||
fn emit_observation(
|
||||
&mut self,
|
||||
event: ObservationEvent<'_>,
|
||||
critical: bool,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let Some(state) = self.observation.as_mut() else {
|
||||
return Ok(());
|
||||
};
|
||||
let mut pending = Some(event);
|
||||
if !critical {
|
||||
if state.is_truncated() {
|
||||
return Ok(());
|
||||
}
|
||||
let estimate = estimate_event_bytes(pending.as_ref().expect("event present"));
|
||||
if !state.admit(estimate) {
|
||||
let reason = state.truncation_reason(estimate);
|
||||
let limit = state.limit_for(reason);
|
||||
let written = state.written();
|
||||
pending = Some(ObservationEvent::ObservationTruncated {
|
||||
reason,
|
||||
limit,
|
||||
written,
|
||||
dropped: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
let result = match pending {
|
||||
Some(event) => state.sink.emit(event),
|
||||
None => Ok(()),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => Ok(()),
|
||||
Err(error) => Err(self.record_observation_error(error)),
|
||||
}
|
||||
}
|
||||
|
||||
fn record_observation_error(&mut self, error: ObservationError) -> RuntimeError {
|
||||
self.observation_error = Some(error.message.clone());
|
||||
error.into_runtime_error()
|
||||
}
|
||||
|
||||
pub(crate) fn observe_effect(
|
||||
&mut self,
|
||||
operation: &str,
|
||||
result_code: &str,
|
||||
ctx: &ExecutionContext,
|
||||
) {
|
||||
let result = self.emit_observation(
|
||||
ObservationEvent::Effect {
|
||||
operation,
|
||||
result_code,
|
||||
module_id: &ctx.module_id,
|
||||
span: ctx.span,
|
||||
},
|
||||
false,
|
||||
);
|
||||
// Effect recording is an existing infallible path. The failure is
|
||||
// stored and surfaced by the next fuel/deadline boundary and by the
|
||||
// CLI after the run; it is never silently forgotten.
|
||||
let _ = result;
|
||||
}
|
||||
|
||||
/// Override the budget.
|
||||
pub fn with_budget(mut self, budget: Budget) -> Self {
|
||||
self.budget = budget;
|
||||
@@ -703,6 +838,17 @@ impl Host for StdHost {
|
||||
} else {
|
||||
self.output.extend_from_slice(&bytes[..count]);
|
||||
}
|
||||
// Real-time boundary: emit exactly the bytes the host just
|
||||
// committed, at this write, never by splitting the final buffer.
|
||||
let committed = &bytes[..count];
|
||||
for chunk in committed.chunks(crate::observe::MAX_STREAM_CHUNK_BYTES) {
|
||||
let event = if stdio == Some("stderr") {
|
||||
ObservationEvent::StderrChunk { data: chunk }
|
||||
} else {
|
||||
ObservationEvent::StdoutChunk { data: chunk }
|
||||
};
|
||||
self.emit_observation(event, true)?;
|
||||
}
|
||||
}
|
||||
self.record_semantic(
|
||||
"resource.write",
|
||||
@@ -1384,6 +1530,13 @@ impl Host for StdHost {
|
||||
}
|
||||
|
||||
fn consume_fuel(&mut self, amount: u64, span: Option<Span>) -> Result<(), RuntimeError> {
|
||||
if let Some(message) = &self.observation_error {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Observation,
|
||||
span,
|
||||
format!("observe.transport_failed: {message}"),
|
||||
));
|
||||
}
|
||||
self.budget.consume_fuel(amount, span)
|
||||
}
|
||||
|
||||
@@ -1392,9 +1545,192 @@ impl Host for StdHost {
|
||||
}
|
||||
|
||||
fn check_deadline(&self, span: Option<Span>) -> Result<(), RuntimeError> {
|
||||
if let Some(message) = &self.observation_error {
|
||||
return Err(RuntimeError::new(
|
||||
ErrorCategory::Observation,
|
||||
span,
|
||||
format!("observe.transport_failed: {message}"),
|
||||
));
|
||||
}
|
||||
self.budget.check_deadline(span)
|
||||
}
|
||||
|
||||
fn observation_enabled(&self) -> bool {
|
||||
self.observation.is_some()
|
||||
}
|
||||
|
||||
fn observation_begin_frame(
|
||||
&mut self,
|
||||
function_id: &str,
|
||||
module_id: &str,
|
||||
span: Option<Span>,
|
||||
) -> Result<Option<FrameId>, RuntimeError> {
|
||||
let Some(state) = self.observation.as_mut() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let frame_id = state.begin_frame();
|
||||
let parent_frame_id = state.parent_frame();
|
||||
state.push_frame(frame_id);
|
||||
self.emit_observation(
|
||||
ObservationEvent::CallEnter {
|
||||
frame_id,
|
||||
parent_frame_id,
|
||||
function_id,
|
||||
module_id,
|
||||
span,
|
||||
},
|
||||
false,
|
||||
)?;
|
||||
Ok(Some(frame_id))
|
||||
}
|
||||
|
||||
fn observation_end_frame(
|
||||
&mut self,
|
||||
frame_id: Option<FrameId>,
|
||||
status: &str,
|
||||
module_id: &str,
|
||||
span: Option<Span>,
|
||||
) -> Result<(), RuntimeError> {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
if let Some(state) = self.observation.as_mut() {
|
||||
state.pop_frame(frame_id);
|
||||
}
|
||||
self.emit_observation(
|
||||
ObservationEvent::CallExit {
|
||||
frame_id,
|
||||
status,
|
||||
module_id,
|
||||
span,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
|
||||
fn observe_runtime(&mut self, event: RuntimeObservation<'_>) -> Result<(), RuntimeError> {
|
||||
if self.observation.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
match event {
|
||||
RuntimeObservation::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
self.emit_observation(
|
||||
ObservationEvent::Return {
|
||||
frame_id,
|
||||
value_type,
|
||||
module_id,
|
||||
span,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
RuntimeObservation::BranchEval {
|
||||
frame_id,
|
||||
result,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
self.emit_observation(
|
||||
ObservationEvent::BranchEval {
|
||||
frame_id,
|
||||
result,
|
||||
module_id,
|
||||
span,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
RuntimeObservation::LoopIteration {
|
||||
frame_id,
|
||||
decision,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
self.emit_observation(
|
||||
ObservationEvent::LoopIteration {
|
||||
frame_id,
|
||||
decision,
|
||||
module_id,
|
||||
span,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
RuntimeObservation::VariableAssigned {
|
||||
frame_id,
|
||||
name,
|
||||
value,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(config) = self.observation.as_ref().map(|state| &state.config) else {
|
||||
return Ok(());
|
||||
};
|
||||
let selected = config.selected_variables.contains(name);
|
||||
let (value_state, observed) = encode_value(config, selected, value);
|
||||
self.emit_observation(
|
||||
ObservationEvent::VariableAssigned {
|
||||
frame_id,
|
||||
name,
|
||||
value_type: value.type_name(),
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value: observed,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
RuntimeObservation::ParameterBound {
|
||||
frame_id,
|
||||
name,
|
||||
source,
|
||||
value,
|
||||
module_id,
|
||||
span,
|
||||
} => {
|
||||
let Some(frame_id) = frame_id else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(config) = self.observation.as_ref().map(|state| &state.config) else {
|
||||
return Ok(());
|
||||
};
|
||||
let selected = config.selected_parameters.contains(name);
|
||||
let (value_state, observed) = encode_value(config, selected, value);
|
||||
self.emit_observation(
|
||||
ObservationEvent::ParameterObserved {
|
||||
frame_id,
|
||||
name,
|
||||
source,
|
||||
value_type: value.type_name(),
|
||||
module_id,
|
||||
span,
|
||||
value_state,
|
||||
value: observed,
|
||||
},
|
||||
false,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn take_output(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.output)
|
||||
}
|
||||
|
||||
@@ -37,5 +37,8 @@ impl StdHost {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ pub mod fs;
|
||||
pub mod handles;
|
||||
pub mod host;
|
||||
pub mod kernels;
|
||||
pub mod observe;
|
||||
mod plugin_worker;
|
||||
mod process;
|
||||
mod provider_c;
|
||||
@@ -28,5 +29,11 @@ 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 observe::{
|
||||
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError,
|
||||
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
|
||||
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
|
||||
};
|
||||
pub use resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider};
|
||||
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
|
||||
@@ -0,0 +1,540 @@
|
||||
//! Typed runtime observation facade (RFC-OBS-0001, ADR-0059).
|
||||
//!
|
||||
//! This module is internal to the workspace. It defines the typed events the
|
||||
//! 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.
|
||||
//!
|
||||
//! Defaults are deliberately inert: no sink means no allocation and no
|
||||
//! serialization. The facade never exposes `Frame.locals`, the whole
|
||||
//! `MemoryStore`, raw OS pointers or host handles.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use marqdo_span::Span;
|
||||
use marqdo_value::{ErrorCategory, RuntimeError, Value};
|
||||
|
||||
/// Default maximum number of structural/value observation events per run.
|
||||
pub const DEFAULT_MAX_OBSERVATION_EVENTS: u64 = 100_000;
|
||||
/// Default approximate maximum encoded bytes for structural/value events.
|
||||
pub const DEFAULT_MAX_OBSERVATION_BYTES: u64 = 16 * 1024 * 1024;
|
||||
/// Default maximum encoded bytes for one selected value.
|
||||
pub const DEFAULT_MAX_VALUE_BYTES: usize = 256;
|
||||
/// Maximum committed stdio bytes carried by one chunk event.
|
||||
pub const MAX_STREAM_CHUNK_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Opaque run-scoped call-instance identity.
|
||||
///
|
||||
/// Not a function identity, not a source location and never a memory pointer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct FrameId(pub u64);
|
||||
|
||||
impl FrameId {
|
||||
/// Stable wire form used by the public protocol (`f1`, `f2`, ...).
|
||||
pub fn as_wire(self) -> String {
|
||||
format!("f{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a bound parameter's value came from.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ParameterSource {
|
||||
/// Supplied by the caller (CLI `--arg` or a Marqdo call).
|
||||
Provided,
|
||||
/// Evaluated from the declared default expression.
|
||||
Default,
|
||||
}
|
||||
|
||||
impl ParameterSource {
|
||||
/// Stable wire name.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ParameterSource::Provided => "provided",
|
||||
ParameterSource::Default => "default",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Observation policy for one run.
|
||||
///
|
||||
/// `structural` always implies frame identity; value events only exist for
|
||||
/// exact names in `selected_variables`/`selected_parameters`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObservationConfig {
|
||||
/// Publish lifecycle/frame/branch/loop/effect events.
|
||||
pub structural: bool,
|
||||
/// Exact local-variable names allowed to publish a value.
|
||||
pub selected_variables: BTreeSet<String>,
|
||||
/// Exact parameter names allowed to publish a value.
|
||||
pub selected_parameters: BTreeSet<String>,
|
||||
/// Second explicit consent required to publish `Text` bytes.
|
||||
pub allow_text_values: bool,
|
||||
/// Structural/value event budget (`0` = unlimited).
|
||||
pub max_observation_events: u64,
|
||||
/// Approximate structural/value byte budget (`0` = unlimited).
|
||||
pub max_observation_bytes: u64,
|
||||
/// Maximum source bytes encoded for one value (`0` = unlimited).
|
||||
pub max_value_bytes: usize,
|
||||
}
|
||||
|
||||
impl Default for ObservationConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
structural: true,
|
||||
selected_variables: BTreeSet::new(),
|
||||
selected_parameters: BTreeSet::new(),
|
||||
allow_text_values: false,
|
||||
max_observation_events: DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
max_observation_bytes: DEFAULT_MAX_OBSERVATION_BYTES,
|
||||
max_value_bytes: DEFAULT_MAX_VALUE_BYTES,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ObservationConfig {
|
||||
/// Whether any value can ever be published.
|
||||
pub fn values_enabled(&self) -> bool {
|
||||
!self.selected_variables.is_empty() || !self.selected_parameters.is_empty()
|
||||
}
|
||||
|
||||
/// Negotiated observation level (`base`, `structural` or `values`).
|
||||
pub fn level(&self) -> &'static str {
|
||||
if self.values_enabled() {
|
||||
"values"
|
||||
} else if self.structural {
|
||||
"structural"
|
||||
} else {
|
||||
"base"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a value has (or has not) a wire encoding.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ValueState {
|
||||
/// Name not selected; no value encoded.
|
||||
NotRequested,
|
||||
/// Name selected but policy hides the value.
|
||||
Redacted,
|
||||
/// Encoded but truncated to the configured maximum.
|
||||
Truncated,
|
||||
/// Type not supported by the v1 scalar policy.
|
||||
Unsupported,
|
||||
/// Encoded normally.
|
||||
Observed,
|
||||
}
|
||||
|
||||
impl ValueState {
|
||||
/// Stable wire name.
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
ValueState::NotRequested => "not_requested",
|
||||
ValueState::Redacted => "redacted",
|
||||
ValueState::Truncated => "truncated",
|
||||
ValueState::Unsupported => "unsupported",
|
||||
ValueState::Observed => "observed",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bounded, policy-filtered value encoding (the `marqdo.value.v1` wire
|
||||
/// object plus optional truncation metadata).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ObservedValue {
|
||||
/// JSON object safe to publish.
|
||||
pub wire: serde_json::Value,
|
||||
}
|
||||
|
||||
/// One typed internal observation event.
|
||||
///
|
||||
/// Borrows strings and stdio bytes so the default disabled path never clones a
|
||||
/// frame, argument list or whole `Value`. The sink must consume it
|
||||
/// synchronously before returning.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum ObservationEvent<'a> {
|
||||
/// Bytes committed to the program's stdout by the host.
|
||||
StdoutChunk { data: &'a [u8] },
|
||||
/// Bytes committed to the program's stderr by the host.
|
||||
StderrChunk { data: &'a [u8] },
|
||||
/// A new frame exists (arguments already bound).
|
||||
CallEnter {
|
||||
frame_id: FrameId,
|
||||
parent_frame_id: Option<FrameId>,
|
||||
function_id: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A frame finished, including failure paths.
|
||||
CallExit {
|
||||
frame_id: FrameId,
|
||||
status: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A `return` statement committed its value.
|
||||
Return {
|
||||
frame_id: FrameId,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A branch condition was evaluated.
|
||||
BranchEval {
|
||||
frame_id: FrameId,
|
||||
result: bool,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A loop condition was evaluated.
|
||||
LoopIteration {
|
||||
frame_id: FrameId,
|
||||
decision: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// The host completed a controlled effect attempt.
|
||||
Effect {
|
||||
operation: &'a str,
|
||||
result_code: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A local assignment was committed.
|
||||
VariableAssigned {
|
||||
frame_id: FrameId,
|
||||
name: &'a str,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
value_state: ValueState,
|
||||
value: Option<ObservedValue>,
|
||||
},
|
||||
/// A function parameter was bound.
|
||||
ParameterObserved {
|
||||
frame_id: FrameId,
|
||||
name: &'a str,
|
||||
source: ParameterSource,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
value_state: ValueState,
|
||||
value: Option<ObservedValue>,
|
||||
},
|
||||
/// The structural/value observation budget was exhausted.
|
||||
ObservationTruncated {
|
||||
reason: &'a str,
|
||||
limit: u64,
|
||||
written: u64,
|
||||
dropped: Option<u64>,
|
||||
},
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Debug)]
|
||||
pub enum RuntimeObservation<'a> {
|
||||
/// A `return` statement committed (before the call exits).
|
||||
Return {
|
||||
frame_id: Option<FrameId>,
|
||||
value_type: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A branch condition evaluated.
|
||||
BranchEval {
|
||||
frame_id: Option<FrameId>,
|
||||
result: bool,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A loop condition evaluated.
|
||||
LoopIteration {
|
||||
frame_id: Option<FrameId>,
|
||||
decision: &'a str,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A local variable assignment committed.
|
||||
VariableAssigned {
|
||||
frame_id: Option<FrameId>,
|
||||
name: &'a str,
|
||||
value: &'a Value,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
/// A parameter was bound.
|
||||
ParameterBound {
|
||||
frame_id: Option<FrameId>,
|
||||
name: &'a str,
|
||||
source: ParameterSource,
|
||||
value: &'a Value,
|
||||
module_id: &'a str,
|
||||
span: Option<Span>,
|
||||
},
|
||||
}
|
||||
|
||||
/// Sink installed by the composition root (the CLI JSONL writer in product
|
||||
/// builds, an in-memory recorder in tests).
|
||||
pub trait ObservationSink {
|
||||
/// Consume one event synchronously.
|
||||
fn emit(&mut self, event: ObservationEvent<'_>) -> Result<(), ObservationError>;
|
||||
}
|
||||
|
||||
/// A sink failed to accept an event (usually a closed/broken output pipe).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ObservationError {
|
||||
/// Human-readable transport reason (safe to print to OS stderr).
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
impl ObservationError {
|
||||
/// Construct an observation transport error.
|
||||
pub fn new(message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert into the stable runtime failure used to abort the run.
|
||||
pub fn into_runtime_error(self) -> RuntimeError {
|
||||
RuntimeError::new(
|
||||
ErrorCategory::Observation,
|
||||
None,
|
||||
format!("observe.transport_failed: {}", self.message),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ObservationError {
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ObservationError {}
|
||||
|
||||
/// Mutable per-run observation state owned by `StdHost`.
|
||||
pub(crate) struct ObservationState {
|
||||
pub(crate) config: ObservationConfig,
|
||||
pub(crate) sink: Box<dyn ObservationSink>,
|
||||
next_frame: u64,
|
||||
frames: Vec<FrameId>,
|
||||
written: u64,
|
||||
bytes: u64,
|
||||
truncated: bool,
|
||||
}
|
||||
|
||||
impl ObservationState {
|
||||
pub(crate) fn new(config: ObservationConfig, sink: Box<dyn ObservationSink>) -> Self {
|
||||
Self {
|
||||
config,
|
||||
sink,
|
||||
next_frame: 0,
|
||||
frames: Vec::new(),
|
||||
written: 0,
|
||||
bytes: 0,
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn begin_frame(&mut self) -> FrameId {
|
||||
self.next_frame += 1;
|
||||
FrameId(self.next_frame)
|
||||
}
|
||||
|
||||
pub(crate) fn parent_frame(&self) -> Option<FrameId> {
|
||||
self.frames.last().copied()
|
||||
}
|
||||
|
||||
pub(crate) fn push_frame(&mut self, frame: FrameId) {
|
||||
self.frames.push(frame);
|
||||
}
|
||||
|
||||
/// Pop the frame if it is on the stack. A mismatch is a runtime bug, not a
|
||||
/// consumer-visible event, so it is repaired defensively rather than
|
||||
/// panicking inside the host.
|
||||
pub(crate) fn pop_frame(&mut self, frame: FrameId) {
|
||||
if self.frames.last().copied() == Some(frame) {
|
||||
self.frames.pop();
|
||||
} else if let Some(position) = self.frames.iter().rposition(|item| *item == frame) {
|
||||
self.frames.truncate(position);
|
||||
}
|
||||
}
|
||||
|
||||
/// Estimate one encoded event and accept it if the budget allows.
|
||||
///
|
||||
/// Returns `Ok(true)` when the event was admitted, `Ok(false)` when the
|
||||
/// budget was already exhausted, and writes the single truncation marker
|
||||
/// through `emit_truncated` on the transition.
|
||||
pub(crate) fn admit(&mut self, estimate: u64) -> bool {
|
||||
if self.truncated {
|
||||
return false;
|
||||
}
|
||||
let event_limit = self.config.max_observation_events;
|
||||
let byte_limit = self.config.max_observation_bytes;
|
||||
if (event_limit > 0 && self.written >= event_limit)
|
||||
|| (byte_limit > 0 && self.bytes.saturating_add(estimate) > byte_limit)
|
||||
{
|
||||
self.truncated = true;
|
||||
return false;
|
||||
}
|
||||
self.written += 1;
|
||||
self.bytes = self.bytes.saturating_add(estimate);
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn truncation_reason(&self, estimate: u64) -> &'static str {
|
||||
let event_limit = self.config.max_observation_events;
|
||||
if event_limit > 0 && self.written >= event_limit {
|
||||
"event_budget"
|
||||
} else if self.config.max_observation_bytes > 0
|
||||
&& self.bytes.saturating_add(estimate) > self.config.max_observation_bytes
|
||||
{
|
||||
"byte_budget"
|
||||
} else {
|
||||
"event_budget"
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_truncated(&self) -> bool {
|
||||
self.truncated
|
||||
}
|
||||
|
||||
pub(crate) fn written(&self) -> u64 {
|
||||
self.written
|
||||
}
|
||||
|
||||
pub(crate) fn limit_for(&self, reason: &str) -> u64 {
|
||||
if reason == "byte_budget" {
|
||||
self.config.max_observation_bytes
|
||||
} else {
|
||||
self.config.max_observation_events
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a selected value under the v1 scalar policy.
|
||||
///
|
||||
/// No `Debug`, no recursive container expansion and no handle serialization.
|
||||
pub fn encode_value(
|
||||
config: &ObservationConfig,
|
||||
selected: bool,
|
||||
value: &Value,
|
||||
) -> (ValueState, Option<ObservedValue>) {
|
||||
if !selected {
|
||||
return (ValueState::NotRequested, None);
|
||||
}
|
||||
match value {
|
||||
Value::Int(_) | Value::Float(_) | Value::Bool(_) => (
|
||||
ValueState::Observed,
|
||||
Some(ObservedValue {
|
||||
wire: marqdo_value::to_wire(value),
|
||||
}),
|
||||
),
|
||||
Value::Text(text) => {
|
||||
if !config.allow_text_values {
|
||||
return (ValueState::Redacted, None);
|
||||
}
|
||||
let limit = config.max_value_bytes;
|
||||
if limit == 0 || text.len() <= limit {
|
||||
return (
|
||||
ValueState::Observed,
|
||||
Some(ObservedValue {
|
||||
wire: marqdo_value::to_wire(value),
|
||||
}),
|
||||
);
|
||||
}
|
||||
let mut cut = limit.min(text.len());
|
||||
while cut > 0 && !text.is_char_boundary(cut) {
|
||||
cut -= 1;
|
||||
}
|
||||
let prefix = Value::Text(text[..cut].to_string());
|
||||
let mut wire = marqdo_value::to_wire(&prefix);
|
||||
if let serde_json::Value::Object(map) = &mut wire {
|
||||
map.insert("truncated".to_string(), serde_json::Value::Bool(true));
|
||||
map.insert(
|
||||
"original_byte_count".to_string(),
|
||||
serde_json::Value::from(text.len() as u64),
|
||||
);
|
||||
}
|
||||
(ValueState::Truncated, Some(ObservedValue { wire }))
|
||||
}
|
||||
_ => (ValueState::Unsupported, None),
|
||||
}
|
||||
}
|
||||
|
||||
/// Approximate encoded size, used only for the observation byte budget.
|
||||
pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
|
||||
let mut total: u64 = 160;
|
||||
let mut add_text = |text: &str| total = total.saturating_add(text.len() as u64);
|
||||
match event {
|
||||
ObservationEvent::StdoutChunk { data } | ObservationEvent::StderrChunk { data } => {
|
||||
total = total.saturating_add((data.len() as u64).saturating_mul(4) / 3);
|
||||
}
|
||||
ObservationEvent::CallEnter {
|
||||
function_id,
|
||||
module_id,
|
||||
..
|
||||
} => {
|
||||
add_text(function_id);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::CallExit {
|
||||
status, module_id, ..
|
||||
} => {
|
||||
add_text(status);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::Return {
|
||||
value_type,
|
||||
module_id,
|
||||
..
|
||||
} => {
|
||||
add_text(value_type);
|
||||
add_text(module_id);
|
||||
}
|
||||
ObservationEvent::BranchEval { module_id, .. }
|
||||
| ObservationEvent::LoopIteration { module_id, .. }
|
||||
| ObservationEvent::Effect { module_id, .. } => {
|
||||
add_text(module_id);
|
||||
if let ObservationEvent::LoopIteration { decision, .. } = event {
|
||||
add_text(decision);
|
||||
}
|
||||
if let ObservationEvent::Effect { operation, .. } = event {
|
||||
add_text(operation);
|
||||
}
|
||||
}
|
||||
ObservationEvent::VariableAssigned {
|
||||
name,
|
||||
value_type,
|
||||
module_id,
|
||||
value,
|
||||
..
|
||||
}
|
||||
| ObservationEvent::ParameterObserved {
|
||||
name,
|
||||
value_type,
|
||||
module_id,
|
||||
value,
|
||||
..
|
||||
} => {
|
||||
add_text(name);
|
||||
add_text(value_type);
|
||||
add_text(module_id);
|
||||
if let Some(value) = value {
|
||||
total = total.saturating_add(encoded_len(&value.wire));
|
||||
}
|
||||
}
|
||||
ObservationEvent::ObservationTruncated { reason, .. } => add_text(reason),
|
||||
}
|
||||
total
|
||||
}
|
||||
|
||||
fn encoded_len(value: &serde_json::Value) -> u64 {
|
||||
serde_json::to_vec(value)
|
||||
.map(|bytes| bytes.len() as u64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
Reference in new issue
Block a user