Ship oracle journal values, bytecode/frontend hardening, and replay-policy Lean.
Host exposes oracle journals as language values with refuse/copy gates; bytecode and foreign session paths get modularized; applications and verification replay-policy sources land with Lake builds ignored. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
e3d9021bb6
commit
8f1010f967
101 files changed
+17962
-1727
No files matched your search
+25
-6
@@ -220,6 +220,8 @@ pub enum HostFn {
|
||||
ForeignSessionInterrupt = 211,
|
||||
/// `<TAB>` M7: `access(集合, 键)` — polymorphic collection access (legacy index).
|
||||
Access = 212,
|
||||
OracleJournal = 213,
|
||||
OracleReplayCheck = 214,
|
||||
}
|
||||
|
||||
/// Single source of truth for every host function. `<TAB>` slimming
|
||||
@@ -438,6 +440,8 @@ pub const HOST_FN_TABLE: &[HostFnDef] = &[
|
||||
HostFnDef { id: 210, f: HostFn::ForeignSessionList, name: "host_foreign_session_list", required: &[], optional: &[] },
|
||||
HostFnDef { id: 211, f: HostFn::ForeignSessionInterrupt, name: "host_foreign_session_interrupt", required: &["id"], optional: &[] },
|
||||
HostFnDef { id: 212, f: HostFn::Access, name: "host_access", required: &["value", "key"], optional: &[] },
|
||||
HostFnDef { id: 213, f: HostFn::OracleJournal, name: "host_oracle_journal", required: &[], optional: &[] },
|
||||
HostFnDef { id: 214, f: HostFn::OracleReplayCheck, name: "host_oracle_replay_check", required: &["expected", "observed"], optional: &[] },
|
||||
];
|
||||
|
||||
|
||||
@@ -466,6 +470,8 @@ impl HostFn {
|
||||
"host_cwd" => Self::Cwd,
|
||||
"host_exit" => Self::Exit,
|
||||
"host_exec" => Self::Exec,
|
||||
"host_oracle_journal" => Self::OracleJournal,
|
||||
"host_oracle_replay_check" => Self::OracleReplayCheck,
|
||||
"host_json_parse" => Self::JsonParse,
|
||||
"host_json_stringify" => Self::JsonStringify,
|
||||
"host_json_get" => Self::JsonGet,
|
||||
@@ -748,7 +754,13 @@ pub fn call_host(
|
||||
bound.get("args"),
|
||||
bound.get("capture"),
|
||||
),
|
||||
HostFn::JsonParse => json::parse(require(bound, "text")?),
|
||||
HostFn::OracleJournal => Ok(Value::List(ctx.oracle_observations.clone())),
|
||||
HostFn::OracleReplayCheck => super::oracle::replay_check(require(bound, "expected")?, require(bound, "observed")?),
|
||||
HostFn::JsonParse => {
|
||||
let value = json::parse(require(bound, "text")?)?;
|
||||
super::oracle::append(ctx, "decode", &value)?;
|
||||
Ok(value)
|
||||
},
|
||||
HostFn::JsonStringify => {
|
||||
json::stringify(require(bound, "value")?, bound.get("indent"))
|
||||
}
|
||||
@@ -1127,7 +1139,7 @@ pub fn call_host(
|
||||
HostFn::ForeignSessionEval => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
crate::host::foreign_session::eval_with_stdin(
|
||||
let record = crate::host::foreign_session::eval_with_stdin(
|
||||
ctx,
|
||||
require(bound, "id")?,
|
||||
bound.get("code"),
|
||||
@@ -1135,7 +1147,10 @@ pub fn call_host(
|
||||
bound.get("input"),
|
||||
bound.get("stdin").and_then(|v| v.reveal_text()),
|
||||
bound.get("timeout"),
|
||||
)
|
||||
)?;
|
||||
let value = super::oracle::eval_observation(&record)?;
|
||||
super::oracle::append(ctx, "eval", &value)?;
|
||||
Ok(record)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
@@ -1162,11 +1177,13 @@ pub fn call_host(
|
||||
HostFn::ForeignSessionGet => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
crate::host::foreign_session::get(
|
||||
let value = crate::host::foreign_session::get(
|
||||
ctx,
|
||||
require(bound, "id")?,
|
||||
require(bound, "name")?,
|
||||
)
|
||||
)?;
|
||||
super::oracle::append(ctx, "get", &value)?;
|
||||
Ok(value)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
@@ -1177,7 +1194,9 @@ pub fn call_host(
|
||||
HostFn::ForeignSessionNames => {
|
||||
#[cfg(feature = "exec-host")]
|
||||
{
|
||||
crate::host::foreign_session::names(ctx, require(bound, "id")?)
|
||||
let value = crate::host::foreign_session::names(ctx, require(bound, "id")?)?;
|
||||
super::oracle::append(ctx, "decode", &value)?;
|
||||
Ok(value)
|
||||
}
|
||||
#[cfg(not(feature = "exec-host"))]
|
||||
{
|
||||
|
||||
+54
-55
@@ -15,7 +15,7 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::foreign::registry::{self, LangSpec};
|
||||
use crate::foreign::split_cmd_line;
|
||||
use crate::host::json::{json_to_value, value_to_json};
|
||||
use crate::host::json::value_to_json;
|
||||
use crate::host::{HostCaps, HostContext};
|
||||
use crate::value::{CodeBlock, Value};
|
||||
|
||||
@@ -158,6 +158,7 @@ pub(crate) struct Execution {
|
||||
pub lang: String,
|
||||
pub cmd: String,
|
||||
pub script: String,
|
||||
pub diagnostic_source: String,
|
||||
}
|
||||
|
||||
impl Execution {
|
||||
@@ -180,6 +181,7 @@ impl Execution {
|
||||
("result_error".into(), Value::Text(result_error)),
|
||||
("error".into(), Value::Text(self.error.clone())),
|
||||
("script".into(), Value::Text(self.script.clone())),
|
||||
("diagnostic_source".into(), Value::Text(self.diagnostic_source.clone())),
|
||||
("cached".into(), Value::Bool(false)),
|
||||
])
|
||||
}
|
||||
@@ -588,10 +590,11 @@ fn prepare_invoke(args: &InvokeArgs<'_>) -> Result<PreparedInvoke, String> {
|
||||
let stdin = opt_text(args.stdin)?;
|
||||
let input_json = match args.input {
|
||||
None | Some(Value::None) => None,
|
||||
Some(v) => Some(
|
||||
serde_json::to_string(&value_to_json(v)?)
|
||||
.map_err(|e| format!("input JSON encode: {e}"))?,
|
||||
),
|
||||
Some(v) => {
|
||||
super::oracle::admit(v)?;
|
||||
Some(serde_json::to_string(&value_to_json(v)?)
|
||||
.map_err(|e| format!("input JSON encode: {e}"))?)
|
||||
},
|
||||
};
|
||||
if stdin.is_some() && input_json.is_some() {
|
||||
return Err("stdin and input are mutually exclusive".into());
|
||||
@@ -620,7 +623,7 @@ pub fn invoke(ctx: &mut HostContext, args: InvokeArgs<'_>) -> Result<Value, Stri
|
||||
ensure_config(ctx);
|
||||
let prepared = prepare_invoke(&args)?;
|
||||
let exec = execute_job(ctx, &prepared.job)?;
|
||||
let (result, result_error) = parse_output(&exec.stdout, &prepared.output);
|
||||
let (result, result_error) = parse_output(&exec.stdout, &prepared.output)?;
|
||||
Ok(exec.record(result, result_error))
|
||||
}
|
||||
|
||||
@@ -636,13 +639,10 @@ pub fn call(ctx: &mut HostContext, args: InvokeArgs<'_>) -> Result<Value, String
|
||||
if exec.stdout.trim().is_empty() {
|
||||
return Ok(Value::None);
|
||||
}
|
||||
match serde_json::from_str::<serde_json::Value>(&exec.stdout) {
|
||||
Ok(j) => json_to_value(&j),
|
||||
Err(e) => Err(format!(
|
||||
"foreign call: stdout is not JSON: {e}; stdout: {}",
|
||||
tail(exec.stdout.trim(), 512)
|
||||
)),
|
||||
}
|
||||
super::json::decode_text(&exec.stdout).map_err(|e| match e {
|
||||
super::json::DecodeError::Domain(e) => e,
|
||||
super::json::DecodeError::Syntax(e) => format!("foreign call: stdout is not JSON: {e}; stdout: {}", tail(exec.stdout.trim(), 512)),
|
||||
})
|
||||
}
|
||||
|
||||
fn present(v: Option<&Value>) -> Option<&Value> {
|
||||
@@ -752,17 +752,18 @@ fn error_record(ctx: &HostContext, job: &Job, error: String) -> Value {
|
||||
lang: job.lang.clone(),
|
||||
cmd: display_for_job(ctx, job, None),
|
||||
script: String::new(),
|
||||
diagnostic_source: String::new(),
|
||||
}
|
||||
.record(Value::None, String::new())
|
||||
}
|
||||
|
||||
fn run_prepared(env: &ForeignEnv, items: Vec<PreparedMany>, concurrency: usize) -> Vec<(usize, Value)> {
|
||||
fn run_prepared(env: &ForeignEnv, items: Vec<PreparedMany>, concurrency: usize) -> Result<Vec<(usize, Value)>, String> {
|
||||
if items.is_empty() {
|
||||
return Vec::new();
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let workers = concurrency.max(1).min(items.len());
|
||||
let queue = Arc::new(Mutex::new(VecDeque::from(items)));
|
||||
let results: Arc<Mutex<Vec<(usize, Value)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
let results: Arc<Mutex<Vec<(usize, Result<Value, String>)>>> = Arc::new(Mutex::new(Vec::new()));
|
||||
thread::scope(|scope| {
|
||||
for _ in 0..workers {
|
||||
let queue = Arc::clone(&queue);
|
||||
@@ -782,11 +783,10 @@ fn run_prepared(env: &ForeignEnv, items: Vec<PreparedMany>, concurrency: usize)
|
||||
execute_job(&ctx, &item.job)
|
||||
})) {
|
||||
Ok(Ok(exec)) => {
|
||||
let (result, result_error) = parse_output(&exec.stdout, &item.output);
|
||||
exec.record(result, result_error)
|
||||
parse_output(&exec.stdout, &item.output).map(|(result, error)| exec.record(result, error))
|
||||
}
|
||||
Ok(Err(e)) => error_record(&ctx, &item.job, e),
|
||||
Err(_) => error_record(&ctx, &item.job, "foreign worker panicked".into()),
|
||||
Ok(Err(e)) => Ok(error_record(&ctx, &item.job, e)),
|
||||
Err(_) => Ok(error_record(&ctx, &item.job, "foreign worker panicked".into())),
|
||||
};
|
||||
if let Ok(mut out) = results.lock() {
|
||||
out.push((item.idx, value));
|
||||
@@ -799,7 +799,7 @@ fn run_prepared(env: &ForeignEnv, items: Vec<PreparedMany>, concurrency: usize)
|
||||
Err(shared) => shared.lock().map(|m| m.clone()).unwrap_or_default(),
|
||||
};
|
||||
out.sort_by_key(|(i, _)| *i);
|
||||
out
|
||||
out.into_iter().map(|(i, result)| result.map(|value| (i, value)).map_err(|e| format!("foreign[{i}]: {e}"))).collect()
|
||||
}
|
||||
|
||||
/// Build a prepared job for one `runs` item (code value or option map).
|
||||
@@ -851,7 +851,7 @@ pub fn run_many(
|
||||
requested
|
||||
};
|
||||
let env = ForeignEnv::from_ctx(ctx);
|
||||
let results = run_prepared(&env, prepared, concurrency);
|
||||
let results = run_prepared(&env, prepared, concurrency)?;
|
||||
Ok(Value::List(results.into_iter().map(|(_, v)| v).collect()))
|
||||
}
|
||||
|
||||
@@ -879,6 +879,7 @@ pub fn call_many(
|
||||
};
|
||||
let mut prepared = Vec::with_capacity(n);
|
||||
for (idx, input) in list.iter().enumerate() {
|
||||
super::oracle::admit(input)?;
|
||||
let json = serde_json::to_string(&value_to_json(input)?)
|
||||
.map_err(|e| format!("call_many input JSON encode: {e}"))?;
|
||||
let mut job = base.job.clone();
|
||||
@@ -891,7 +892,7 @@ pub fn call_many(
|
||||
});
|
||||
}
|
||||
let env = ForeignEnv::from_ctx(ctx);
|
||||
let records = run_prepared(&env, prepared, concurrency);
|
||||
let records = run_prepared(&env, prepared, concurrency)?;
|
||||
let mut results = Vec::with_capacity(records.len());
|
||||
let mut errors = Vec::new();
|
||||
for (idx, record) in records {
|
||||
@@ -936,34 +937,15 @@ fn resolve_invoke_source(args: &InvokeArgs<'_>) -> Result<(String, String), Stri
|
||||
))
|
||||
}
|
||||
|
||||
fn parse_output(stdout: &str, mode: &str) -> (Value, String) {
|
||||
match mode {
|
||||
"text" => (Value::None, String::new()),
|
||||
"lines" => (
|
||||
Value::List(stdout.lines().map(|l| Value::Text(l.to_string())).collect()),
|
||||
String::new(),
|
||||
),
|
||||
"json" => {
|
||||
if stdout.trim().is_empty() {
|
||||
return (Value::None, String::new());
|
||||
}
|
||||
match serde_json::from_str::<serde_json::Value>(stdout) {
|
||||
Ok(j) => match json_to_value(&j) {
|
||||
Ok(v) => (v, String::new()),
|
||||
Err(e) => (Value::None, e),
|
||||
},
|
||||
Err(e) => (Value::None, format!("stdout is not JSON: {e}")),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
if stdout.trim().is_empty() {
|
||||
return (Value::None, String::new());
|
||||
}
|
||||
match serde_json::from_str::<serde_json::Value>(stdout) {
|
||||
Ok(j) => (json_to_value(&j).unwrap_or(Value::None), String::new()),
|
||||
Err(_) => (Value::None, String::new()),
|
||||
}
|
||||
}
|
||||
fn parse_output(stdout: &str, mode: &str) -> Result<(Value, String), String> {
|
||||
if mode == "text" { return Ok((Value::None, String::new())); }
|
||||
if mode == "lines" { return Ok((Value::List(stdout.lines().map(|s| Value::Text(s.into())).collect()), String::new())); }
|
||||
if stdout.trim().is_empty() { return Ok((Value::None, String::new())); }
|
||||
match super::json::decode_text(stdout) {
|
||||
Ok(v) => Ok((v, String::new())),
|
||||
Err(super::json::DecodeError::Domain(e)) => Err(e),
|
||||
Err(super::json::DecodeError::Syntax(e)) if mode == "json" => Ok((Value::None, format!("stdout is not JSON: {e}"))),
|
||||
Err(super::json::DecodeError::Syntax(_)) => Ok((Value::None, String::new())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1734,6 +1716,7 @@ fn execute_job(ctx: &HostContext, job: &Job) -> Result<Execution, String> {
|
||||
lang: job.lang.clone(),
|
||||
cmd: display_for_job(ctx, job, None),
|
||||
script: String::new(),
|
||||
diagnostic_source: String::new(),
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -1803,6 +1786,7 @@ fn execute_job(ctx: &HostContext, job: &Job) -> Result<Execution, String> {
|
||||
lang: job.lang.clone(),
|
||||
cmd,
|
||||
script: script_keep,
|
||||
diagnostic_source: script_path.display().to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1837,7 +1821,7 @@ pub fn invoke_for_view(
|
||||
cmd_override: cmd_override.map(str::to_string),
|
||||
};
|
||||
let exec = execute_job(&ctx, &job)?;
|
||||
let (result, result_error) = parse_output(&exec.stdout, "auto");
|
||||
let (result, result_error) = parse_output(&exec.stdout, "auto")?;
|
||||
Ok(exec.record(result, result_error))
|
||||
}
|
||||
|
||||
@@ -1886,13 +1870,13 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn output_modes() {
|
||||
let (v, e) = parse_output("42", "auto");
|
||||
let (v, e) = parse_output("42", "auto").unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert_eq!(v, Value::Int(42));
|
||||
let (v, e) = parse_output("a\nb\n", "lines");
|
||||
let (v, e) = parse_output("a\nb\n", "lines").unwrap();
|
||||
assert!(e.is_empty());
|
||||
assert_eq!(v, Value::List(vec![Value::Text("a".into()), Value::Text("b".into())]));
|
||||
let (v, e) = parse_output("not json", "json");
|
||||
let (v, e) = parse_output("not json", "json").unwrap();
|
||||
assert!(v == Value::None);
|
||||
assert!(!e.is_empty());
|
||||
}
|
||||
@@ -1965,4 +1949,19 @@ mod tests {
|
||||
assert_eq!(map_get(&records[1], "ok"), Some(&Value::Bool(false)));
|
||||
assert_eq!(map_get(&records[2], "stdout").and_then(|v| v.reveal_text()), Some("c\n"));
|
||||
}
|
||||
#[test]
|
||||
fn structured_output_domain_errors_are_not_none_or_success_records() {
|
||||
for mode in ["auto", "json"] {
|
||||
for bad in ["9007199254740992", "9.007199254740992e15", "1e9999", r#"{"x":1,"x":2}"#, r#"{"a":[],"b":[1]}"#] {
|
||||
assert!(parse_output(bad, mode).is_err(), "{mode}: {bad}");
|
||||
}
|
||||
}
|
||||
let ctx = HostContext::default();
|
||||
let env = ForeignEnv::from_ctx(&ctx);
|
||||
let items = (0..2).map(|idx| PreparedMany {
|
||||
idx, job: Job::simple("python", "print('{\"x\":1,\"x\":2}')", None), output: "auto".into(),
|
||||
}).collect();
|
||||
assert!(run_prepared(&env, items, 2).unwrap_err().contains("duplicate"));
|
||||
}
|
||||
|
||||
}
|
||||
+389
-252
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,174 @@
|
||||
//! Concurrent control inputs are scoped to a single recorded document action.
|
||||
//! Replay supplies their elapsed-time inputs, reobserves acceptance, and stops
|
||||
//! on divergence; elapsed wall time is not a deterministic foreign-state oracle.
|
||||
use crate::host::foreign_session::InterruptHandle;
|
||||
use crate::value::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct ControlEvent {
|
||||
pub after_us: u64,
|
||||
pub results: Vec<(String, Result<bool, String>)>,
|
||||
}
|
||||
impl ControlEvent {
|
||||
pub fn value(&self) -> Value {
|
||||
Value::Map(vec![
|
||||
("after_us".into(), Value::Int(self.after_us as i64)),
|
||||
(
|
||||
"results".into(),
|
||||
Value::List(
|
||||
self.results
|
||||
.iter()
|
||||
.map(|(name, result)| {
|
||||
Value::Map(vec![
|
||||
("kernel".into(), Value::Text(name.clone())),
|
||||
("accepted".into(), Value::Bool(result.is_ok())),
|
||||
("active".into(), Value::Bool(matches!(result, Ok(true)))),
|
||||
(
|
||||
"error".into(),
|
||||
Value::Text(result.as_ref().err().cloned().unwrap_or_default()),
|
||||
),
|
||||
])
|
||||
})
|
||||
.collect(),
|
||||
),
|
||||
),
|
||||
])
|
||||
}
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct State {
|
||||
kernels: BTreeMap<String, InterruptHandle>,
|
||||
generation: u64,
|
||||
action: Option<(Instant, Vec<ControlEvent>)>,
|
||||
}
|
||||
#[derive(Default, Debug)]
|
||||
struct Shared {
|
||||
state: Mutex<State>,
|
||||
changed: Condvar,
|
||||
}
|
||||
#[derive(Clone, Default, Debug)]
|
||||
pub struct DocumentControl(Arc<Shared>);
|
||||
|
||||
impl DocumentControl {
|
||||
pub(super) fn cancelled(&self) -> bool {
|
||||
self.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.action
|
||||
.as_ref()
|
||||
.is_some_and(|(_, events)| !events.is_empty())
|
||||
}
|
||||
pub(super) fn register(&self, kernel: &str, handle: InterruptHandle) {
|
||||
self.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.kernels
|
||||
.insert(kernel.into(), handle);
|
||||
}
|
||||
pub(super) fn begin(&self, plan: Vec<ControlEvent>) -> Option<JoinHandle<()>> {
|
||||
let generation = {
|
||||
let mut state = self.0.state.lock().unwrap();
|
||||
state.generation += 1;
|
||||
state.action = Some((Instant::now(), Vec::new()));
|
||||
state.generation
|
||||
};
|
||||
if plan.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let controller = self.clone();
|
||||
Some(std::thread::spawn(move || {
|
||||
for event in plan {
|
||||
let mut state = controller.0.state.lock().unwrap();
|
||||
loop {
|
||||
if state.generation != generation || state.action.is_none() {
|
||||
return;
|
||||
}
|
||||
let elapsed = state.action.as_ref().unwrap().0.elapsed();
|
||||
let remaining = Duration::from_micros(event.after_us).saturating_sub(elapsed);
|
||||
if remaining.is_zero() {
|
||||
break;
|
||||
}
|
||||
state = controller
|
||||
.0
|
||||
.changed
|
||||
.wait_timeout(state, remaining.min(Duration::from_millis(200)))
|
||||
.unwrap()
|
||||
.0;
|
||||
}
|
||||
// Keep the action-generation check and signal under one lock.
|
||||
let _ = Self::request_locked(&mut state, Some(event.after_us));
|
||||
}
|
||||
}))
|
||||
}
|
||||
pub(super) fn finish(&self, scheduler: Option<JoinHandle<()>>) -> Vec<ControlEvent> {
|
||||
let events = self
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.action
|
||||
.take()
|
||||
.map(|(_, events)| events)
|
||||
.unwrap_or_default();
|
||||
self.0.changed.notify_all();
|
||||
if let Some(scheduler) = scheduler {
|
||||
let _ = scheduler.join();
|
||||
}
|
||||
events
|
||||
}
|
||||
pub fn interrupt(&self) -> Result<Value, String> {
|
||||
let mut state = self
|
||||
.0
|
||||
.state
|
||||
.lock()
|
||||
.map_err(|_| "document control lock poisoned")?;
|
||||
Self::request_locked(&mut state, None).map(|event| event.value())
|
||||
}
|
||||
fn request_locked(
|
||||
state: &mut State,
|
||||
scheduled_us: Option<u64>,
|
||||
) -> Result<ControlEvent, String> {
|
||||
let start = state
|
||||
.action
|
||||
.as_ref()
|
||||
.ok_or("no document action in flight")?
|
||||
.0;
|
||||
let after_us = scheduled_us
|
||||
.unwrap_or_else(|| start.elapsed().as_micros().min(i64::MAX as u128) as u64);
|
||||
let results = state
|
||||
.kernels
|
||||
.iter()
|
||||
.filter(|(_, handle)| handle.is_live())
|
||||
.map(|(name, handle)| (name.clone(), handle.request()))
|
||||
.collect();
|
||||
let event = ControlEvent { after_us, results };
|
||||
state.action.as_mut().unwrap().1.push(event.clone());
|
||||
Ok(event)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn completed_action_cancels_pending_scheduler_before_next_generation() {
|
||||
let controller = DocumentControl::default();
|
||||
let scheduler = controller.begin(vec![ControlEvent {
|
||||
after_us: 60_000_000,
|
||||
results: Vec::new(),
|
||||
}]);
|
||||
let start = Instant::now();
|
||||
assert!(controller.finish(scheduler).is_empty());
|
||||
assert!(start.elapsed() < Duration::from_secs(1));
|
||||
assert!(controller.interrupt().is_err());
|
||||
let next = controller.begin(Vec::new());
|
||||
assert!(!controller.cancelled());
|
||||
assert!(controller.finish(next).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
//! Lossless, typed, bottom-up sharing for complete history snapshots.
|
||||
//! References always point backwards. Expansion costs and depth are checked
|
||||
//! before building the expanded value, so a small DAG cannot expand unboundedly.
|
||||
use crate::host::{json::value_to_json, oracle::admit};
|
||||
use crate::value::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
const FORMAT: &str = "marqdo.history.dag";
|
||||
const MAX_NODES: usize = 1_000_000;
|
||||
const MAX_VALUES: usize = 8_000_000;
|
||||
const MAX_BYTES: usize = 512 * 1024 * 1024;
|
||||
const MAX_DEPTH: usize = 128;
|
||||
|
||||
fn text(s: &str) -> Value {
|
||||
Value::Text(s.into())
|
||||
}
|
||||
fn list(v: &Value) -> Result<&[Value], String> {
|
||||
if let Value::List(v) = v {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err("snapshot DAG: expected list".into())
|
||||
}
|
||||
}
|
||||
fn string(v: &Value) -> Result<&str, String> {
|
||||
if let Value::Text(v) = v {
|
||||
Ok(v)
|
||||
} else {
|
||||
Err("snapshot DAG: expected text".into())
|
||||
}
|
||||
}
|
||||
fn field<'a>(v: &'a Value, key: &str) -> Result<&'a Value, String> {
|
||||
if let Value::Map(fields) = v {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == key)
|
||||
.map(|(_, v)| v)
|
||||
.ok_or_else(|| format!("snapshot DAG: missing {key}"))
|
||||
} else {
|
||||
Err("snapshot DAG: expected object".into())
|
||||
}
|
||||
}
|
||||
fn wire(v: &Value) -> Result<String, String> {
|
||||
serde_json::to_string(&value_to_json(v)?).map_err(|e| e.to_string())
|
||||
}
|
||||
fn checksum(root: &Value, nodes: &Value) -> Result<String, String> {
|
||||
Ok(format!(
|
||||
"{:x}",
|
||||
Sha256::digest(wire(&Value::List(vec![root.clone(), nodes.clone()]))?.as_bytes())
|
||||
))
|
||||
}
|
||||
pub fn is_packed(v: &Value) -> bool {
|
||||
field(v, "format").ok() == Some(&text(FORMAT))
|
||||
}
|
||||
|
||||
pub fn pack(snapshot: &Value) -> Result<Value, String> {
|
||||
fn intern(
|
||||
v: &Value,
|
||||
nodes: &mut Vec<Value>,
|
||||
seen: &mut HashMap<String, usize>,
|
||||
depth: usize,
|
||||
) -> Result<usize, String> {
|
||||
if depth > MAX_DEPTH {
|
||||
return Err("snapshot DAG: depth budget exceeded".into());
|
||||
}
|
||||
let row = match v {
|
||||
Value::None => vec![text("null")],
|
||||
Value::Bool(v) => vec![text("bool"), Value::Bool(*v)],
|
||||
Value::Int(v) => vec![text("int"), text(&v.to_string())],
|
||||
Value::Num(v) => vec![text("float"), text(&format!("{:016x}", v.to_bits()))],
|
||||
Value::Text(v) => vec![text("text"), text(v)],
|
||||
Value::List(values) => {
|
||||
let refs = values
|
||||
.iter()
|
||||
.map(|v| intern(v, nodes, seen, depth + 1).map(|i| Value::Int(i as i64)))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
vec![text("list"), Value::List(refs)]
|
||||
}
|
||||
Value::Map(fields) => {
|
||||
let refs = fields
|
||||
.iter()
|
||||
.map(|(k, v)| {
|
||||
intern(v, nodes, seen, depth + 1)
|
||||
.map(|i| Value::List(vec![text(k), Value::Int(i as i64)]))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
vec![text("map"), Value::List(refs)]
|
||||
}
|
||||
_ => return Err("snapshot DAG: value outside V_safe".into()),
|
||||
};
|
||||
let row = Value::List(row);
|
||||
let key = wire(&row)?;
|
||||
if let Some(index) = seen.get(&key) {
|
||||
return Ok(*index);
|
||||
}
|
||||
if nodes.len() >= MAX_NODES {
|
||||
return Err("snapshot DAG: node budget exceeded".into());
|
||||
}
|
||||
let index = nodes.len();
|
||||
nodes.push(row);
|
||||
seen.insert(key, index);
|
||||
Ok(index)
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let root = intern(snapshot, &mut nodes, &mut HashMap::new(), 0)?;
|
||||
admit(snapshot)?;
|
||||
let nodes = Value::List(nodes);
|
||||
let root = Value::Int(root as i64);
|
||||
let hash = checksum(&root, &nodes)?;
|
||||
let envelope = Value::Map(vec![
|
||||
("format".into(), text(FORMAT)),
|
||||
("version".into(), Value::Int(1)),
|
||||
("root".into(), root),
|
||||
("nodes".into(), nodes),
|
||||
("sha256".into(), text(&hash)),
|
||||
]);
|
||||
// Apply exactly the decoder's resource limits to locally produced envelopes.
|
||||
validate(&envelope)?;
|
||||
Ok(envelope)
|
||||
}
|
||||
|
||||
enum Node {
|
||||
Atom(Value),
|
||||
List(Vec<usize>),
|
||||
Map(Vec<(String, usize)>),
|
||||
}
|
||||
impl Node {
|
||||
fn refs(&self) -> Vec<usize> {
|
||||
match self {
|
||||
Self::Atom(_) => Vec::new(),
|
||||
Self::List(v) => v.clone(),
|
||||
Self::Map(v) => v.iter().map(|(_, i)| *i).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn index(v: &Value, before: usize) -> Result<usize, String> {
|
||||
match v {
|
||||
Value::Int(i) if *i >= 0 && (*i as u64) < before as u64 => Ok(*i as usize),
|
||||
_ => Err("snapshot DAG: forward/cyclic/out-of-range reference".into()),
|
||||
}
|
||||
}
|
||||
fn validate(envelope: &Value) -> Result<(Vec<Node>, usize), String> {
|
||||
let Value::Map(fields) = envelope else {
|
||||
return Err("snapshot DAG: expected envelope".into());
|
||||
};
|
||||
let names: HashSet<_> = fields.iter().map(|(k, _)| k.as_str()).collect();
|
||||
if fields.len() != 5
|
||||
|| names != HashSet::from(["format", "version", "root", "nodes", "sha256"])
|
||||
|| string(field(envelope, "format")?)? != FORMAT
|
||||
|| field(envelope, "version")? != &Value::Int(1)
|
||||
{
|
||||
return Err("snapshot DAG: invalid envelope schema".into());
|
||||
}
|
||||
let rows = list(field(envelope, "nodes")?)?;
|
||||
if rows.is_empty() || rows.len() > MAX_NODES {
|
||||
return Err("snapshot DAG: node budget exceeded".into());
|
||||
}
|
||||
let root = index(field(envelope, "root")?, rows.len())?;
|
||||
if root + 1 != rows.len() {
|
||||
return Err("snapshot DAG: root must be last".into());
|
||||
}
|
||||
let expected = string(field(envelope, "sha256")?)?;
|
||||
if expected != checksum(field(envelope, "root")?, field(envelope, "nodes")?)? {
|
||||
return Err("snapshot DAG: checksum differs".into());
|
||||
}
|
||||
let mut nodes = Vec::new();
|
||||
let mut costs: Vec<(usize, usize, usize)> = Vec::new();
|
||||
let mut unique = HashSet::new();
|
||||
for (i, raw) in rows.iter().enumerate() {
|
||||
if !unique.insert(wire(raw)?) {
|
||||
return Err("snapshot DAG: duplicate dictionary node".into());
|
||||
}
|
||||
let row = list(raw)?;
|
||||
let tag = string(row.first().ok_or("snapshot DAG: empty node")?)?;
|
||||
let node = match (tag, row) {
|
||||
("null", [_]) => Node::Atom(Value::None),
|
||||
("bool", [_, Value::Bool(v)]) => Node::Atom(Value::Bool(*v)),
|
||||
("text", [_, Value::Text(v)]) => Node::Atom(text(v)),
|
||||
("int", [_, Value::Text(v)]) => {
|
||||
let n = v
|
||||
.parse::<i64>()
|
||||
.map_err(|_| "snapshot DAG: invalid integer")?;
|
||||
if n.to_string() != *v {
|
||||
return Err("snapshot DAG: noncanonical integer".into());
|
||||
}
|
||||
Node::Atom(Value::Int(n))
|
||||
}
|
||||
("float", [_, Value::Text(v)]) if v.len() == 16 => {
|
||||
let bits =
|
||||
u64::from_str_radix(v, 16).map_err(|_| "snapshot DAG: invalid float bits")?;
|
||||
if format!("{bits:016x}") != *v {
|
||||
return Err("snapshot DAG: noncanonical float bits".into());
|
||||
}
|
||||
Node::Atom(Value::Num(f64::from_bits(bits)))
|
||||
}
|
||||
("list", [_, refs]) => Node::List(
|
||||
list(refs)?
|
||||
.iter()
|
||||
.map(|v| index(v, i))
|
||||
.collect::<Result<_, _>>()?,
|
||||
),
|
||||
("map", [_, refs]) => {
|
||||
let mut keys = HashSet::new();
|
||||
let mut fields = Vec::new();
|
||||
for pair in list(refs)? {
|
||||
let [key, value] = list(pair)? else {
|
||||
return Err("snapshot DAG: invalid map pair".into());
|
||||
};
|
||||
let key = string(key)?;
|
||||
if !keys.insert(key) {
|
||||
return Err("snapshot DAG: duplicate map key".into());
|
||||
}
|
||||
fields.push((key.into(), index(value, i)?));
|
||||
}
|
||||
Node::Map(fields)
|
||||
}
|
||||
_ => return Err("snapshot DAG: invalid node tag/payload".into()),
|
||||
};
|
||||
let mut values = 1usize;
|
||||
let mut bytes = match &node {
|
||||
Node::Atom(v) => {
|
||||
admit(v)?;
|
||||
match v {
|
||||
Value::Text(s) => s
|
||||
.len()
|
||||
.checked_mul(6)
|
||||
.and_then(|n| n.checked_add(2))
|
||||
.ok_or("snapshot DAG: size overflow")?,
|
||||
_ => 32,
|
||||
}
|
||||
}
|
||||
Node::Map(v) => v
|
||||
.iter()
|
||||
.try_fold(2usize, |n, (k, _)| {
|
||||
n.checked_add(k.len().checked_mul(6)?.checked_add(4)?)
|
||||
})
|
||||
.ok_or("snapshot DAG: size overflow")?,
|
||||
Node::List(_) => 2,
|
||||
};
|
||||
let mut depth = 1;
|
||||
for reference in node.refs() {
|
||||
let (count, size, height) = costs[reference];
|
||||
values = values
|
||||
.checked_add(count)
|
||||
.ok_or("snapshot DAG: expansion overflow")?;
|
||||
bytes = bytes
|
||||
.checked_add(size)
|
||||
.and_then(|n| n.checked_add(1))
|
||||
.ok_or("snapshot DAG: expansion overflow")?;
|
||||
depth = depth.max(height + 1);
|
||||
}
|
||||
if values > MAX_VALUES || bytes > MAX_BYTES || depth > MAX_DEPTH {
|
||||
return Err("snapshot DAG: expansion budget exceeded".into());
|
||||
}
|
||||
costs.push((values, bytes, depth));
|
||||
nodes.push(node);
|
||||
}
|
||||
let mut reachable = HashSet::new();
|
||||
let mut todo = vec![root];
|
||||
while let Some(i) = todo.pop() {
|
||||
if reachable.insert(i) {
|
||||
todo.extend(nodes[i].refs());
|
||||
}
|
||||
}
|
||||
if reachable.len() != nodes.len() {
|
||||
return Err("snapshot DAG: unreachable dictionary node".into());
|
||||
}
|
||||
Ok((nodes, root))
|
||||
}
|
||||
|
||||
pub fn unpack(envelope: &Value) -> Result<Value, String> {
|
||||
fn expand(nodes: &[Node], i: usize) -> Value {
|
||||
match &nodes[i] {
|
||||
Node::Atom(v) => v.clone(),
|
||||
Node::List(refs) => Value::List(refs.iter().map(|i| expand(nodes, *i)).collect()),
|
||||
Node::Map(fields) => Value::Map(
|
||||
fields
|
||||
.iter()
|
||||
.map(|(k, i)| (k.clone(), expand(nodes, *i)))
|
||||
.collect(),
|
||||
),
|
||||
}
|
||||
}
|
||||
let (nodes, root) = validate(envelope)?;
|
||||
let value = expand(&nodes, root);
|
||||
admit(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn envelope(rows: Vec<Value>) -> Value {
|
||||
let root = Value::Int(rows.len() as i64 - 1);
|
||||
let nodes = Value::List(rows);
|
||||
let hash = checksum(&root, &nodes).unwrap();
|
||||
Value::Map(vec![
|
||||
("format".into(), text(FORMAT)),
|
||||
("version".into(), Value::Int(1)),
|
||||
("root".into(), root),
|
||||
("nodes".into(), nodes),
|
||||
("sha256".into(), text(&hash)),
|
||||
])
|
||||
}
|
||||
fn row(tag: &str, value: Value) -> Value {
|
||||
Value::List(vec![text(tag), value])
|
||||
}
|
||||
#[test]
|
||||
fn typed_roundtrip_preserves_order_float_bits_and_repeated_values() {
|
||||
let shared = Value::Map(vec![
|
||||
(
|
||||
"z".into(),
|
||||
Value::List(vec![
|
||||
Value::None,
|
||||
Value::Bool(true),
|
||||
Value::Int(1),
|
||||
Value::Num(-0.0),
|
||||
Value::Num(1.25),
|
||||
]),
|
||||
),
|
||||
("汉字".into(), text("🧪")),
|
||||
]);
|
||||
let input = Value::List(vec![shared; 128]);
|
||||
let packed = pack(&input).unwrap();
|
||||
let decoded_wire =
|
||||
crate::host::json::parse(&crate::host::json::stringify(&packed, None).unwrap())
|
||||
.unwrap();
|
||||
let expanded = unpack(&decoded_wire).unwrap();
|
||||
assert_eq!(input, expanded);
|
||||
assert_eq!(wire(&input).unwrap(), wire(&expanded).unwrap());
|
||||
let Value::List(ref xs) = expanded else {
|
||||
panic!()
|
||||
};
|
||||
let Value::Map(ref fields) = xs[0] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(fields[0].0, "z");
|
||||
let Value::List(ref values) = fields[0].1 else {
|
||||
panic!()
|
||||
};
|
||||
let Value::Num(number) = values[3] else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(number.to_bits(), (-0.0f64).to_bits());
|
||||
assert!(list(field(&packed, "nodes").unwrap()).unwrap().len() < 20);
|
||||
assert!(wire(&packed).unwrap().len() < wire(&input).unwrap().len());
|
||||
}
|
||||
#[test]
|
||||
fn refuses_cycles_amplification_unreachable_duplicates_and_unsafe_atoms() {
|
||||
let bad = [
|
||||
envelope(vec![row("list", Value::List(vec![Value::Int(0)]))]),
|
||||
envelope(vec![row("text", text("unused")), row("text", text("root"))]),
|
||||
envelope(vec![row("text", text("same")), row("text", text("same"))]),
|
||||
envelope(vec![row("int", text("9007199254740992"))]),
|
||||
envelope(vec![row("float", text("7ff8000000000000"))]),
|
||||
envelope(vec![row("int", text("00"))]),
|
||||
];
|
||||
for value in bad {
|
||||
assert!(unpack(&value).is_err());
|
||||
}
|
||||
let mut rows = vec![row("text", text("x"))];
|
||||
for n in 0..40 {
|
||||
rows.push(row("list", Value::List(vec![Value::Int(n), Value::Int(n)])));
|
||||
}
|
||||
let error = unpack(&envelope(rows)).unwrap_err();
|
||||
assert!(error.contains("budget"), "{error}");
|
||||
let mut hash = pack(&Value::Int(1)).unwrap();
|
||||
if let Value::Map(ref mut fields) = hash {
|
||||
fields.iter_mut().find(|(k, _)| k == "sha256").unwrap().1 = text("bad");
|
||||
}
|
||||
assert!(unpack(&hash).unwrap_err().contains("checksum"));
|
||||
}
|
||||
#[test]
|
||||
fn sharing_does_not_admit_ragged_columns_or_duplicate_keys() {
|
||||
let ragged = Value::Map(vec![
|
||||
("a".into(), Value::List(vec![Value::Int(1)])),
|
||||
("b".into(), Value::List(Vec::new())),
|
||||
]);
|
||||
assert!(pack(&ragged).is_err());
|
||||
let duplicate = Value::Map(vec![
|
||||
("a".into(), Value::Int(1)),
|
||||
("a".into(), Value::Int(2)),
|
||||
]);
|
||||
assert!(pack(&duplicate).is_err());
|
||||
let value = envelope(vec![
|
||||
row("int", text("1")),
|
||||
row("list", Value::List(vec![Value::Int(0)])),
|
||||
row("list", Value::List(Vec::new())),
|
||||
row(
|
||||
"map",
|
||||
Value::List(vec![
|
||||
Value::List(vec![text("a"), Value::Int(1)]),
|
||||
Value::List(vec![text("b"), Value::Int(2)]),
|
||||
]),
|
||||
),
|
||||
]);
|
||||
assert!(unpack(&value).is_err());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+455
-38
@@ -16,11 +16,15 @@ use crate::host::json::{json_to_value, value_to_json};
|
||||
use crate::host::HostContext;
|
||||
use crate::value::Value;
|
||||
|
||||
mod control;
|
||||
pub mod validation;
|
||||
pub use control::InterruptHandle;
|
||||
|
||||
const SESSION_TIMEOUT_SECS: f64 = 10.0;
|
||||
const MAX_SESSION_TIMEOUT_SECS: f64 = 3600.0;
|
||||
const MAX_PROCESS_STDERR: usize = 1_048_576;
|
||||
|
||||
const PY_BOOTSTRAP: &str = r#"import sys, json, io, ast, traceback, contextlib
|
||||
const PY_BOOTSTRAP: &str = r#"import sys, json, io, ast, traceback, contextlib, math, signal
|
||||
_out = sys.stdout
|
||||
_MAX_SAFE = 9007199254740991
|
||||
def _sanitize(o):
|
||||
@@ -31,13 +35,19 @@ def _sanitize(o):
|
||||
raise ValueError("json: integer outside V_safe (±(2^53-1)): %s" % o)
|
||||
return o
|
||||
if isinstance(o, float):
|
||||
if not math.isfinite(o):
|
||||
raise ValueError("json: non-finite number outside V_safe")
|
||||
if o.is_integer() and abs(o) > _MAX_SAFE:
|
||||
raise ValueError("json: integer outside V_safe (±(2^53-1)): %s" % o)
|
||||
return o
|
||||
if isinstance(o, str):
|
||||
return o
|
||||
if isinstance(o, (list, tuple)):
|
||||
return [_sanitize(x) for x in o]
|
||||
if isinstance(o, dict):
|
||||
return {str(k): _sanitize(v) for k, v in o.items()}
|
||||
if any(not isinstance(k, str) for k in o):
|
||||
raise TypeError("not JSON-safe: object keys must be strings")
|
||||
return {k: _sanitize(v) for k, v in o.items()}
|
||||
raise TypeError("not JSON-safe: %s" % type(o).__name__)
|
||||
def _send(o):
|
||||
try:
|
||||
@@ -48,10 +58,17 @@ def _send(o):
|
||||
"id": rid, "ok": False,
|
||||
"stdout": (o.get("stdout") if isinstance(o, dict) else "") or "",
|
||||
"stderr": (o.get("stderr") if isinstance(o, dict) else "") or "",
|
||||
"result": None, "error": str(e),
|
||||
"result": None, "error": str(e), "domain_error": True,
|
||||
}, ensure_ascii=False)
|
||||
_out.write(line + "\n")
|
||||
_out.flush()
|
||||
_busy = False
|
||||
def _interrupt(signum, frame):
|
||||
global _busy
|
||||
if _busy:
|
||||
_busy = False
|
||||
raise KeyboardInterrupt
|
||||
signal.signal(signal.SIGINT, _interrupt)
|
||||
_g = {"__name__": "__main__", "marqdo_input": None}
|
||||
for _line in sys.stdin:
|
||||
_line = _line.strip()
|
||||
@@ -87,6 +104,8 @@ for _line in sys.stdin:
|
||||
_out_buf = io.StringIO()
|
||||
_err_buf = io.StringIO()
|
||||
try:
|
||||
_busy = True
|
||||
_send({"id": rid, "phase": "ready"})
|
||||
_tree = ast.parse(_code, "<marqdo>")
|
||||
_result = None
|
||||
with contextlib.redirect_stdout(_out_buf), contextlib.redirect_stderr(_err_buf):
|
||||
@@ -97,10 +116,13 @@ for _line in sys.stdin:
|
||||
_result = eval(compile(ast.Expression(_last.value), "<marqdo>", "eval"), _g)
|
||||
else:
|
||||
exec(compile(_tree, "<marqdo>", "exec"), _g)
|
||||
_busy = False
|
||||
_send({"id": rid, "ok": True, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": _result, "error": ""})
|
||||
except BaseException:
|
||||
_busy = False
|
||||
_send({"id": rid, "ok": False, "stdout": _out_buf.getvalue(), "stderr": _err_buf.getvalue(), "result": None, "error": traceback.format_exc(limit=8)})
|
||||
finally:
|
||||
_busy = False
|
||||
sys.stdin = _old_stdin
|
||||
"#;
|
||||
|
||||
@@ -108,12 +130,14 @@ const JS_BOOTSTRAP: &str = r#"const readline = require("readline");
|
||||
const util = require("util");
|
||||
const vm = require("vm");
|
||||
const out = process.stdout.write.bind(process.stdout);
|
||||
process.on("SIGINT", () => {});
|
||||
const MAX_SAFE = Number.MAX_SAFE_INTEGER;
|
||||
globalThis.require = require;
|
||||
const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
|
||||
function sanitize(v) {
|
||||
function sanitize(v, active = new Set()) {
|
||||
if (v === null || typeof v === "boolean" || typeof v === "string") return v;
|
||||
if (typeof v === "number") {
|
||||
if (!Number.isFinite(v)) throw new Error("json: non-finite number outside V_safe");
|
||||
if (Number.isInteger(v) && Math.abs(v) > MAX_SAFE)
|
||||
throw new Error("json: integer outside V_safe (±(2^53-1)): " + v);
|
||||
return v;
|
||||
@@ -123,11 +147,36 @@ function sanitize(v) {
|
||||
throw new Error("json: integer outside V_safe (±(2^53-1)): " + v.toString());
|
||||
return Number(v);
|
||||
}
|
||||
if (Array.isArray(v)) return v.map(sanitize);
|
||||
if (v && typeof v === "object") {
|
||||
const o = {};
|
||||
for (const k of Object.keys(v)) o[k] = sanitize(v[k]);
|
||||
return o;
|
||||
if (active.has(v)) throw new Error("not JSON-safe: cyclic value");
|
||||
active.add(v);
|
||||
try {
|
||||
const keys = Reflect.ownKeys(v);
|
||||
if (Array.isArray(v)) {
|
||||
if (keys.length !== v.length + 1)
|
||||
throw new Error("not JSON-safe: sparse array or extra array properties");
|
||||
const rows = [];
|
||||
for (let i = 0; i < v.length; i++) {
|
||||
const d = Object.getOwnPropertyDescriptor(v, String(i));
|
||||
if (!d || !d.enumerable || !("value" in d))
|
||||
throw new Error("not JSON-safe: array accessor or missing element");
|
||||
rows.push(sanitize(d.value, active));
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
const prototype = Object.getPrototypeOf(v);
|
||||
if (prototype !== Object.prototype && prototype !== null)
|
||||
throw new Error("not JSON-safe: expected plain record");
|
||||
const o = Object.create(null);
|
||||
for (const k of keys) {
|
||||
if (typeof k !== "string") throw new Error("not JSON-safe: symbol record key");
|
||||
const d = Object.getOwnPropertyDescriptor(v, k);
|
||||
if (!d || !d.enumerable || !("value" in d))
|
||||
throw new Error("not JSON-safe: record accessor or hidden property");
|
||||
o[k] = sanitize(d.value, active);
|
||||
}
|
||||
return o;
|
||||
} finally { active.delete(v); }
|
||||
}
|
||||
throw new Error("not JSON-safe: " + (typeof v));
|
||||
}
|
||||
@@ -137,7 +186,7 @@ function send(o) {
|
||||
out(JSON.stringify({
|
||||
id: o && o.id !== undefined ? o.id : null, ok: false,
|
||||
stdout: (o && o.stdout) || "", stderr: (o && o.stderr) || "",
|
||||
result: null, error: String(e && e.message ? e.message : e)
|
||||
result: null, error: String(e && e.message ? e.message : e), domain_error: true
|
||||
}) + "\n");
|
||||
}
|
||||
}
|
||||
@@ -166,7 +215,7 @@ rl.on("line", async (line) => {
|
||||
let result = null;
|
||||
try { result = vm.runInThisContext(String(req.name), { filename: "<marqdo-get>" }); }
|
||||
catch (e) { result = globalThis[req.name] === undefined ? null : globalThis[req.name]; }
|
||||
send({ id: rid, ok: true, stdout: "", stderr: "", result: toJSON(result), error: "" });
|
||||
send({ id: rid, ok: true, stdout: "", stderr: "", result: result, error: "" });
|
||||
return;
|
||||
}
|
||||
if (op === "names") {
|
||||
@@ -187,15 +236,27 @@ rl.on("line", async (line) => {
|
||||
stdinPatched = true;
|
||||
} catch (e) {}
|
||||
}
|
||||
const cap = await capture(async () => vm.runInThisContext(req.code || "", { filename: "<marqdo>" }));
|
||||
send({ id: rid, phase: "ready" });
|
||||
const cap = await capture(async () => vm.runInThisContext(req.code || "", { filename: "<marqdo>", breakOnSigint: true }));
|
||||
if (stdinPatched) {
|
||||
try { Object.defineProperty(process, "stdin", { value: oldStdin, configurable: true, writable: true }); } catch (e) {}
|
||||
}
|
||||
send({ id: rid, ok: !cap.error, stdout: cap.logs, stderr: cap.errs, result: toJSON(cap.result), error: cap.error });
|
||||
send({ id: rid, ok: !cap.error, stdout: cap.logs, stderr: cap.errs, result: cap.result, error: cap.error });
|
||||
});
|
||||
"#;
|
||||
|
||||
/// Internal protocol evidence, distinct from admitted language observations.
|
||||
/// Includes failed requests and post-execution domain refusals, so set/input
|
||||
/// dependencies cannot disappear from the recorded history.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProtocolStep {
|
||||
pub session: String,
|
||||
pub request: serde_json::Value,
|
||||
pub response: Result<serde_json::Value, String>,
|
||||
}
|
||||
|
||||
pub struct Session {
|
||||
pub interrupt_handle: InterruptHandle,
|
||||
pub id: String,
|
||||
pub lang: String,
|
||||
pub cmd: String,
|
||||
@@ -224,7 +285,11 @@ impl std::fmt::Debug for Session {
|
||||
|
||||
impl Drop for Session {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
if let Some(_pid) = self.interrupt_handle.retire() {
|
||||
#[cfg(unix)]
|
||||
unsafe { libc::kill(-(_pid as i32), libc::SIGKILL); }
|
||||
let _ = self.child.kill();
|
||||
}
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
@@ -468,6 +533,7 @@ pub fn open(
|
||||
let started_ms = now_ms();
|
||||
let cmd_display = argv[0].clone();
|
||||
let session = Session {
|
||||
interrupt_handle: InterruptHandle::new(child.id()),
|
||||
id: id.clone(),
|
||||
lang: canonical.clone(),
|
||||
cmd: cmd_display.clone(),
|
||||
@@ -545,7 +611,7 @@ pub fn eval_with_stdin(
|
||||
};
|
||||
let input_json = match input {
|
||||
None | Some(Value::None) => serde_json::Value::Null,
|
||||
Some(v) => value_to_json(v)?,
|
||||
Some(v) => { super::oracle::admit(v)?; value_to_json(v)? },
|
||||
};
|
||||
let default_timeout = ctx.foreign_sessions[&id].timeout.as_secs_f64();
|
||||
let dur = parse_timeout(timeout, default_timeout)?;
|
||||
@@ -564,6 +630,9 @@ pub fn eval_with_stdin(
|
||||
let reply = match send_and_wait(ctx, &id, &request, dur) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
// Replay divergence is a language-level stop, not process death or
|
||||
// an ordinary failed-eval value. Keep the actual committed kernel.
|
||||
if ctx.foreign_replay_divergence.is_some() { return Err(e); }
|
||||
let timed_out = e.contains("timed out");
|
||||
let stderr = session_dead_stderr(ctx, &id);
|
||||
remove_session(ctx, &id);
|
||||
@@ -611,7 +680,7 @@ pub fn eval_with_stdin(
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
// Ω ∉ V_safe is a language fault, not a soft cell failure.
|
||||
if error.contains("outside V_safe") {
|
||||
if reply.get("domain_error").and_then(|v| v.as_bool()) == Some(true) {
|
||||
return Err(error);
|
||||
}
|
||||
let result = reply
|
||||
@@ -619,6 +688,7 @@ pub fn eval_with_stdin(
|
||||
.map(json_to_value)
|
||||
.transpose()?
|
||||
.unwrap_or(Value::None);
|
||||
super::oracle::admit(&result)?;
|
||||
Ok(record(
|
||||
Some(&id),
|
||||
&lang,
|
||||
@@ -647,13 +717,54 @@ fn send_and_wait(
|
||||
request: &serde_json::Value,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
if ctx.foreign_replay_expected.is_some() {
|
||||
if let Some(error) = &ctx.foreign_replay_divergence { return Err(error.clone()); }
|
||||
}
|
||||
let permit = validation::prepare(ctx.foreign_replay_expected.as_mut(), id, request)
|
||||
.map_err(|failure| {
|
||||
let error = failure.to_string();
|
||||
ctx.foreign_replay_divergence = Some(error.clone());
|
||||
error
|
||||
})?;
|
||||
let control = ctx.foreign_sessions.get(id).map(|s| s.interrupt_handle.clone());
|
||||
if let Some(handle) = &control { handle.begin(request.get("op").and_then(|v| v.as_str()) == Some("eval")); }
|
||||
let response = send_and_wait_inner(ctx, permit, timeout);
|
||||
if let Some(handle) = control { handle.finish(); }
|
||||
ctx.foreign_protocol_steps.push(ProtocolStep {
|
||||
session: id.to_string(), request: request.clone(), response: response.clone(),
|
||||
});
|
||||
if let Some(steps) = &mut ctx.foreign_replay_expected {
|
||||
if let Err(failure) = steps.accept_response(&response) {
|
||||
let error = failure.to_string();
|
||||
ctx.foreign_replay_divergence = Some(error.clone());
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn send_control(
|
||||
ctx: &mut HostContext, id: &str, request: &serde_json::Value,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let response = send_and_wait(ctx, id, request, Duration::from_secs(10));
|
||||
if response.is_err() && ctx.foreign_replay_divergence.is_none() { remove_session(ctx, id); }
|
||||
response
|
||||
}
|
||||
|
||||
fn send_and_wait_inner(
|
||||
ctx: &mut HostContext,
|
||||
permit: validation::DispatchPermit,
|
||||
timeout: Duration,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let id = permit.session();
|
||||
let request = permit.request();
|
||||
let line = serde_json::to_string(request).map_err(|e| format!("session request: {e}"))?;
|
||||
{
|
||||
let session = ctx
|
||||
.foreign_sessions
|
||||
.get_mut(id)
|
||||
.ok_or_else(|| format!("foreign session `{id}` not found"))?;
|
||||
if let Ok(Some(_)) = session.child.try_wait() {
|
||||
if let Ok(Some(_)) = session.interrupt_handle.try_wait(&mut session.child) {
|
||||
return Err("session process exited".into());
|
||||
}
|
||||
session
|
||||
@@ -687,13 +798,18 @@ fn send_and_wait(
|
||||
if rid != 1 {
|
||||
continue;
|
||||
}
|
||||
if v.get("phase").and_then(|v| v.as_str()) == Some("ready") {
|
||||
session.interrupt_handle.ready()?;
|
||||
continue;
|
||||
}
|
||||
return Ok(v);
|
||||
}
|
||||
// Unexpected non-protocol output: keep waiting until the deadline.
|
||||
continue;
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
if let Ok(Some(_)) = session.child.try_wait() {
|
||||
session.interrupt_handle.retry()?;
|
||||
if let Ok(Some(_)) = session.interrupt_handle.try_wait(&mut session.child) {
|
||||
return Err("session process exited".into());
|
||||
}
|
||||
continue;
|
||||
@@ -707,11 +823,13 @@ fn send_and_wait(
|
||||
|
||||
fn kill_session(ctx: &mut HostContext, id: &str) {
|
||||
if let Some(mut s) = ctx.foreign_sessions.remove(id) {
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
libc::kill(-(s.child.id() as i32), libc::SIGKILL);
|
||||
if let Some(_pid) = s.interrupt_handle.retire() {
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
libc::kill(-(_pid as i32), libc::SIGKILL);
|
||||
}
|
||||
let _ = s.child.kill();
|
||||
}
|
||||
let _ = s.child.kill();
|
||||
let _ = s.child.wait();
|
||||
s.alive = false;
|
||||
}
|
||||
@@ -725,17 +843,7 @@ pub fn interrupt(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
.foreign_sessions
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| format!("foreign session `{id}` not found"))?;
|
||||
#[cfg(unix)]
|
||||
unsafe {
|
||||
libc::kill(-(session.child.id() as i32), libc::SIGINT);
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &session.child.id().to_string(), "/T", "/F"])
|
||||
.output();
|
||||
session.alive = false;
|
||||
}
|
||||
session.interrupt_handle.request()?;
|
||||
Ok(Value::Bool(true))
|
||||
}
|
||||
|
||||
@@ -746,13 +854,17 @@ pub fn set(
|
||||
value: &Value,
|
||||
) -> Result<Value, String> {
|
||||
let id = as_session_id(id)?.to_string();
|
||||
if !ctx.foreign_sessions.contains_key(&id) {
|
||||
return Err(format!("foreign session `{id}` not found"));
|
||||
}
|
||||
let name = as_text(name, "name")?.to_string();
|
||||
if !valid_name(&name) {
|
||||
return Err("session_set: name must be an identifier".into());
|
||||
}
|
||||
super::oracle::admit(value)?;
|
||||
let json = value_to_json(value)?;
|
||||
let request = serde_json::json!({"id": 1, "op": "set", "name": name, "value": json});
|
||||
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
|
||||
let reply = send_control(ctx, &id, &request)?;
|
||||
if reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
Ok(Value::None)
|
||||
} else {
|
||||
@@ -766,12 +878,15 @@ pub fn set(
|
||||
|
||||
pub fn get(ctx: &mut HostContext, id: &Value, name: &Value) -> Result<Value, String> {
|
||||
let id = as_session_id(id)?.to_string();
|
||||
if !ctx.foreign_sessions.contains_key(&id) {
|
||||
return Err(format!("foreign session `{id}` not found"));
|
||||
}
|
||||
let name = as_text(name, "name")?.to_string();
|
||||
if !valid_name(&name) {
|
||||
return Err("session_get: name must be an identifier".into());
|
||||
}
|
||||
let request = serde_json::json!({"id": 1, "op": "get", "name": name});
|
||||
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
|
||||
let reply = send_control(ctx, &id, &request)?;
|
||||
if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
return Err(reply
|
||||
.get("error")
|
||||
@@ -779,16 +894,21 @@ pub fn get(ctx: &mut HostContext, id: &Value, name: &Value) -> Result<Value, Str
|
||||
.unwrap_or("session_get failed")
|
||||
.to_string());
|
||||
}
|
||||
match reply.get("result") {
|
||||
let value = match reply.get("result") {
|
||||
Some(v) => json_to_value(v),
|
||||
None => Ok(Value::None),
|
||||
}
|
||||
}?;
|
||||
super::oracle::admit(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub fn names(ctx: &mut HostContext, id: &Value) -> Result<Value, String> {
|
||||
let id = as_session_id(id)?.to_string();
|
||||
if !ctx.foreign_sessions.contains_key(&id) {
|
||||
return Err(format!("foreign session `{id}` not found"));
|
||||
}
|
||||
let request = serde_json::json!({"id": 1, "op": "names"});
|
||||
let reply = send_and_wait(ctx, &id, &request, Duration::from_secs(10))?;
|
||||
let reply = send_control(ctx, &id, &request)?;
|
||||
if !reply.get("ok").and_then(|v| v.as_bool()).unwrap_or(false) {
|
||||
return Err(reply
|
||||
.get("error")
|
||||
@@ -837,7 +957,7 @@ pub fn shutdown(ctx: &mut HostContext) {
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_name(name: &str) -> bool {
|
||||
pub(crate) fn valid_name(name: &str) -> bool {
|
||||
let mut chars = name.chars();
|
||||
match chars.next() {
|
||||
Some(c) if c == '_' || c.is_ascii_alphabetic() => {}
|
||||
@@ -857,4 +977,301 @@ mod tests {
|
||||
assert!(!valid_name("1x"));
|
||||
assert!(!valid_name("a-b"));
|
||||
}
|
||||
#[test]
|
||||
fn bridge_live_boundary_and_refusal_preserves_input_store() {
|
||||
let edge = 9_007_199_254_740_991i64;
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
let name = Value::Text("payload".into());
|
||||
for n in [i64::MIN, -edge-1, -edge, -edge+1, -1, 0, 1, edge-1, edge, edge+1, i64::MAX] {
|
||||
set(&mut ctx, &id, &name, &Value::Int(17)).unwrap();
|
||||
let input = Value::List(vec![Value::Text("中文🧪".into()), Value::List(vec![Value::Int(n)])]);
|
||||
let result = set(&mut ctx, &id, &name, &input);
|
||||
if (-edge..=edge).contains(&n) {
|
||||
result.unwrap();
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), input, "{lang} {n}");
|
||||
} else {
|
||||
assert!(result.unwrap_err().contains("outside V_safe"));
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(17));
|
||||
}
|
||||
println!("E4 {lang} integer {n}: verified");
|
||||
}
|
||||
for source in if lang == "python" {
|
||||
["2**53", "float('nan')", "float('inf')"]
|
||||
} else { ["2**53", "NaN", "Infinity"] } {
|
||||
let error = eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, None).unwrap_err();
|
||||
assert!(error.contains("outside V_safe"), "{lang} {source}: {error}");
|
||||
// A refused response must remain a protocol response, not kill Node.
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(17));
|
||||
println!("E4 {lang} response {source}: refused, session responsive");
|
||||
}
|
||||
let alias = id.clone();
|
||||
close(&mut ctx, &id).unwrap();
|
||||
// Missing handle wins over an invalid name and an OOD payload.
|
||||
let err = set(&mut ctx, &alias, &Value::Text("bad-name".into()), &Value::Int(i64::MAX)).unwrap_err();
|
||||
assert!(err.contains("not found"), "{err}");
|
||||
assert!(get(&mut ctx, &alias, &name).is_err());
|
||||
assert!(close(&mut ctx, &alias).is_err());
|
||||
assert!(ctx.foreign_sessions.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_two_session_model_traces() {
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
let mut ids = Vec::new();
|
||||
let mut live = [true; 2];
|
||||
let mut expected = [0i64; 2];
|
||||
let name = Value::Text("counter".into());
|
||||
for _ in 0..2 {
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
set(&mut ctx, &id, &name, &Value::Int(0)).unwrap();
|
||||
ids.push(id);
|
||||
}
|
||||
let mut seed = 0x52455155495245u64;
|
||||
for step in 0..256 {
|
||||
seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
|
||||
let slot = ((seed >> 32) & 1) as usize;
|
||||
let op = (seed >> 40) % 5;
|
||||
match op {
|
||||
0 => {
|
||||
let value = step as i64 - 128;
|
||||
let result = set(&mut ctx, &ids[slot], &name, &Value::Int(value));
|
||||
assert_eq!(result.is_ok(), live[slot]);
|
||||
if live[slot] { expected[slot] = value; }
|
||||
}
|
||||
1 => {
|
||||
let result = get(&mut ctx, &ids[slot], &name);
|
||||
if live[slot] { assert_eq!(result.unwrap(), Value::Int(expected[slot])); }
|
||||
else { assert!(result.unwrap_err().contains("not found")); }
|
||||
}
|
||||
2 => {
|
||||
let src = if lang == "python" { "counter += 1\ncounter" } else { "counter += 1; counter" };
|
||||
let result = eval(&mut ctx, &ids[slot], None, Some(&Value::Text(src.into())), None, None);
|
||||
assert_eq!(result.is_ok(), live[slot]);
|
||||
if live[slot] { expected[slot] += 1; }
|
||||
}
|
||||
3 => {
|
||||
assert_eq!(close(&mut ctx, &ids[slot]).is_ok(), live[slot]);
|
||||
live[slot] = false;
|
||||
}
|
||||
_ => {
|
||||
if live[slot] { close(&mut ctx, &ids[slot]).unwrap(); }
|
||||
let stale = ids[slot].clone();
|
||||
ids[slot] = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
assert_ne!(stale, ids[slot]);
|
||||
assert!(get(&mut ctx, &stale, &name).is_err());
|
||||
set(&mut ctx, &ids[slot], &name, &Value::Int(0)).unwrap();
|
||||
expected[slot] = 0;
|
||||
live[slot] = true;
|
||||
}
|
||||
}
|
||||
// Independent model predicts every remaining store after every command.
|
||||
for j in 0..2 {
|
||||
assert_eq!(ctx.foreign_sessions.contains_key(as_session_id(&ids[j]).unwrap()), live[j]);
|
||||
if live[j] { assert_eq!(get(&mut ctx, &ids[j], &name).unwrap(), Value::Int(expected[j]), "{lang} step {step} slot {j}"); }
|
||||
}
|
||||
}
|
||||
shutdown(&mut ctx);
|
||||
assert!(ctx.foreign_sessions.is_empty());
|
||||
println!("E3 {lang}: seed 0x52455155495245, 256 commands verified");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_process_exit_timeout_and_reopen() {
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
for source in if lang == "python" { ["import os; os._exit(7)", "while True: pass"] }
|
||||
else { ["process.exit(7)", "while(true) {}"] } {
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
let result = eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, Some(&Value::Num(0.1)));
|
||||
assert!(result.is_ok(), "process failure should be a failure record: {result:?}");
|
||||
let Value::Map(m) = result.unwrap() else { panic!() };
|
||||
assert!(m.iter().any(|(k,v)| k == "ok" && v == &Value::Bool(false)));
|
||||
assert!(ctx.foreign_sessions.is_empty(), "dead session must be retired");
|
||||
assert!(get(&mut ctx, &id, &Value::Text("x".into())).is_err());
|
||||
println!("E5 {lang} {source}: recorded and retired");
|
||||
}
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
set(&mut ctx, &id, &Value::Text("x".into()), &Value::Int(41)).unwrap();
|
||||
assert_eq!(get(&mut ctx, &id, &Value::Text("x".into())).unwrap(), Value::Int(41));
|
||||
shutdown(&mut ctx);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_history_and_post_refusal_effects_are_preserved() {
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
let name = Value::Text("n".into());
|
||||
set(&mut ctx, &id, &name, &Value::Int(1)).unwrap();
|
||||
let code = if lang == "python" { "n += marqdo_input\nn" } else { "n += marqdo_input; n" };
|
||||
let result = eval(&mut ctx, &id, None, Some(&Value::Text(code.into())), Some(&Value::Int(3)), None).unwrap();
|
||||
let Value::Map(fields) = result else { panic!() };
|
||||
assert_eq!(fields.iter().find(|(k,_)| k == "result").unwrap().1, Value::Int(4));
|
||||
let sent = ctx.foreign_protocol_steps.last().unwrap();
|
||||
assert_eq!(sent.session, as_session_id(&id).unwrap());
|
||||
assert_eq!(sent.request["op"], "eval");
|
||||
assert_eq!(sent.request["input"], 3);
|
||||
assert_eq!(sent.request["code"], code);
|
||||
let before = ctx.foreign_protocol_steps.len();
|
||||
assert!(set(&mut ctx, &id, &name, &Value::Int(i64::MAX)).is_err());
|
||||
assert_eq!(ctx.foreign_protocol_steps.len(), before, "invalid input must not query oracle");
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(4));
|
||||
let bad = if lang == "python" { "n = 99\n2**53" } else { "n = 99; 2**53" };
|
||||
assert!(eval(&mut ctx, &id, None, Some(&Value::Text(bad.into())), None, None).unwrap_err().contains("outside V_safe"));
|
||||
let fault = ctx.foreign_protocol_steps.last().unwrap();
|
||||
assert_eq!(fault.response.as_ref().unwrap()["domain_error"], true);
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(99), "foreign effects must not be claimed to roll back");
|
||||
let ordinary_error = if lang == "python" { "raise ValueError('outside V_safe')" }
|
||||
else { "throw new Error('outside V_safe')" };
|
||||
let record = eval(&mut ctx, &id, None, Some(&Value::Text(ordinary_error.into())), None, None).unwrap();
|
||||
let Value::Map(fields) = record else { panic!() };
|
||||
assert_eq!(fields.iter().find(|(k,_)| k == "ok").unwrap().1, Value::Bool(false));
|
||||
let unsupported = if lang == "python" { "object()" } else { "(function(){})" };
|
||||
assert!(eval(&mut ctx, &id, None, Some(&Value::Text(unsupported.into())), None, None).unwrap_err().contains("not JSON-safe"));
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), Value::Int(99));
|
||||
close(&mut ctx, &id).unwrap();
|
||||
println!("E6 {lang}: complete inputs recorded; pre-send refusal has no request; post-send refusal retains effects; structured domain classification verified");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_extension_policy_agrees_on_python_and_node() {
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
let key = Value::Text("number".into());
|
||||
for value in [1.5, -0.0, 9_007_199_254_740_991.0, -9_007_199_254_740_991.0] {
|
||||
set(&mut ctx, &id, &key, &Value::Num(value)).unwrap();
|
||||
match get(&mut ctx, &id, &key).unwrap() {
|
||||
Value::Num(n) => assert_eq!(n, value),
|
||||
Value::Int(n) => assert_eq!(n as f64, value),
|
||||
other => panic!("{lang}: {other:?}"),
|
||||
}
|
||||
}
|
||||
for value in [9_007_199_254_740_992.0, -9_007_199_254_740_992.0, 1e100] {
|
||||
let before = ctx.foreign_protocol_steps.len();
|
||||
assert!(set(&mut ctx, &id, &key, &Value::Num(value)).unwrap_err().contains("outside V_safe"));
|
||||
assert_eq!(ctx.foreign_protocol_steps.len(), before);
|
||||
}
|
||||
let source = if lang == "python" { "float(2**53)" } else { "Number(2**53)" };
|
||||
assert!(eval(&mut ctx, &id, None, Some(&Value::Text(source.into())), None, None).unwrap_err().contains("outside V_safe"));
|
||||
close(&mut ctx, &id).unwrap();
|
||||
println!("E7 {lang}: finite fractions admitted, integral float/scientific-notation bypass refused");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_non_json_containers_and_lossy_properties_are_refused_without_coercion() {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = open(&mut ctx, &Value::Text("node".into()), None, None, None, None).unwrap();
|
||||
let expressions = [
|
||||
"new Map([['k',1]])", "new Set([1,2])", "new Date(0)", "/x/",
|
||||
"new Uint8Array([1,2])", "new Number(7)",
|
||||
"Object.assign(Object.create({inherited:1}),{own:2})",
|
||||
"Object.defineProperty({},'hidden',{value:7})", "({[Symbol('k')]:7})",
|
||||
"Object.defineProperty({},'data',{enumerable:true,get(){retained=123;return 7}})",
|
||||
"new Array(2)", "Object.assign([1,2],{tag:3})", "[undefined]",
|
||||
"(()=>{var x={};x.self=x;return x;})()",
|
||||
];
|
||||
for expression in expressions {
|
||||
let code = Value::Text(format!("retained = 99; {expression}"));
|
||||
let result = eval(&mut ctx,&id,None,Some(&code),None,None);
|
||||
assert!(result.as_ref().is_err_and(|e|e.contains("not JSON-safe")),"silently coerced {expression}: {result:?}");
|
||||
let reply=ctx.foreign_protocol_steps.last().unwrap().response.as_ref().unwrap().clone();
|
||||
assert_eq!(reply["domain_error"],serde_json::json!(true));
|
||||
assert_eq!(get(&mut ctx,&id,&Value::Text("retained".into())).unwrap(),Value::Int(99),"getter must not run during refusal");
|
||||
println!("NODE_DOMAIN_REFUSAL:{}",serde_json::json!({"expression":expression,"reply":reply.clone(),"retained":99}));
|
||||
}
|
||||
// Null prototypes, special string keys and shared acyclic subvalues remain records/lists.
|
||||
let code=Value::Text("var item = Object.assign(Object.create(null),{constructor:7}); [item,item]".into());
|
||||
let result=eval(&mut ctx,&id,None,Some(&code),None,None).unwrap();
|
||||
let Value::Map(fields)=result else {panic!()};
|
||||
let observed=&fields.iter().find(|(k,_)|k=="result").unwrap().1;
|
||||
assert_eq!(observed,&Value::List(vec![Value::Map(vec![("constructor".into(),Value::Int(7))]);2]));
|
||||
close(&mut ctx,&id).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recursive_values_and_object_keys_cross_without_coercion() {
|
||||
fn payload(seed: u64, depth: usize) -> Value {
|
||||
if depth == 0 { return match seed % 4 {
|
||||
0 => Value::None, 1 => Value::Bool(seed & 4 != 0),
|
||||
2 => Value::Int((seed % 2001) as i64 - 1000),
|
||||
_ => Value::Text(format!("中文🧪\\\"\n{}", seed % 10)),
|
||||
}; }
|
||||
match seed % 3 {
|
||||
0 => Value::List(vec![payload(seed.wrapping_mul(17).wrapping_add(1), depth-1), payload(seed.wrapping_mul(31).wrapping_add(2), depth-1)]),
|
||||
1 => Value::Map(vec![("data".into(), payload(seed.wrapping_mul(43).wrapping_add(3), depth-1)), ("tag".into(), Value::Text("record".into()))]),
|
||||
_ => payload(seed, 0),
|
||||
}
|
||||
}
|
||||
for lang in ["python", "node"] {
|
||||
let mut ctx = HostContext::default();
|
||||
let id = open(&mut ctx, &Value::Text(lang.into()), None, None, None, None).unwrap();
|
||||
let name = Value::Text("payload".into());
|
||||
for seed in 0..64 {
|
||||
let v = payload(seed, 4);
|
||||
set(&mut ctx, &id, &name, &v).unwrap();
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), v, "{lang} seed {seed}");
|
||||
}
|
||||
let special = Value::Map(vec![
|
||||
("__proto__".into(), Value::Map(vec![("polluted".into(), Value::Bool(true))])),
|
||||
("constructor".into(), Value::Text("data".into())),
|
||||
]);
|
||||
set(&mut ctx, &id, &name, &special).unwrap();
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), special, "{lang} valid special keys lost");
|
||||
for bad in [Value::Map(vec![("a".into(), Value::Int(1)), ("a".into(), Value::Int(2))]),
|
||||
Value::Map(vec![("a".into(), Value::List(vec![])), ("b".into(), Value::List(vec![Value::Int(1)]))])] {
|
||||
let before = ctx.foreign_protocol_steps.len();
|
||||
assert!(set(&mut ctx, &id, &name, &bad).is_err());
|
||||
assert_eq!(ctx.foreign_protocol_steps.len(), before);
|
||||
assert_eq!(get(&mut ctx, &id, &name).unwrap(), special);
|
||||
}
|
||||
if lang == "python" {
|
||||
let code = Value::Text("{1: 'integer key', '1': 'string key'}".into());
|
||||
assert!(eval(&mut ctx, &id, None, Some(&code), None, None).unwrap_err().contains("keys must be strings"));
|
||||
} else {
|
||||
let code = Value::Text("typeof ({}).polluted === 'undefined'".into());
|
||||
let Value::Map(m) = eval(&mut ctx, &id, None, Some(&code), None, None).unwrap() else { panic!() };
|
||||
assert_eq!(m.iter().find(|(k,_)| k == "result").unwrap().1, Value::Bool(true));
|
||||
}
|
||||
close(&mut ctx, &id).unwrap();
|
||||
println!("E8 {lang}: 64 nested round-trips, special keys preserved, invalid key/shape inputs refused without requests");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn bootstrap_interrupts_busy_eval_and_preserves_idle_state(){
|
||||
for lang in ["python","node"]{
|
||||
let mut ctx=HostContext::default();let id=open(&mut ctx,&Value::Text(lang.into()),None,None,None,None).unwrap();
|
||||
let name=Value::Text("n".into());set(&mut ctx,&id,&name,&Value::Int(8)).unwrap();
|
||||
interrupt(&mut ctx,&id).unwrap();assert_eq!(get(&mut ctx,&id,&name).unwrap(),Value::Int(8));
|
||||
let marker=ctx.cwd.join(format!("target/interrupt-marker-{}-{lang}",std::process::id()));let _=std::fs::remove_file(&marker);
|
||||
let literal=serde_json::to_string(&marker.display().to_string()).unwrap();
|
||||
let code=if lang=="python"{format!("with open({literal}, 'w') as marker:\n marker.write('ready')\nwhile True: pass")}
|
||||
else{format!("require('fs').writeFileSync({literal}, 'ready'); while(true) {{}}")};
|
||||
let pid=ctx.foreign_sessions[as_session_id(&id).unwrap()].child.id();let child_id=id.clone();
|
||||
let worker=std::thread::spawn(move||{let out=eval(&mut ctx,&child_id,None,Some(&Value::Text(code)),None,Some(&Value::Num(3.0)));(ctx,out)});
|
||||
let deadline=Instant::now()+Duration::from_secs(2);
|
||||
while !marker.exists()&&Instant::now()<deadline{std::thread::sleep(Duration::from_millis(1));}
|
||||
let ready=marker.exists();
|
||||
if ready{assert_eq!(unsafe{libc::kill(-(pid as i32),libc::SIGINT)},0);}
|
||||
let (mut ctx,out)=worker.join().unwrap();assert!(ready,"{lang}: code did not start");
|
||||
let Value::Map(record)=out.unwrap() else{panic!()};
|
||||
assert_eq!(record.iter().find(|(k,_)|k=="ok").unwrap().1,Value::Bool(false));
|
||||
assert_eq!(record.iter().find(|(k,_)|k=="alive").unwrap().1,Value::Bool(true));
|
||||
let error=record.iter().find(|(k,_)|k=="error").unwrap().1.as_display();
|
||||
assert!(error.contains("KeyboardInterrupt")||error.contains("interrupted"),"{lang}: {error}");
|
||||
assert_eq!(get(&mut ctx,&id,&name).unwrap(),Value::Int(8));close(&mut ctx,&id).unwrap();std::fs::remove_file(marker).unwrap();
|
||||
println!("E10 {lang}: idle interrupt is safe; busy synchronous eval interrupted with kernel and store alive");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
//! An owned-process interrupt capability. Retirement precedes every child reap,
|
||||
//! so a stale capability cannot signal a reused operating-system process id.
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct State {
|
||||
pid: Option<u32>,
|
||||
evaluating: bool,
|
||||
ready: bool,
|
||||
requested: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InterruptHandle(Arc<Mutex<State>>);
|
||||
|
||||
impl InterruptHandle {
|
||||
pub(super) fn new(pid: u32) -> Self {
|
||||
Self(Arc::new(Mutex::new(State {
|
||||
pid: Some(pid),
|
||||
..State::default()
|
||||
})))
|
||||
}
|
||||
pub(super) fn retire(&self) -> Option<u32> {
|
||||
if let Ok(mut state) = self.0.lock() {
|
||||
let pid = state.pid.take();
|
||||
state.evaluating = false;
|
||||
pid
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
pub(super) fn try_wait(
|
||||
&self,
|
||||
child: &mut std::process::Child,
|
||||
) -> std::io::Result<Option<std::process::ExitStatus>> {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
let result = child.try_wait();
|
||||
if matches!(result, Ok(Some(_))) {
|
||||
state.pid = None;
|
||||
state.evaluating = false;
|
||||
}
|
||||
result
|
||||
}
|
||||
pub(super) fn begin(&self, evaluating: bool) {
|
||||
let mut state = self.0.lock().unwrap();
|
||||
state.evaluating = evaluating;
|
||||
state.ready = false;
|
||||
state.requested = false;
|
||||
}
|
||||
pub(super) fn finish(&self) {
|
||||
self.0.lock().unwrap().evaluating = false;
|
||||
}
|
||||
// SIGINT can arrive between a Node ready frame and installation of V8's
|
||||
// breakOnSigint handler. Retry the same logical request while awaiting its
|
||||
// response; never carry a retry into the next request or retired process.
|
||||
pub(super) fn retry(&self) -> Result<(), String> {
|
||||
let state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.evaluating && state.ready && state.requested {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn ready(&self) -> Result<(), String> {
|
||||
let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.ready {
|
||||
return Ok(());
|
||||
}
|
||||
state.ready = true;
|
||||
if state.requested {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn is_live(&self) -> bool {
|
||||
self.0.lock().is_ok_and(|s| s.pid.is_some())
|
||||
}
|
||||
|
||||
/// False means idle; cancellation is coalesced within one evaluation.
|
||||
/// Before the bootstrap's ready frame it is queued rather than sent into
|
||||
/// interpreter startup or transport parsing.
|
||||
pub fn request(&self) -> Result<bool, String> {
|
||||
let mut state = self.0.lock().map_err(|_| "interrupt lock poisoned")?;
|
||||
if state.pid.is_none() {
|
||||
return Err("interrupt capability retired".into());
|
||||
}
|
||||
if !state.evaluating {
|
||||
return Ok(false);
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
return Err("non-destructive interrupt is unsupported on this platform".into());
|
||||
if !state.requested {
|
||||
if state.ready {
|
||||
Self::signal(&state)?;
|
||||
}
|
||||
state.requested = true;
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
fn signal(state: &State) -> Result<(), String> {
|
||||
let pid = state.pid.ok_or("interrupt capability retired")?;
|
||||
#[cfg(unix)]
|
||||
{
|
||||
if unsafe { libc::kill(-(pid as i32), libc::SIGINT) } != 0 {
|
||||
return Err(format!(
|
||||
"interrupt failed: {}",
|
||||
std::io::Error::last_os_error()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
let _ = pid;
|
||||
Err("non-destructive interrupt is unsupported on this platform".into())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use crate::host::{foreign_session, HostContext};
|
||||
use crate::value::Value;
|
||||
#[test]
|
||||
fn retired_interrupt_capability_cannot_reach_replacement_kernel() {
|
||||
for language in ["python", "node"] {
|
||||
let mut host = HostContext::default();
|
||||
let lang = Value::Text(language.into());
|
||||
let old = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap();
|
||||
let Value::Handle(id) = &old else { panic!() };
|
||||
let control = host.foreign_sessions[id].interrupt_handle.clone();
|
||||
assert!(!control.request().unwrap());
|
||||
foreign_session::close(&mut host, &old).unwrap();
|
||||
let new = foreign_session::open(&mut host, &lang, None, None, None, None).unwrap();
|
||||
assert!(!control.is_live());
|
||||
assert!(control.request().unwrap_err().contains("retired"));
|
||||
foreign_session::set(&mut host, &new, &Value::Text("n".into()), &Value::Int(8))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
foreign_session::get(&mut host, &new, &Value::Text("n".into())).unwrap(),
|
||||
Value::Int(8)
|
||||
);
|
||||
foreign_session::close(&mut host, &new).unwrap();
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn cancellation_queued_during_bootstrap_reaches_busy_evaluation() {
|
||||
use std::time::{Duration, Instant};
|
||||
for language in ["python", "node"] {
|
||||
let mut host = HostContext::default();
|
||||
let id = foreign_session::open(
|
||||
&mut host,
|
||||
&Value::Text(language.into()),
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
let Value::Handle(ref name) = id else {
|
||||
panic!()
|
||||
};
|
||||
let control = host.foreign_sessions[name].interrupt_handle.clone();
|
||||
let kernel = id.clone();
|
||||
let code = if language == "python" {
|
||||
"while True: pass"
|
||||
} else {
|
||||
"while(true) {}"
|
||||
};
|
||||
let worker = std::thread::spawn(move || {
|
||||
let record = foreign_session::eval(
|
||||
&mut host,
|
||||
&kernel,
|
||||
None,
|
||||
Some(&Value::Text(code.into())),
|
||||
None,
|
||||
Some(&Value::Int(2)),
|
||||
)
|
||||
.unwrap();
|
||||
(host, record)
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
while !control.0.lock().unwrap().evaluating && Instant::now() < deadline {
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert!(control.request().unwrap());
|
||||
assert!(
|
||||
control.request().unwrap(),
|
||||
"logical duplicates must coalesce"
|
||||
);
|
||||
let (mut host, record) = worker.join().unwrap();
|
||||
let Value::Map(fields) = record else { panic!() };
|
||||
assert_eq!(
|
||||
fields.iter().find(|(k, _)| k == "timed_out").unwrap().1,
|
||||
Value::Bool(false),
|
||||
"{language}: {fields:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
fields.iter().find(|(k, _)| k == "alive").unwrap().1,
|
||||
Value::Bool(true)
|
||||
);
|
||||
foreign_session::close(&mut host, &id).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
//! Production adapter to the executable Lean replay policy.
|
||||
//! All replay decisions come from ReplayPolicy.Cursor, with no Rust fallback.
|
||||
use super::ProtocolStep;
|
||||
use serde_json::{json, Value};
|
||||
use std::collections::VecDeque;
|
||||
mod policy;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DivergenceKind { Missing, Request, Reply, Surplus, Phase, Policy }
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Divergence {
|
||||
pub kind: DivergenceKind,
|
||||
pub matched_prefix: usize,
|
||||
pub detail: Option<String>,
|
||||
}
|
||||
impl std::fmt::Display for Divergence {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self.kind {
|
||||
DivergenceKind::Missing | DivergenceKind::Request => "replay: protocol request differs before dispatch",
|
||||
DivergenceKind::Reply => "replay: protocol response differs",
|
||||
DivergenceKind::Surplus => "replay: recorded execution prefix was not consumed",
|
||||
DivergenceKind::Phase => "replay: invalid protocol validation phase",
|
||||
DivergenceKind::Policy => "replay: verified policy unavailable",
|
||||
})?;
|
||||
if let Some(detail) = &self.detail { write!(f, ": {detail}")? }
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ReplayCursor {
|
||||
client: Option<policy::Client>,
|
||||
progress: (usize, usize),
|
||||
stopped: Option<Divergence>,
|
||||
}
|
||||
impl From<VecDeque<ProtocolStep>> for ReplayCursor {
|
||||
fn from(expected: VecDeque<ProtocolStep>) -> Self {
|
||||
let count = expected.len();
|
||||
match policy::Client::start(expected) {
|
||||
Ok((client, reply)) if reply.allow && reply.matched == 0 && reply.remaining == count =>
|
||||
Self { client: Some(client), progress: (0, count), stopped: None },
|
||||
result => {
|
||||
let detail = match result { Err(e) => e, Ok(_) => "invalid policy initialization".into() };
|
||||
Self { client: None, progress: (0,count), stopped: Some(Divergence {
|
||||
kind: DivergenceKind::Policy, matched_prefix: 0, detail: Some(detail) }) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl From<Vec<ProtocolStep>> for ReplayCursor {
|
||||
fn from(expected: Vec<ProtocolStep>) -> Self { VecDeque::from(expected).into() }
|
||||
}
|
||||
/// Private construction, no Clone: actual dispatch consumes this snapshot.
|
||||
pub(super) struct DispatchPermit { session: String, request: Value }
|
||||
impl DispatchPermit {
|
||||
pub(super) fn session(&self) -> &str { &self.session }
|
||||
pub(super) fn request(&self) -> &Value { &self.request }
|
||||
}
|
||||
impl ReplayCursor {
|
||||
fn unavailable(&mut self, detail: String) -> Divergence {
|
||||
self.client.take();
|
||||
let error = Divergence { kind: DivergenceKind::Policy, matched_prefix: self.progress.0, detail: Some(detail) };
|
||||
self.stopped = Some(error.clone());
|
||||
error
|
||||
}
|
||||
fn command(&mut self, command: Value) -> Result<(), Divergence> {
|
||||
if let Some(error) = &self.stopped { return Err(error.clone()) }
|
||||
let result = self.client.as_mut().ok_or_else(|| "no policy process".to_string())
|
||||
.and_then(|client| client.exchange(command));
|
||||
let reply = result.map_err(|e| self.unavailable(e))?;
|
||||
self.progress = (reply.matched, reply.remaining);
|
||||
if reply.allow { return Ok(()) }
|
||||
let kind = match reply.reason.as_deref() {
|
||||
Some("missing") => DivergenceKind::Missing,
|
||||
Some("request") => DivergenceKind::Request,
|
||||
Some("reply") => DivergenceKind::Reply,
|
||||
Some("surplus") => DivergenceKind::Surplus,
|
||||
Some("phase") => DivergenceKind::Phase,
|
||||
_ => return Err(self.unavailable("unknown policy stop reason".into())),
|
||||
};
|
||||
let error = Divergence { kind, matched_prefix: reply.matched, detail: None };
|
||||
self.stopped = Some(error.clone());
|
||||
Err(error)
|
||||
}
|
||||
fn prepare(&mut self, session: &str, request: &Value) -> Result<DispatchPermit, Divergence> {
|
||||
self.command(json!({"op":"prepare", "value":policy::request_key(session,request)}))?;
|
||||
Ok(DispatchPermit { session: session.into(), request: request.clone() })
|
||||
}
|
||||
pub(super) fn accept_response(&mut self, response: &Result<Value,String>) -> Result<(), Divergence> {
|
||||
self.command(json!({"op":"receive", "value":policy::response_key(response)}))
|
||||
}
|
||||
pub fn progress(&self) -> (usize,usize) { self.progress }
|
||||
/// Called only at the outer action boundary; consumes the cursor.
|
||||
pub fn finish(mut self) -> Result<(),Divergence> { self.command(json!({"op":"finish"})) }
|
||||
}
|
||||
pub(super) fn prepare(cursor: Option<&mut ReplayCursor>, session: &str, request: &Value)
|
||||
-> Result<DispatchPermit,Divergence> {
|
||||
if let Some(cursor) = cursor { return cursor.prepare(session,request) }
|
||||
Ok(DispatchPermit { session: session.into(), request: request.clone() })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
fn step(reply: Result<Value, String>) -> ProtocolStep {
|
||||
ProtocolStep {
|
||||
session: "s".into(),
|
||||
request: json!({"op":"get"}),
|
||||
response: reply,
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn local_returns_and_ordinary_failures_preserve_residual_history() {
|
||||
let mut cursor: ReplayCursor =
|
||||
vec![step(Err("foreign failure".into())), step(Ok(json!(7)))].into();
|
||||
assert_eq!(cursor.progress(), (0, 2));
|
||||
let permit = cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
assert_eq!(permit.session(), "s");
|
||||
cursor
|
||||
.accept_response(&Err("foreign failure".into()))
|
||||
.unwrap();
|
||||
assert_eq!(cursor.progress(), (1, 1));
|
||||
cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
cursor.accept_response(&Ok(json!(7))).unwrap();
|
||||
cursor.finish().unwrap();
|
||||
}
|
||||
#[test]
|
||||
fn divergence_is_sticky_and_matching_reply_cannot_revive_it() {
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
cursor.prepare("s", &json!({"op":"get"})).unwrap();
|
||||
let first = cursor.accept_response(&Ok(json!(8))).unwrap_err();
|
||||
assert_eq!(first.kind, DivergenceKind::Reply);
|
||||
assert_eq!(
|
||||
cursor.prepare("s", &json!({"op":"get"})).err().unwrap(),
|
||||
first
|
||||
);
|
||||
assert_eq!(cursor.accept_response(&Ok(json!(7))).unwrap_err(), first);
|
||||
assert_eq!(cursor.finish().unwrap_err(), first);
|
||||
}
|
||||
#[test]
|
||||
fn permit_is_a_snapshot_and_phase_errors_fail_closed() {
|
||||
let mut request = json!({"op":"get"});
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
let permit = cursor.prepare("s", &request).unwrap();
|
||||
request["op"] = json!("write");
|
||||
assert_ne!(permit.request(), &request);
|
||||
assert_eq!(
|
||||
cursor.prepare("s", permit.request()).err().unwrap().kind,
|
||||
DivergenceKind::Phase
|
||||
);
|
||||
assert!(cursor.accept_response(&Ok(json!(7))).is_err());
|
||||
}
|
||||
#[test]
|
||||
fn mismatching_and_missing_requests_never_issue_a_permit() {
|
||||
let mut cursor: ReplayCursor = vec![step(Ok(json!(7)))].into();
|
||||
let error = cursor
|
||||
.prepare("other-session", &json!({"op":"get"}))
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(error.kind, DivergenceKind::Request);
|
||||
assert_eq!(cursor.progress(), (0, 1));
|
||||
assert_eq!(
|
||||
cursor.prepare("s", &json!({"op":"get"})).err().unwrap(),
|
||||
error
|
||||
);
|
||||
let mut empty: ReplayCursor = Vec::<ProtocolStep>::new().into();
|
||||
assert_eq!(
|
||||
empty.prepare("s", &json!({"op":"get"})).err().unwrap().kind,
|
||||
DivergenceKind::Missing
|
||||
);
|
||||
assert!(empty.finish().is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Transport for the executable Lean policy. This module makes no replay
|
||||
//! acceptance decisions; malformed/unavailable policy responses fail closed.
|
||||
use super::super::ProtocolStep;
|
||||
use serde::Deserialize;
|
||||
use serde_json::{json, Value};
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::mpsc::{self, Receiver};
|
||||
use std::time::Duration;
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Reply {
|
||||
pub policy: String,
|
||||
pub allow: bool,
|
||||
pub matched: usize,
|
||||
pub remaining: usize,
|
||||
pub reason: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Client {
|
||||
child: Child,
|
||||
input: ChildStdin,
|
||||
replies: Receiver<Result<Reply,String>>,
|
||||
}
|
||||
|
||||
pub(super) fn request_key(session: &str, request: &Value) -> String {
|
||||
serde_json::to_string(&(session,request.to_string())).expect("strings serialize")
|
||||
}
|
||||
pub(super) fn response_key(response: &Result<Value,String>) -> String {
|
||||
serde_json::to_string(response).expect("protocol responses serialize")
|
||||
}
|
||||
|
||||
fn executable() -> PathBuf {
|
||||
if let Some(path) = std::env::var_os("MARQDO_REPLAY_POLICY") { return path.into() }
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
if let Some(parent) = exe.parent() {
|
||||
let adjacent = parent.join("marqdo-replay-policy");
|
||||
if adjacent.is_file() { return adjacent }
|
||||
}
|
||||
}
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("verification/replay-policy/.lake/build/bin/replayPolicy")
|
||||
}
|
||||
|
||||
impl Client {
|
||||
pub(super) fn start(steps: impl IntoIterator<Item=ProtocolStep>) -> Result<(Self,Reply),String> {
|
||||
let path=executable();
|
||||
let mut child=Command::new(&path).stdin(Stdio::piped()).stdout(Stdio::piped())
|
||||
.stderr(Stdio::null()).spawn().map_err(|e|format!("{}: {e}",path.display()))?;
|
||||
let input=child.stdin.take().ok_or("policy stdin unavailable")?;
|
||||
let output=child.stdout.take().ok_or("policy stdout unavailable")?;
|
||||
let (sender,replies)=mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(output).lines() {
|
||||
let reply=line.map_err(|e|e.to_string())
|
||||
.and_then(|line|serde_json::from_str(&line).map_err(|e|e.to_string()));
|
||||
let failed=reply.is_err();
|
||||
if sender.send(reply).is_err() || failed { break }
|
||||
}
|
||||
});
|
||||
let steps: Vec<_>=steps.into_iter().map(|step|json!({
|
||||
"q":request_key(&step.session,&step.request),"r":response_key(&step.response)
|
||||
})).collect();
|
||||
let mut client=Self {child,input,replies};
|
||||
let reply=client.exchange(json!({"op":"init","steps":steps}))?;
|
||||
Ok((client,reply))
|
||||
}
|
||||
|
||||
pub(super) fn exchange(&mut self, command: Value) -> Result<Reply,String> {
|
||||
serde_json::to_writer(&mut self.input,&command).map_err(|e|e.to_string())?;
|
||||
self.input.write_all(b"\n").map_err(|e|e.to_string())?;
|
||||
self.input.flush().map_err(|e|e.to_string())?;
|
||||
let reply=self.replies.recv_timeout(Duration::from_secs(30))
|
||||
.map_err(|e|format!("policy response: {e}"))??;
|
||||
if reply.policy != include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/verification/replay-policy/POLICY-SHA256")).trim() {
|
||||
return Err("policy executable does not match the compiled source identity".into())
|
||||
}
|
||||
if reply.allow == reply.reason.is_some() {
|
||||
return Err("policy response has inconsistent verdict and reason".into())
|
||||
}
|
||||
Ok(reply)
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
let _=self.child.kill();
|
||||
let _=self.child.wait();
|
||||
}
|
||||
}
|
||||
+124
-8
@@ -16,14 +16,95 @@ fn ood_int_err(n: impl std::fmt::Display) -> String {
|
||||
format!("json: integer outside V_safe (±(2^53-1)): {n}")
|
||||
}
|
||||
|
||||
/// The integer boundary is semantic, not a property of JSON spelling or the
|
||||
/// host's Int/Num tag. Exponent notation must not bypass it.
|
||||
fn checked_number(n: f64) -> Result<serde_json::Value, String> {
|
||||
if !n.is_finite() { return Err("json: non-finite number outside V_safe".into()); }
|
||||
if n.fract() == 0.0 && n.abs() > MAX_SAFE_INT as f64 { return Err(ood_int_err(n)); }
|
||||
Ok(serde_json::Value::Number(serde_json::Number::from_f64(n)
|
||||
.ok_or("json: non-finite number outside V_safe")?))
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum DecodeError { Syntax(String), Domain(String) }
|
||||
|
||||
struct BoundaryValue(Value);
|
||||
impl<'de> serde::Deserialize<'de> for BoundaryValue {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
|
||||
struct BoundaryVisitor;
|
||||
impl<'de> serde::de::Visitor<'de> for BoundaryVisitor {
|
||||
type Value = BoundaryValue;
|
||||
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str("a boundary JSON value") }
|
||||
fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::None)) }
|
||||
fn visit_bool<E: serde::de::Error>(self, v: bool) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Bool(v))) }
|
||||
fn visit_i64<E: serde::de::Error>(self, n: i64) -> Result<Self::Value,E> {
|
||||
if !in_safe_int(n) { return Err(E::custom(ood_int_err(n))); }
|
||||
Ok(BoundaryValue(Value::Int(n)))
|
||||
}
|
||||
fn visit_u64<E: serde::de::Error>(self, n: u64) -> Result<Self::Value,E> {
|
||||
if n > MAX_SAFE_INT as u64 { return Err(E::custom(ood_int_err(n))); }
|
||||
Ok(BoundaryValue(Value::Int(n as i64)))
|
||||
}
|
||||
fn visit_f64<E: serde::de::Error>(self, n: f64) -> Result<Self::Value,E> {
|
||||
checked_number(n).map_err(E::custom)?;
|
||||
Ok(BoundaryValue(Value::Num(n)))
|
||||
}
|
||||
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Text(v.into()))) }
|
||||
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value,E> { Ok(BoundaryValue(Value::Text(v))) }
|
||||
fn visit_seq<A: serde::de::SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value,A::Error> {
|
||||
let mut xs = Vec::new();
|
||||
while let Some(BoundaryValue(v)) = seq.next_element()? { xs.push(v); }
|
||||
Ok(BoundaryValue(Value::List(xs)))
|
||||
}
|
||||
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Self::Value,A::Error> {
|
||||
use serde::de::Error;
|
||||
let mut fields = Vec::new();
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
while let Some(key) = map.next_key::<String>()? {
|
||||
if !keys.insert(key.clone()) { return Err(A::Error::custom("json: duplicate object key outside V_safe")); }
|
||||
let BoundaryValue(v) = map.next_value()?;
|
||||
fields.push((key, v));
|
||||
}
|
||||
// Preserve the pre-existing JSON object's canonical key order.
|
||||
fields.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
let value = Value::Map(fields);
|
||||
value_to_json(&value).map_err(A::Error::custom)?;
|
||||
Ok(BoundaryValue(value))
|
||||
}
|
||||
}
|
||||
de.deserialize_any(BoundaryVisitor)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn decode_text(text: &str) -> Result<Value, DecodeError> {
|
||||
use serde::Deserialize;
|
||||
let classify = |error: serde_json::Error| {
|
||||
let message = error.to_string();
|
||||
// serde_json categorizes its own numeric-overflow diagnostic as Syntax.
|
||||
// It is a domain refusal for a grammar-valid unbounded JSON number.
|
||||
// Match this trusted decoder diagnostic, never foreign program output.
|
||||
if message.starts_with("number out of range at line ") {
|
||||
return DecodeError::Domain(format!("json: number outside V_safe: {message}"));
|
||||
}
|
||||
match error.classify() {
|
||||
serde_json::error::Category::Data => DecodeError::Domain(message),
|
||||
_ => DecodeError::Syntax(message),
|
||||
}
|
||||
};
|
||||
let mut de = serde_json::Deserializer::from_str(text);
|
||||
let value = BoundaryValue::deserialize(&mut de).map_err(classify)?;
|
||||
de.end().map_err(classify)?;
|
||||
Ok(value.0)
|
||||
}
|
||||
|
||||
pub fn parse(text: &Value) -> Result<Value, String> {
|
||||
let s = match text {
|
||||
Value::Text(s) => s.as_str(),
|
||||
_ => return Err("json parse needs text".into()),
|
||||
};
|
||||
let v: serde_json::Value =
|
||||
serde_json::from_str(s).map_err(|e| format!("json parse: {e}"))?;
|
||||
json_to_value(&v)
|
||||
decode_text(s).map_err(|e| match e {
|
||||
DecodeError::Syntax(e) | DecodeError::Domain(e) => format!("json parse: {e}"),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn stringify(value: &Value, indent: Option<&Value>) -> Result<Value, String> {
|
||||
@@ -93,6 +174,7 @@ pub(crate) fn json_to_value(v: &serde_json::Value) -> Result<Value, String> {
|
||||
return Err(ood_int_err(u));
|
||||
} else if let Some(f) = n.as_f64() {
|
||||
// Host extension: non-integer JSON numbers → Num (not in Lean SafeVal).
|
||||
checked_number(f)?;
|
||||
Value::Num(f)
|
||||
} else {
|
||||
return Err(format!("json: unsupported number: {n}"));
|
||||
@@ -126,9 +208,7 @@ pub(crate) fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
}
|
||||
serde_json::Value::Number((*n).into())
|
||||
}
|
||||
Value::Num(n) => serde_json::Number::from_f64(*n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
Value::Num(n) => checked_number(*n)?,
|
||||
Value::Text(s) => serde_json::Value::String(s.clone()),
|
||||
Value::List(xs) => {
|
||||
let mut arr = Vec::with_capacity(xs.len());
|
||||
@@ -169,7 +249,7 @@ pub(crate) fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
cells.push(
|
||||
serde_json::Number::from_f64(n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
.ok_or_else(|| "json: non-finite number outside V_safe".to_string())?,
|
||||
);
|
||||
}
|
||||
arr.push(serde_json::Value::Array(cells));
|
||||
@@ -181,7 +261,7 @@ pub(crate) fn value_to_json(v: &Value) -> Result<serde_json::Value, String> {
|
||||
if let crate::formula::Expr::Num(n) = s {
|
||||
serde_json::Number::from_f64(n)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null)
|
||||
.ok_or_else(|| "json: non-finite number outside V_safe".to_string())?
|
||||
} else {
|
||||
serde_json::Value::String(e.as_display())
|
||||
}
|
||||
@@ -302,4 +382,40 @@ mod tests {
|
||||
let err = value_to_json(&ragged).unwrap_err();
|
||||
assert!(err.contains("arity mismatch"), "{err}");
|
||||
}
|
||||
#[test]
|
||||
fn refuse_nonfinite_in_nested_payloads() {
|
||||
for n in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
for v in [Value::Num(n), Value::List(vec![Value::Num(n)]),
|
||||
Value::Map(vec![("x".into(), Value::Num(n))])] {
|
||||
assert!(value_to_json(&v).unwrap_err().contains("outside V_safe"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exponent_and_float_tags_cannot_bypass_integer_domain() {
|
||||
for text in ["9007199254740992.0", "9.007199254740992e15", "1e100", "1e9999", "-9.007199254740992e15"] {
|
||||
assert!(parse(&Value::Text(text.into())).unwrap_err().contains("outside V_safe"), "{text}");
|
||||
}
|
||||
for n in [9_007_199_254_740_992.0, -9_007_199_254_740_992.0, 1e100] {
|
||||
assert!(value_to_json(&Value::List(vec![Value::Num(n)])).unwrap_err().contains("outside V_safe"));
|
||||
}
|
||||
for text in ["1.5", "-0.0", "9.007199254740991e15"] {
|
||||
assert!(parse(&Value::Text(text.into())).is_ok(), "valid extension {text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_decode_refuses_duplicate_keys_and_ragged_columns() {
|
||||
for text in [r#"{"a":1,"a":2}"#, r#"[{"x":null,"x":true}]"#,
|
||||
r#"{"a":[1],"b":[2,3]}"#] {
|
||||
assert!(matches!(decode_text(text), Err(DecodeError::Domain(_))), "{text}");
|
||||
}
|
||||
for text in [r#"{"a":[1],"b":"metadata"}"#, r#"{"a":[],"b":[]}"#,
|
||||
r#"{"__proto__":{"safe":true},"constructor":"data"}"#] {
|
||||
assert!(decode_text(text).is_ok(), "{text}");
|
||||
}
|
||||
assert!(matches!(decode_text("not JSON"), Err(DecodeError::Syntax(_))));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -23,6 +23,7 @@ mod hash;
|
||||
mod html_ops;
|
||||
pub(crate) mod json;
|
||||
mod log;
|
||||
pub(crate) mod oracle;
|
||||
pub mod math;
|
||||
mod net;
|
||||
mod path;
|
||||
@@ -106,6 +107,7 @@ pub struct HostContext {
|
||||
/// LCG state for `random` / `random_int`.
|
||||
pub rng: u64,
|
||||
pub plots: Vec<PlotArtifact>,
|
||||
pub oracle_observations: Vec<crate::value::Value>,
|
||||
/// lang → interpreter argv (from `set_cmd`).
|
||||
pub foreign_cmds: HashMap<String, Vec<String>>,
|
||||
/// Process-local language registrations (`register` / `set_cmd`).
|
||||
@@ -120,6 +122,12 @@ pub struct HostContext {
|
||||
/// Monotonic session id counter.
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_session_seq: u64,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_protocol_steps: Vec<foreign_session::ProtocolStep>,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_replay_expected: Option<foreign_session::validation::ReplayCursor>,
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub foreign_replay_divergence: Option<String>,
|
||||
/// Loaded native plugins (ABI v1/v2).
|
||||
pub plugins: PluginState,
|
||||
/// Entry `.mq.md` source text (for ABI host_query / context injection).
|
||||
@@ -154,6 +162,7 @@ impl Default for HostContext {
|
||||
sleep_limit_ms: Some(30_000),
|
||||
rng: 0xC0FF_EE42_CAFE_BABE,
|
||||
plots: Vec::new(),
|
||||
oracle_observations: Vec::new(),
|
||||
foreign_cmds: HashMap::new(),
|
||||
foreign_specs: HashMap::new(),
|
||||
foreign_config_specs: HashMap::new(),
|
||||
@@ -162,6 +171,12 @@ impl Default for HostContext {
|
||||
foreign_sessions: HashMap::new(),
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_session_seq: 0,
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_protocol_steps: Vec::new(),
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_replay_expected: None,
|
||||
#[cfg(feature = "exec-host")]
|
||||
foreign_replay_divergence: None,
|
||||
plugins: PluginState::default(),
|
||||
entry_source: None,
|
||||
entry_path: None,
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
//! Document-level observations, separate from process timing and execution logs.
|
||||
use crate::value::Value;
|
||||
use super::HostContext;
|
||||
|
||||
pub(crate) fn admit(value: &Value) -> Result<(), String> {
|
||||
match value {
|
||||
Value::None | Value::Bool(_) | Value::Text(_) => Ok(()),
|
||||
Value::Int(_) => super::json::value_to_json(value).map(|_| ()),
|
||||
Value::Num(_) => super::json::value_to_json(value).map(|_| ()),
|
||||
Value::List(xs) => { for x in xs { admit(x)?; } Ok(()) }
|
||||
Value::Map(xs) => {
|
||||
super::json::value_to_json(value)?;
|
||||
let mut keys = std::collections::HashSet::new();
|
||||
for (key, x) in xs {
|
||||
if !keys.insert(key) { return Err("oracle: duplicate record field".into()); }
|
||||
admit(x)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
_ => Err("oracle: value outside V_safe".into()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn append(ctx: &mut HostContext, channel: &str, value: &Value) -> Result<(), String> {
|
||||
admit(value)?;
|
||||
ctx.oracle_observations.push(Value::Map(vec![
|
||||
("index".into(), Value::Int(ctx.oracle_observations.len() as i64)),
|
||||
("channel".into(), Value::Text(channel.into())),
|
||||
("value".into(), value.clone()),
|
||||
]));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Project a process result to its semantic observation. Success observes the
|
||||
/// returned payload. Failure observes stable diagnostics, never elapsed time,
|
||||
/// command paths or opaque handles. Both document and live runners use this.
|
||||
pub(crate) fn eval_observation(record: &Value) -> Result<Value, String> {
|
||||
let Value::Map(fields) = record else { return Err("oracle: expected eval record".into()) };
|
||||
let get = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_,v)|v.clone()).unwrap_or(Value::None);
|
||||
let value = match get("ok") {
|
||||
Value::Bool(true) => get("result"),
|
||||
Value::Bool(false) => {
|
||||
let source = get("diagnostic_source");
|
||||
Value::Map(["ok", "code", "stdout", "stderr", "error", "timed_out", "alive"]
|
||||
.into_iter().map(|key| {
|
||||
let value = get(key);
|
||||
// Alpha-rename only this execution's allocated source path,
|
||||
// only in diagnostics. Keep raw output and ordinary paths intact.
|
||||
let value = match (key, value, &source) {
|
||||
("stderr" | "error", Value::Text(text), Value::Text(path)) if !path.is_empty() =>
|
||||
Value::Text(text.replace(path, "<foreign-source>")),
|
||||
(_, value, _) => value,
|
||||
};
|
||||
(key.to_string(), value)
|
||||
}).collect())
|
||||
},
|
||||
_ => return Err("oracle: eval record missing boolean ok".into()),
|
||||
};
|
||||
admit(&value)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn validate(journal: &Value) -> Result<&[Value], String> {
|
||||
let Value::List(rows) = journal else { return Err("oracle journal must be a list".into()) };
|
||||
for (i, row) in rows.iter().enumerate() {
|
||||
let Value::Map(fields) = row else { return Err(format!("oracle step {i}: expected record")) };
|
||||
if fields.len() != 3 { return Err(format!("oracle step {i}: expected index/channel/value")); }
|
||||
let get = |k: &str| fields.iter().find(|(key,_)| key == k).map(|(_,v)|v);
|
||||
if get("index") != Some(&Value::Int(i as i64)) { return Err(format!("oracle step {i}: invalid index")); }
|
||||
if !matches!(get("channel"), Some(Value::Text(s)) if ["eval", "get", "decode"].contains(&s.as_str())) {
|
||||
return Err(format!("oracle step {i}: invalid channel"));
|
||||
}
|
||||
admit(get("value").ok_or_else(|| format!("oracle step {i}: missing value"))?)?;
|
||||
}
|
||||
Ok(rows)
|
||||
}
|
||||
|
||||
/// Pure structural equality on admitted journals; reports the least differing index.
|
||||
pub(crate) fn replay_check(expected: &Value, observed: &Value) -> Result<Value, String> {
|
||||
let a = validate(expected)?;
|
||||
let b = validate(observed)?;
|
||||
// Map field order is not part of record identity (matches JSON object semantics).
|
||||
let canonical = |v: &Value| super::json::value_to_json(v);
|
||||
let mut mismatch = None;
|
||||
for i in 0..a.len().max(b.len()) {
|
||||
if a.get(i).map(canonical).transpose()? != b.get(i).map(canonical).transpose()? {
|
||||
mismatch = Some(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
let index = mismatch.map(|i| Value::Int(i as i64)).unwrap_or(Value::None);
|
||||
Ok(Value::Map(vec![
|
||||
("ok".into(), Value::Bool(mismatch.is_none())),
|
||||
("index".into(), index),
|
||||
("expected".into(), mismatch.and_then(|i| a.get(i)).cloned().unwrap_or(Value::None)),
|
||||
("observed".into(), mismatch.and_then(|i| b.get(i)).cloned().unwrap_or(Value::None)),
|
||||
]))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn oracle_journal_structural_mismatch_and_length() {
|
||||
let mut ctx = HostContext::default();
|
||||
append(&mut ctx, "eval", &Value::Int(3)).unwrap();
|
||||
append(&mut ctx, "get", &Value::Int(2)).unwrap();
|
||||
let journal = Value::List(ctx.oracle_observations.clone());
|
||||
let result = replay_check(&journal, &journal).unwrap();
|
||||
assert_eq!(super::super::json::get(&result, &Value::Text("ok".into())).unwrap(), Value::Bool(true));
|
||||
let short = Value::List(ctx.oracle_observations[..1].to_vec());
|
||||
let result = replay_check(&journal, &short).unwrap();
|
||||
assert_eq!(super::super::json::get(&result, &Value::Text("index".into())).unwrap(), Value::Int(1));
|
||||
assert!(append(&mut ctx, "eval", &Value::List(vec![Value::Handle("x".into())])).is_err());
|
||||
let code = Value::Code(crate::value::CodeBlock { lang: "python".into(), source: "1".into() });
|
||||
assert!(admit(&Value::List(vec![code])).is_err());
|
||||
assert_eq!(ctx.oracle_observations.len(), 2);
|
||||
}
|
||||
#[test]
|
||||
fn diagnostic_projection_renames_only_allocated_source_identity() {
|
||||
let make = |path: &str, message: &str| Value::Map(vec![
|
||||
("ok".into(), Value::Bool(false)),
|
||||
("stderr".into(), Value::Text(format!("File {path}: {message}; input /data/original.csv"))),
|
||||
("diagnostic_source".into(), Value::Text(path.into())),
|
||||
]);
|
||||
let a = make("/tmp/allocated-a.py", "ValueError");
|
||||
let b = make("/tmp/allocated-b.py", "ValueError");
|
||||
assert_ne!(a, b, "raw diagnostics must survive");
|
||||
assert_eq!(eval_observation(&a).unwrap(), eval_observation(&b).unwrap());
|
||||
let c = make("/tmp/allocated-b.py", "TypeError");
|
||||
assert_ne!(eval_observation(&a).unwrap(), eval_observation(&c).unwrap());
|
||||
let d = make("/tmp/allocated-b.py", "ValueError /data/changed.csv");
|
||||
assert_ne!(eval_observation(&a).unwrap(), eval_observation(&d).unwrap());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -194,6 +194,17 @@ impl Clone for PluginState {
|
||||
}
|
||||
|
||||
impl PluginState {
|
||||
/// Exercise the real JSON/C ABI without loading an external shared library.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn register_binding_probe(&mut self) {
|
||||
unsafe extern "C" fn echo(args: *const c_char, out: *mut *mut c_char, _err: *mut *mut c_char) -> c_int {
|
||||
if args.is_null() || out.is_null() { return 1; }
|
||||
let Ok(input)=CStr::from_ptr(args).to_str() else { return 1; };
|
||||
*out=host_strdup(input);
|
||||
if (*out).is_null() {1} else {0}
|
||||
}
|
||||
self.fns.insert("binding_probe".into(),RegisteredFn{params:vec!["a".into(),"b".into()],fn_ptr:echo});
|
||||
}
|
||||
pub fn get(&self, name: &str) -> Option<&RegisteredFn> {
|
||||
self.fns.get(name)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user