release: v2.1.4 isolated HTTP execute (ADR 0009)

Default execute/sse-live/stream to Supervisor worker pool; MR-01 gold;
/_runtime/*; bump CLI/wasm/ext to 2.1.4.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-10-26 18:33:33 +08:00
1 parent 58e13ee6d3
commit 3cabe53da2
56 files changed
+4957 -304

No files matched your search

+359 -86
View File
@@ -1,24 +1,87 @@
//! Project snapshot analysis cache (M05 / F14): keyed by project_root + source digests.
//! Concurrent same-snapshot requests coalesce: waiters reuse the leader's result.
//! AnalysisCache v2 (M-R5): SnapshotKey → Arc<Compilation> with single-flight.
//! Cache hits must reuse the compilation result, not merely a digest ticket.
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::collections::{HashMap, VecDeque};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::Instant;
use std::sync::{Arc, Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};
use crate::sema::Compilation;
/// Full-project snapshot identity (design §8.1). Built from the compiler's
/// source enumeration — never a truncated `take(200)` directory listing.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct SnapshotKey {
pub project_identity: String,
pub source_digest: String,
pub compiler_version: String,
}
impl SnapshotKey {
pub fn compute(project_root: &Path) -> Result<Self, String> {
let root = crate::project::ProjectRoot::new(project_root)
.map_err(|e| format!("snapshot.project: {e:#}"))?;
let files = root
.source_files()
.map_err(|e| format!("snapshot.enumerate: {e:#}"))?;
let mut h = Sha256::new();
h.update(root.path().to_string_lossy().as_bytes());
for p in &files {
let rel = p
.strip_prefix(root.path())
.unwrap_or(p)
.to_string_lossy();
h.update(rel.as_bytes());
let meta =
std::fs::metadata(p).map_err(|e| format!("snapshot.meta {}: {e}", p.display()))?;
h.update(meta.len().to_le_bytes());
let bytes =
std::fs::read(p).map_err(|e| format!("snapshot.read {}: {e}", p.display()))?;
h.update(&bytes);
}
let identity = root
.path()
.canonicalize()
.unwrap_or_else(|_| root.path().to_path_buf())
.to_string_lossy()
.to_string();
Ok(Self {
project_identity: identity,
source_digest: format!("{:x}", h.finalize()),
compiler_version: env!("CARGO_PKG_VERSION").to_string(),
})
}
pub fn cache_key(&self) -> String {
format!(
"{}::{}::{}",
self.project_identity, self.source_digest, self.compiler_version
)
}
}
#[derive(Clone)]
struct CacheEntry {
digest_key: String,
#[allow(dead_code)]
key: SnapshotKey,
compilation: Arc<Compilation>,
bytes: usize,
#[allow(dead_code)]
compiled_at: Instant,
}
struct InflightSlot {
waiters: usize,
result: Option<Result<Arc<Compilation>, String>>,
}
struct CacheState {
order: VecDeque<String>,
entries: HashMap<String, CacheEntry>,
/// project_key → refcount of leaders currently analyzing.
inflight: HashMap<String, usize>,
inflight: HashMap<String, InflightSlot>,
bytes_used: usize,
budget_bytes: usize,
}
fn cache() -> &'static (Mutex<CacheState>, Condvar) {
@@ -26,44 +89,217 @@ fn cache() -> &'static (Mutex<CacheState>, Condvar) {
C.get_or_init(|| {
(
Mutex::new(CacheState {
order: VecDeque::new(),
entries: HashMap::new(),
inflight: HashMap::new(),
bytes_used: 0,
budget_bytes: default_budget_bytes(),
}),
Condvar::new(),
)
})
}
fn default_budget_bytes() -> usize {
512 * 1024 * 1024
}
static HITS: AtomicU64 = AtomicU64::new(0);
static MISSES: AtomicU64 = AtomicU64::new(0);
static MERGES: AtomicU64 = AtomicU64::new(0);
static COMPILE_INVOCATIONS: AtomicU64 = AtomicU64::new(0);
static EVICTIONS: AtomicU64 = AtomicU64::new(0);
static RESULT_HITS: AtomicU64 = AtomicU64::new(0);
pub fn project_source_digest(project_root: &Path) -> String {
let mut h = Sha256::new();
h.update(project_root.to_string_lossy().as_bytes());
let mut paths: Vec<PathBuf> = Vec::new();
if let Ok(rd) = std::fs::read_dir(project_root) {
for ent in rd.flatten().take(200) {
let p = ent.path();
if p.extension().and_then(|e| e.to_str()) == Some("md")
|| p
.file_name()
.and_then(|n| n.to_str())
.map(|n| n.ends_with(".mq.md"))
.unwrap_or(false)
{
paths.push(p);
fn key_compiles() -> &'static Mutex<HashMap<String, u64>> {
static K: OnceLock<Mutex<HashMap<String, u64>>> = OnceLock::new();
K.get_or_init(|| Mutex::new(HashMap::new()))
}
fn estimate_bytes(c: &Compilation) -> usize {
let arts = c.semantics.artifacts.len() * 512;
let refs = c.semantics.refs.len() * 128;
let steps = c.semantics.steps.len() * 128;
let diags = c.diagnostics.len() * 64;
4096 + arts + refs + steps + diags
}
enum Admit {
Hit(Arc<Compilation>),
Wait,
Lead,
}
fn admit(key: &str) -> Admit {
let (lock, _cv) = cache();
let mut g = lock.lock().unwrap();
if let Some(e) = g.entries.get(key) {
let arc = Arc::clone(&e.compilation);
if let Some(pos) = g.order.iter().position(|k| k == key) {
g.order.remove(pos);
}
g.order.push_back(key.to_string());
HITS.fetch_add(1, Ordering::Relaxed);
RESULT_HITS.fetch_add(1, Ordering::Relaxed);
return Admit::Hit(arc);
}
if g.inflight.contains_key(key) {
if let Some(slot) = g.inflight.get_mut(key) {
slot.waiters += 1;
}
MERGES.fetch_add(1, Ordering::Relaxed);
return Admit::Wait;
}
g.inflight.insert(
key.to_string(),
InflightSlot {
waiters: 0,
result: None,
},
);
MISSES.fetch_add(1, Ordering::Relaxed);
Admit::Lead
}
fn wait_for(key: &str, deadline: Instant) -> Result<Arc<Compilation>, String> {
let (lock, cv) = cache();
let mut g = lock.lock().unwrap();
loop {
if let Some(e) = g.entries.get(key) {
let arc = Arc::clone(&e.compilation);
if let Some(slot) = g.inflight.get_mut(key) {
slot.waiters = slot.waiters.saturating_sub(1);
if slot.waiters == 0 {
g.inflight.remove(key);
}
}
HITS.fetch_add(1, Ordering::Relaxed);
RESULT_HITS.fetch_add(1, Ordering::Relaxed);
return Ok(arc);
}
if let Some(slot) = g.inflight.get(key) {
if let Some(res) = &slot.result {
let out = res.clone();
let waiters = slot.waiters.saturating_sub(1);
if let Some(slot) = g.inflight.get_mut(key) {
slot.waiters = waiters;
if slot.waiters == 0 {
g.inflight.remove(key);
}
}
HITS.fetch_add(1, Ordering::Relaxed);
RESULT_HITS.fetch_add(1, Ordering::Relaxed);
return out;
}
} else {
// Leader finished without leaving a result — retry admit.
return Err("analysis.retry".into());
}
let remaining = deadline.saturating_duration_since(Instant::now());
if remaining.is_zero() {
if let Some(slot) = g.inflight.get_mut(key) {
slot.waiters = slot.waiters.saturating_sub(1);
if slot.waiters == 0 && slot.result.is_none() {
g.inflight.remove(key);
}
}
return Err("analysis.wait_deadline".into());
}
let (guard, timeout) = cv.wait_timeout(g, remaining).unwrap();
g = guard;
if timeout.timed_out() {
if let Some(slot) = g.inflight.get_mut(key) {
slot.waiters = slot.waiters.saturating_sub(1);
if slot.waiters == 0 && slot.result.is_none() {
g.inflight.remove(key);
}
}
return Err("analysis.wait_deadline".into());
}
}
}
fn finish_leader(key: &str, snap: SnapshotKey, compiled: Result<Arc<Compilation>, String>) {
if compiled.is_ok() {
let mut kc = key_compiles().lock().unwrap();
*kc.entry(key.to_string()).or_insert(0) += 1;
}
let (lock, cv) = cache();
let mut g = lock.lock().unwrap();
if let Ok(ref arc) = compiled {
insert_entry(&mut g, snap, Arc::clone(arc));
}
if let Some(slot) = g.inflight.get_mut(key) {
slot.result = Some(compiled);
if slot.waiters == 0 {
g.inflight.remove(key);
}
}
cv.notify_all();
}
/// Compile once per SnapshotKey; followers await the same Arc<Compilation>.
pub fn get_or_compile(project_root: &Path) -> Result<Arc<Compilation>, String> {
let snap = SnapshotKey::compute(project_root)?;
let key = snap.cache_key();
let deadline = Instant::now() + Duration::from_secs(300);
loop {
match admit(&key) {
Admit::Hit(arc) => return Ok(arc),
Admit::Wait => match wait_for(&key, deadline) {
Err(e) if e == "analysis.retry" => continue,
other => return other,
},
Admit::Lead => {
let compiled = compile_leader(project_root);
COMPILE_INVOCATIONS.fetch_add(1, Ordering::Relaxed);
let out = compiled.clone();
finish_leader(&key, snap, compiled);
return out;
}
}
}
paths.sort();
for p in paths {
h.update(p.to_string_lossy().as_bytes());
if let Ok(bytes) = std::fs::read(&p) {
h.update(&bytes);
}
fn compile_leader(project_root: &Path) -> Result<Arc<Compilation>, String> {
let options = crate::sema::CompileOptions::for_path(project_root)
.map_err(|e| format!("view.compile_failed: {e:#}"))?;
let c = crate::sema::compile_project(&options)
.map_err(|e| format!("view.compile_failed: {e:#}"))?;
Ok(Arc::new(c))
}
fn insert_entry(g: &mut CacheState, key: SnapshotKey, compilation: Arc<Compilation>) {
let ck = key.cache_key();
let bytes = estimate_bytes(&compilation);
while g.bytes_used + bytes > g.budget_bytes && !g.order.is_empty() {
if let Some(old) = g.order.pop_front() {
if let Some(e) = g.entries.remove(&old) {
g.bytes_used = g.bytes_used.saturating_sub(e.bytes);
EVICTIONS.fetch_add(1, Ordering::Relaxed);
}
}
}
format!("{:x}", h.finalize())
if bytes > g.budget_bytes || g.entries.contains_key(&ck) {
return;
}
g.bytes_used += bytes;
g.order.push_back(ck.clone());
g.entries.insert(
ck,
CacheEntry {
key,
compilation,
bytes,
compiled_at: Instant::now(),
},
);
}
pub fn project_source_digest(project_root: &Path) -> String {
SnapshotKey::compute(project_root)
.map(|k| k.source_digest)
.unwrap_or_else(|_| "digest-error".into())
}
fn project_key(project_root: &Path) -> String {
@@ -74,74 +310,38 @@ fn project_key(project_root: &Path) -> String {
.to_string()
}
/// Ticket for a leader analysis; must call [`finish_analysis`] (or drop via finish).
pub struct AnalysisTicket {
#[allow(dead_code)]
key: String,
#[allow(dead_code)]
digest: String,
/// true ⇒ this caller is the leader and must run compile then finish.
pub is_leader: bool,
}
/// Begin analysis: cache hit / wait for in-flight leader / become leader.
pub fn begin_analysis(project_root: &Path) -> AnalysisTicket {
let key = project_key(project_root);
let digest = project_source_digest(project_root);
let (lock, cv) = cache();
let mut g = lock.lock().unwrap();
loop {
if let Some(e) = g.entries.get(&key) {
if e.digest_key == digest {
HITS.fetch_add(1, Ordering::Relaxed);
return AnalysisTicket {
key,
digest,
is_leader: false,
};
}
}
if g.inflight.contains_key(&key) {
MERGES.fetch_add(1, Ordering::Relaxed);
g = cv.wait(g).unwrap();
continue;
}
*g.inflight.entry(key.clone()).or_insert(0) += 1;
MISSES.fetch_add(1, Ordering::Relaxed);
return AnalysisTicket {
key,
digest,
match get_or_compile(project_root) {
Ok(_) => AnalysisTicket {
key: project_key(project_root),
digest: project_source_digest(project_root),
is_leader: false,
},
Err(_) => AnalysisTicket {
key: project_key(project_root),
digest: String::new(),
is_leader: true,
};
}
}
pub fn finish_analysis(ticket: AnalysisTicket) {
if !ticket.is_leader {
return;
}
let (lock, cv) = cache();
let mut g = lock.lock().unwrap();
g.entries.insert(
ticket.key.clone(),
CacheEntry {
digest_key: ticket.digest,
compiled_at: Instant::now(),
},
);
if let Some(n) = g.inflight.get_mut(&ticket.key) {
*n = n.saturating_sub(1);
if *n == 0 {
g.inflight.remove(&ticket.key);
}
}
cv.notify_all();
}
/// Compatibility: note without holding across compile (prefer begin/finish).
pub fn finish_analysis(_ticket: AnalysisTicket) {}
pub fn note_analysis(project_root: &Path) -> bool {
let t = begin_analysis(project_root);
let hit = !t.is_leader;
finish_analysis(t);
hit
// True iff this SnapshotKey was already cached (result hit), independent of
// other projects compiled concurrently in the same process.
let before = compile_count_for(project_root);
let _ = get_or_compile(project_root);
let after = compile_count_for(project_root);
after == before && before > 0
}
pub fn cache_keys_isolated(a: &Path, b: &Path) -> bool {
@@ -156,13 +356,86 @@ pub fn cache_stats() -> (u64, u64, u64) {
)
}
pub fn compile_invocations() -> u64 {
COMPILE_INVOCATIONS.load(Ordering::Relaxed)
}
/// Successful compile count for one SnapshotKey (M-R5 / MR-06).
pub fn compile_count_for(project_root: &Path) -> u64 {
let Ok(snap) = SnapshotKey::compute(project_root) else {
return 0;
};
key_compiles()
.lock()
.unwrap()
.get(&snap.cache_key())
.copied()
.unwrap_or(0)
}
pub fn result_hits() -> u64 {
RESULT_HITS.load(Ordering::Relaxed)
}
pub fn eviction_count() -> u64 {
EVICTIONS.load(Ordering::Relaxed)
}
pub fn reset_cache_for_tests() {
let (lock, cv) = cache();
let mut g = lock.lock().unwrap();
g.entries.clear();
g.order.clear();
g.inflight.clear();
g.bytes_used = 0;
HITS.store(0, Ordering::Relaxed);
MISSES.store(0, Ordering::Relaxed);
MERGES.store(0, Ordering::Relaxed);
COMPILE_INVOCATIONS.store(0, Ordering::Relaxed);
EVICTIONS.store(0, Ordering::Relaxed);
RESULT_HITS.store(0, Ordering::Relaxed);
key_compiles().lock().unwrap().clear();
cv.notify_all();
}
/// Serialize tests that call [`reset_cache_for_tests`] so parallel suites cannot
/// clear another test's SnapshotKey mid-flight. Recovers from poison so one
/// failing cache test does not brick the rest of the suite.
pub fn test_serial_guard() -> std::sync::MutexGuard<'static, ()> {
static G: OnceLock<Mutex<()>> = OnceLock::new();
let m = G.get_or_init(|| Mutex::new(()));
m.lock().unwrap_or_else(|p| p.into_inner())
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::{Arc, Barrier};
use std::thread;
#[test]
fn same_snapshot_compiles_once_under_load() {
let _g = test_serial_guard();
reset_cache_for_tests();
let root = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/executable_knowledge/baseline/02-extract");
let n = 32usize;
let barrier = Arc::new(Barrier::new(n));
let mut handles = Vec::with_capacity(n);
for _ in 0..n {
let barrier = Arc::clone(&barrier);
let root = root.clone();
handles.push(thread::spawn(move || {
barrier.wait();
get_or_compile(&root).expect("compile")
}));
}
let first = handles.pop().unwrap().join().unwrap();
for h in handles {
let arc = h.join().unwrap();
assert!(Arc::ptr_eq(&first, &arc), "followers must share the same Arc");
}
assert_eq!(compile_count_for(&root), 1);
assert_eq!(compile_invocations(), 1);
}
}
+11
View File
@@ -89,13 +89,22 @@ pub fn probe_capabilities(params: &Value) -> Value {
"runtime.cancel".into(),
json!(if cancel_off { 0 } else { 1 }),
);
// Isolated web runtime (doc/design/isolated-web-runtime-development-2026-10-26.md).
// HTTP execute / sse-live defaults to the Supervisor worker pool (ADR 0009).
features.insert("runtime.isolated_execution".into(), json!(1));
// task_control_v2 / event_replay: host_query("runtime") + /_runtime/* system routes.
features.insert("runtime.task_control_v2".into(), json!(1));
features.insert("runtime.event_replay".into(), json!(1));
features.insert("runtime.read_lane".into(), json!(0));
#[cfg(feature = "view")]
{
features.insert("view.analysis_cache_v2".into(), json!(1));
features.insert("view.document".into(), json!(1));
features.insert("view.reference_resolve".into(), json!(1));
}
#[cfg(not(feature = "view"))]
{
features.insert("view.analysis_cache_v2".into(), json!(0));
features.insert("view.document".into(), json!(0));
features.insert("view.reference_resolve".into(), json!(0));
}
@@ -111,6 +120,8 @@ pub fn probe_capabilities(params: &Value) -> Value {
"ModelSelectionV1",
"ModelCallUsageV1",
"RuntimeEventV1",
"RuntimeEventV2",
"InvokeRequestV2",
"DocumentViewV1",
"KnowledgeLocatorV1"
]
+3 -14
View File
@@ -92,20 +92,9 @@ pub fn build_document_view(req: &DocumentViewRequest) -> Result<Value, Value> {
let title = title_from_source(&source, &req.document);
// Semantic projection — compile_project does not load plugins / evaluate.
// Hold analysis lock across compile so concurrent same-snapshot reads coalesce (F14).
let ticket = crate::workbench::analysis_cache::begin_analysis(&project_root);
let options = crate::sema::CompileOptions::for_path(&project_root)
.map_err(|e| err("view.compile_failed", format!("{e:#}")))?;
let compilation = match crate::sema::compile_project(&options) {
Ok(c) => {
crate::workbench::analysis_cache::finish_analysis(ticket);
c
}
Err(e) => {
crate::workbench::analysis_cache::finish_analysis(ticket);
return Err(err("view.compile_failed", format!("{e:#}")));
}
};
// M-R5: Arc<Compilation> single-flight cache; followers reuse the same result.
let compilation = crate::workbench::analysis_cache::get_or_compile(&project_root)
.map_err(|e| err("view.compile_failed", e))?;
let rel = req.document.replace('\\', "/");
let mut presentation = KnowledgePresentation::from_project(&compilation.semantics, &rel, &title);
+6 -3
View File
@@ -16,15 +16,18 @@ pub mod snapshot;
pub mod usage;
pub use analysis_cache::{
begin_analysis, cache_keys_isolated, cache_stats, finish_analysis, note_analysis,
project_source_digest, reset_cache_for_tests, AnalysisTicket,
begin_analysis, cache_keys_isolated, cache_stats, compile_count_for, compile_invocations,
finish_analysis, get_or_compile, note_analysis, project_source_digest, reset_cache_for_tests,
result_hits, test_serial_guard, AnalysisTicket, SnapshotKey,
};
pub use capabilities::probe_capabilities;
#[cfg(feature = "view")]
pub use document_view::{build_document_view, DocumentViewRequest};
pub use event_sink::{bind_event_sink, clear_event_sink, emit_event, emit_message_delta};
pub use locator::{resolve_reference, KnowledgeLocator};
pub use run_context::{cancel_requested, RunContext};
pub use run_context::{
cancel_requested, cancel_token_body_means_cancel, RequestContext, RunContext,
};
pub use selection::{parse_model_selection, ModelSelection};
pub use snapshot::{build_snapshot_manifest, version_unavailable_result};
pub use usage::{
+179 -12
View File
@@ -1,7 +1,61 @@
//! RunContextV1 — request-local run identity for selection / usage / cancel (M01).
//! RunContextV1 — request-local run identity for selection / usage / cancel (M01 / M-R1).
use serde_json::{json, Map, Value};
/// Explicit request Context handles (M-R1). Paths are opaque grants owned by the
/// control plane; callers must not pass browser-supplied absolute paths unchecked.
#[derive(Debug, Clone, Default)]
pub struct RequestContext {
pub workspace_id: Option<String>,
pub snapshot_id: Option<String>,
pub selection_ref: Option<String>,
pub capabilities_ref: Option<String>,
pub deadline_at: Option<String>,
pub lease_id: Option<String>,
pub attempt_id: Option<String>,
pub epoch: Option<u64>,
}
impl RequestContext {
pub fn from_value(v: &Value) -> Self {
Self {
workspace_id: str_opt(v, "workspace_id"),
snapshot_id: str_opt(v, "snapshot_id"),
selection_ref: str_opt(v, "selection_ref"),
capabilities_ref: str_opt(v, "capabilities_ref"),
deadline_at: str_opt(v, "deadline_at"),
lease_id: str_opt(v, "lease_id").or_else(|| {
v.get("lease")
.and_then(|l| l.get("id"))
.and_then(|x| x.as_str())
.map(|s| s.to_string())
}),
attempt_id: str_opt(v, "attempt_id"),
epoch: v
.get("epoch")
.and_then(|x| x.as_u64())
.or_else(|| {
v.get("lease")
.and_then(|l| l.get("epoch"))
.and_then(|x| x.as_u64())
}),
}
}
pub fn to_json(&self) -> Value {
json!({
"workspace_id": self.workspace_id,
"snapshot_id": self.snapshot_id,
"selection_ref": self.selection_ref,
"capabilities_ref": self.capabilities_ref,
"deadline_at": self.deadline_at,
"lease_id": self.lease_id,
"attempt_id": self.attempt_id,
"epoch": self.epoch,
})
}
}
#[derive(Debug, Clone, Default)]
pub struct RunContext {
pub run_id: String,
@@ -12,6 +66,8 @@ pub struct RunContext {
pub usage_sink: Option<String>,
pub event_sink: Option<String>,
pub cancellation_token: Option<String>,
/// Explicit Context object (M-R1); serialized alongside RunContextV1 fields.
pub context: RequestContext,
}
impl RunContext {
@@ -22,6 +78,10 @@ impl RunContext {
.filter(|s| !s.is_empty())
.ok_or_else(|| "run_context.missing:run_id".to_string())?
.to_string();
let context = v
.get("context")
.map(RequestContext::from_value)
.unwrap_or_default();
Ok(Self {
run_id,
parent_run_id: v
@@ -56,6 +116,7 @@ impl RunContext {
.get("cancellation_token")
.and_then(|x| x.as_str())
.map(|s| s.to_string()),
context,
})
}
@@ -71,10 +132,11 @@ impl RunContext {
"usage_sink": self.usage_sink,
"event_sink": self.event_sink,
"cancellation_token": self.cancellation_token,
"context": self.context.to_json(),
})
}
/// Child inherits selection/event/cancel; new run_id linked to parent.
/// Child inherits selection/event/cancel handles; new run_id linked to parent.
pub fn spawn_child(&self, child_run_id: &str) -> Self {
Self {
run_id: child_run_id.to_string(),
@@ -85,10 +147,12 @@ impl RunContext {
usage_sink: self.usage_sink.clone(),
event_sink: self.event_sink.clone(),
cancellation_token: self.cancellation_token.clone(),
context: self.context.clone(),
}
}
/// Env vars for subtask injection (never includes api_key).
/// Env pairs for *child* Command.env injection (never api_key / credential plaintext).
/// Parent process must not `setenv` these to carry request state across tasks.
pub fn selection_env(&self) -> Vec<(String, String)> {
let mut out = Vec::new();
out.push(("MARQDO_RUN_ID".into(), self.run_id.clone()));
@@ -107,6 +171,9 @@ impl RunContext {
if let Some(sink) = &self.event_sink {
out.push(("MARQDO_EVENT_FORWARD".into(), sink.clone()));
}
if let Some(usage) = &self.usage_sink {
out.push(("MARQDO_USAGE_SINK".into(), usage.clone()));
}
if let Some(model) = self
.selection_context
.get("upstream_model_id")
@@ -124,25 +191,125 @@ impl RunContext {
out.push(("MARQDO_LLM_BASE_URL".into(), base.to_string()));
out.push(("OPENAI_BASE_URL".into(), base.to_string()));
}
// credential_ref only — never expand api_key into child env here.
if let Some(cred) = self
.selection_context
.get("credential_ref")
.and_then(|v| v.as_str())
{
out.push(("MARQDO_CREDENTIAL_REF".into(), cred.to_string()));
}
if let Some(ws) = &self.context.workspace_id {
out.push(("MARQDO_WORKSPACE_ID".into(), ws.clone()));
}
if let Some(snap) = &self.context.snapshot_id {
out.push(("MARQDO_SNAPSHOT_ID".into(), snap.clone()));
}
if let Some(lease) = &self.context.lease_id {
out.push(("MARQDO_LEASE_ID".into(), lease.clone()));
}
if let Some(attempt) = &self.context.attempt_id {
out.push(("MARQDO_ATTEMPT_ID".into(), attempt.clone()));
}
out
}
/// Apply this run's handles onto a child Command without mutating parent env.
pub fn apply_to_command(&self, cmd: &mut std::process::Command) {
for (k, v) in self.selection_env() {
cmd.env(k, v);
}
}
}
/// Check whether a cancel token file/env indicates cancellation.
fn str_opt(v: &Value, key: &str) -> Option<String> {
v.get(key)
.and_then(|x| x.as_str())
.filter(|s| !s.is_empty())
.map(|s| s.to_string())
}
/// Unified cancel-token semantics (M-R1 / design §6):
/// - missing path / missing file → not cancelled
/// - empty body / `"0"` → not cancelled
/// - `"1"` / `"cancelled"` → cancelled
/// - read failure → not cancelled (caller may log); do not treat as cancel
///
/// Process-global `MARQDO_CANCEL` is **not** consulted when an explicit token
/// handle is provided, so parallel tasks cannot cancel each other via env.
pub fn cancel_requested(token: Option<&str>) -> bool {
let Some(tok) = token.filter(|s| !s.is_empty()) else {
return false;
};
// Token may be a path: presence of file or contents "1"/"cancelled" means stop.
let path = std::path::Path::new(tok);
if path.is_file() {
if let Ok(body) = std::fs::read_to_string(path) {
if !path.is_file() {
return false;
}
match std::fs::read_to_string(path) {
Ok(body) => {
let t = body.trim();
return t.is_empty() || t == "1" || t.eq_ignore_ascii_case("cancelled");
t == "1" || t.eq_ignore_ascii_case("cancelled")
}
return true;
Err(_) => false,
}
}
/// Token-file body interpretation used by LLM plugin and control plane alike.
pub fn cancel_token_body_means_cancel(body: &str) -> bool {
let t = body.trim();
t == "1" || t.eq_ignore_ascii_case("cancelled")
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
#[test]
fn empty_and_zero_token_are_not_cancelled() {
let dir = std::env::temp_dir().join(format!("mq-rc-empty-{}", std::process::id()));
let _ = std::fs::remove_file(&dir);
std::fs::File::create(&dir).unwrap();
assert!(!cancel_requested(Some(dir.to_str().unwrap())));
std::fs::write(&dir, "0").unwrap();
assert!(!cancel_requested(Some(dir.to_str().unwrap())));
std::fs::write(&dir, "cancelled").unwrap();
assert!(cancel_requested(Some(dir.to_str().unwrap())));
let _ = std::fs::remove_file(&dir);
}
#[test]
fn explicit_token_ignores_global_marqdo_cancel() {
let dir = std::env::temp_dir().join(format!("mq-rc-ign-{}", std::process::id()));
let _ = std::fs::remove_file(&dir);
let mut f = std::fs::File::create(&dir).unwrap();
f.write_all(b"").unwrap();
drop(f);
std::env::set_var("MARQDO_CANCEL", "1");
assert!(
!cancel_requested(Some(dir.to_str().unwrap())),
"empty token must not cancel even if MARQDO_CANCEL=1"
);
std::env::remove_var("MARQDO_CANCEL");
let _ = std::fs::remove_file(&dir);
}
#[test]
fn context_round_trip() {
let v = json!({
"run_id": "r1",
"cancellation_token": "/tmp/t",
"context": {
"workspace_id": "ws",
"lease": {"id": "lease_1", "epoch": 3},
"attempt_id": "a1"
}
});
let rc = RunContext::from_value(&v).unwrap();
assert_eq!(rc.context.lease_id.as_deref(), Some("lease_1"));
assert_eq!(rc.context.epoch, Some(3));
let child = rc.spawn_child("r2");
assert_eq!(child.parent_run_id.as_deref(), Some("r1"));
assert_eq!(child.context.lease_id.as_deref(), Some("lease_1"));
}
std::env::var("MARQDO_CANCEL")
.map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
.unwrap_or(false)
}