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:
cflmyandCursor committed 2026-11-06 15:04:27 +08:00
1 parent e3d9021bb6
commit 8f1010f967
101 files changed
+17962 -1727

No files matched your search

+204
View File
@@ -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();
}
}
}
+173
View File
@@ -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();
}
}