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
+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");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user