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:
1 parent
58e13ee6d3
commit
3cabe53da2
56 files changed
+4957
-304
No files matched your search
+49
-9
@@ -322,6 +322,42 @@ unsafe extern "C" fn host_query(
|
||||
}
|
||||
};
|
||||
|
||||
let args_owned: Option<String> = if args_json.is_null() {
|
||||
None
|
||||
} else {
|
||||
CStr::from_ptr(args_json)
|
||||
.to_str()
|
||||
.ok()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
|
||||
// Control plane (admit/cancel/events) must not take INVOKE_LOCK or require
|
||||
// an evaluating HostContext — otherwise cancel cannot interrupt a busy run.
|
||||
if name == "runtime" {
|
||||
let raw = args_owned.as_deref().unwrap_or("{}");
|
||||
let args: serde_json::Value = match serde_json::from_str(if raw.trim().is_empty() {
|
||||
"{}"
|
||||
} else {
|
||||
raw
|
||||
}) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
set_err(&format!("runtime args: {e}"));
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
match crate::runtime::host_api::handle(&args) {
|
||||
Ok(j) => {
|
||||
set_out(&j.to_string());
|
||||
return 0;
|
||||
}
|
||||
Err(e) => {
|
||||
set_err(&e);
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let ctx_ptr = CURRENT_HOST.with(|c| c.get());
|
||||
let ctx_ptr = if ctx_ptr.is_null() {
|
||||
global_host_slot()
|
||||
@@ -348,15 +384,6 @@ unsafe extern "C" fn host_query(
|
||||
}
|
||||
let ctx = &mut *ctx_ptr;
|
||||
|
||||
let args_owned: Option<String> = if args_json.is_null() {
|
||||
None
|
||||
} else {
|
||||
CStr::from_ptr(args_json)
|
||||
.to_str()
|
||||
.ok()
|
||||
.map(|s| s.to_string())
|
||||
};
|
||||
|
||||
let result = match name {
|
||||
"module_source" => agent_rt::module_source(ctx).and_then(|v| value_to_json(&v)),
|
||||
"call_site" => agent_rt::call_site(ctx, Some(ctx.current_line)).and_then(|v| value_to_json(&v)),
|
||||
@@ -364,6 +391,19 @@ unsafe extern "C" fn host_query(
|
||||
"cwd" => Ok(serde_json::Value::String(
|
||||
ctx.cwd.to_string_lossy().into_owned(),
|
||||
)),
|
||||
"entry_path" => {
|
||||
let path = ctx.entry_path.clone().unwrap_or_else(|| ctx.cwd.clone());
|
||||
let abs = if path.is_absolute() {
|
||||
path
|
||||
} else {
|
||||
std::env::current_dir()
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
.join(path)
|
||||
};
|
||||
Ok(serde_json::Value::String(
|
||||
abs.to_string_lossy().into_owned(),
|
||||
))
|
||||
}
|
||||
"entry_dir" => {
|
||||
// Script directory: parent of entry file (for_run also sets ctx.cwd to this).
|
||||
let dir = ctx
|
||||
|
||||
+12
-1
@@ -695,7 +695,9 @@ fn require<'a>(bound: &'a HashMap<String, Value>, key: &str) -> Result<&'a Value
|
||||
.ok_or_else(|| format!("host call missing `{key}`"))
|
||||
}
|
||||
|
||||
/// Propagate run/selection identity when parent has them (api_key stays via process inheritance).
|
||||
/// Propagate run/selection identity onto the *child* Command.env map.
|
||||
/// Reads parent env only as a fallback when an explicit RunContext was not
|
||||
/// applied; never uses parent `setenv`/`set_current_dir` as request state (M-R1).
|
||||
fn apply_run_selection_env(cmd: &mut Command) {
|
||||
for key in [
|
||||
"MARQDO_RUN_ID",
|
||||
@@ -703,6 +705,13 @@ fn apply_run_selection_env(cmd: &mut Command) {
|
||||
"MARQDO_TURN_ID",
|
||||
"MARQDO_WORKSPACE_SCOPE",
|
||||
"MARQDO_CANCEL_TOKEN",
|
||||
"MARQDO_EVENT_FORWARD",
|
||||
"MARQDO_USAGE_SINK",
|
||||
"MARQDO_CREDENTIAL_REF",
|
||||
"MARQDO_WORKSPACE_ID",
|
||||
"MARQDO_SNAPSHOT_ID",
|
||||
"MARQDO_LEASE_ID",
|
||||
"MARQDO_ATTEMPT_ID",
|
||||
"MARQDO_LLM_MODEL",
|
||||
"MARQDO_LLM_BASE_URL",
|
||||
"OPENAI_MODEL",
|
||||
@@ -712,6 +721,8 @@ fn apply_run_selection_env(cmd: &mut Command) {
|
||||
cmd.env(key, v);
|
||||
}
|
||||
}
|
||||
// Do not forward process-global MARQDO_CANCEL into children — request cancel
|
||||
// must use MARQDO_CANCEL_TOKEN so leases stay isolated.
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -545,6 +545,20 @@ impl Interpreter {
|
||||
])
|
||||
}
|
||||
|
||||
/// Pin `module` as site and call `lib.member` (isolated worker / CLI `--call-lib-path`).
|
||||
pub fn run_site_lib_path(
|
||||
&mut self,
|
||||
module: &Module,
|
||||
path: &str,
|
||||
args: Option<&Value>,
|
||||
) -> std::result::Result<Value, String> {
|
||||
let prev = self.site_module;
|
||||
self.site_module = Some(module as *const Module);
|
||||
let out = self.call_site_lib_path(path, args);
|
||||
self.site_module = prev;
|
||||
out
|
||||
}
|
||||
|
||||
/// Resolve `lib.member` on the site (entry) module — used by ABI `call_lib_path`.
|
||||
pub(crate) fn call_site_lib_path(
|
||||
&mut self,
|
||||
|
||||
@@ -25,19 +25,29 @@ pub fn compile(opts: KnowledgeOptions) -> Result<KnowledgeGraph> {
|
||||
} else {
|
||||
opts.path.clone()
|
||||
};
|
||||
let t0 = std::time::Instant::now();
|
||||
let semantic = crate::sema::compile_project(&crate::sema::CompileOptions {
|
||||
project_root: semantic_root,
|
||||
entry: opts.path.is_file().then(|| opts.path.clone()),
|
||||
lock_mode: crate::sema::LockMode::Off,
|
||||
})?;
|
||||
let sema_ms = t0.elapsed().as_millis();
|
||||
let t1 = std::time::Instant::now();
|
||||
crate::sema::write_semantic_projections(&opts.out_dir, &semantic)?;
|
||||
let sema_write_ms = t1.elapsed().as_millis();
|
||||
let extract_opts = ExtractOptions {
|
||||
path: opts.path.clone(),
|
||||
out_dir: opts.out_dir.clone(),
|
||||
};
|
||||
let t2 = std::time::Instant::now();
|
||||
let graph = extract_graph(&extract_opts)?;
|
||||
let extract_ms = t2.elapsed().as_millis();
|
||||
let t3 = std::time::Instant::now();
|
||||
write_projections(&opts.out_dir, &graph)?;
|
||||
let retrieve_write_ms = t3.elapsed().as_millis();
|
||||
let t4 = std::time::Instant::now();
|
||||
write_publish_manifest(&opts.out_dir, &semantic, &graph)?;
|
||||
let manifest_ms = t4.elapsed().as_millis();
|
||||
eprintln!(
|
||||
"marqdo knowledge: {} module(s), {} symbol(s), {} capability(ies), {} knowledge → {} (semantic graph/; retrieval ekc/)",
|
||||
graph.modules.len(),
|
||||
@@ -46,6 +56,10 @@ pub fn compile(opts: KnowledgeOptions) -> Result<KnowledgeGraph> {
|
||||
graph.knowledge.len(),
|
||||
opts.out_dir.display()
|
||||
);
|
||||
eprintln!(
|
||||
"marqdo knowledge timing_ms: sema={sema_ms} sema_write={sema_write_ms} extract={extract_ms} retrieve_write={retrieve_write_ms} manifest={manifest_ms} total={}",
|
||||
t0.elapsed().as_millis()
|
||||
);
|
||||
Ok(graph)
|
||||
}
|
||||
|
||||
|
||||
+51
-1
@@ -37,6 +37,7 @@ pub mod lex;
|
||||
pub mod linalg_ops;
|
||||
pub mod load;
|
||||
pub mod mlsp;
|
||||
pub mod runtime;
|
||||
pub mod workbench;
|
||||
pub mod parse;
|
||||
pub mod project;
|
||||
@@ -112,6 +113,10 @@ pub struct RunOptions {
|
||||
pub binds: Vec<(String, String)>,
|
||||
/// Attach CoW session for `ext/ai/sandbox` nested runs.
|
||||
pub sandbox_session: Option<String>,
|
||||
/// Isolated worker: call `lib.member` on the site entry instead of `# main`.
|
||||
pub call_lib_path: Option<String>,
|
||||
/// JSON object of named args for [`Self::call_lib_path`] (file path or inline).
|
||||
pub args_json: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl Default for RunOptions {
|
||||
@@ -135,6 +140,8 @@ impl Default for RunOptions {
|
||||
emit_result: None,
|
||||
binds: Vec::new(),
|
||||
sandbox_session: None,
|
||||
call_lib_path: None,
|
||||
args_json: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -229,7 +236,11 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: trace-eval ({path_label}) ===");
|
||||
}
|
||||
let value = interp.run_module(&module)?;
|
||||
let value = if let Some(lib_path) = &opts.call_lib_path {
|
||||
run_call_lib_path(&mut interp, &module, lib_path, opts)?
|
||||
} else {
|
||||
interp.run_module(&module)?
|
||||
};
|
||||
if opts.trace_eval {
|
||||
eprintln!("=== marqdo: end trace-eval ===");
|
||||
}
|
||||
@@ -275,6 +286,45 @@ pub fn run_file(path: &Path, opts: &RunOptions) -> Result<i32> {
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
/// Worker mode: resolve `lib.member` on the loaded site module (imports already wired).
|
||||
fn run_call_lib_path(
|
||||
interp: &mut Interpreter,
|
||||
module: &crate::ast::Module,
|
||||
lib_path: &str,
|
||||
opts: &RunOptions,
|
||||
) -> Result<crate::value::Value> {
|
||||
let args_val = load_args_json(opts)?;
|
||||
// Keep site_module pinned for the duration of the lib call (plugins may re-enter).
|
||||
let value = interp
|
||||
.run_site_lib_path(module, lib_path, args_val.as_ref())
|
||||
.map_err(|e| anyhow::anyhow!(e))?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn load_args_json(opts: &RunOptions) -> Result<Option<crate::value::Value>> {
|
||||
let Some(path) = &opts.args_json else {
|
||||
return Ok(None);
|
||||
};
|
||||
let text = if path.as_os_str() == "-" {
|
||||
use std::io::Read;
|
||||
let mut buf = String::new();
|
||||
std::io::stdin()
|
||||
.read_to_string(&mut buf)
|
||||
.map_err(|e| anyhow::anyhow!("args-json stdin: {e}"))?;
|
||||
buf
|
||||
} else {
|
||||
std::fs::read_to_string(path)
|
||||
.map_err(|e| anyhow::anyhow!("args-json {}: {e}", path.display()))?
|
||||
};
|
||||
if text.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let json: serde_json::Value =
|
||||
serde_json::from_str(&text).map_err(|e| anyhow::anyhow!("args-json parse: {e}"))?;
|
||||
let v = crate::host::json::json_to_value(&json).map_err(|e| anyhow::anyhow!(e))?;
|
||||
Ok(Some(v))
|
||||
}
|
||||
|
||||
fn emit_result_file(opts: &RunOptions, value: &crate::value::Value) -> Result<()> {
|
||||
let Some(path) = &opts.emit_result else {
|
||||
return Ok(());
|
||||
|
||||
+14
@@ -120,6 +120,14 @@ enum Commands {
|
||||
#[arg(long = "fs-root", value_name = "DIR")]
|
||||
fs_root: Option<PathBuf>,
|
||||
|
||||
/// Isolated worker: call `lib.member` on the site entry instead of `# main`.
|
||||
#[arg(long = "call-lib-path", value_name = "LIB.MEMBER")]
|
||||
call_lib_path: Option<String>,
|
||||
|
||||
/// Named args JSON for `--call-lib-path` (file path, or `-` for stdin).
|
||||
#[arg(long = "args-json", value_name = "FILE")]
|
||||
args_json: Option<PathBuf>,
|
||||
|
||||
/// Emit diagnostics as JSON on stderr (machine-readable; AI/MLSP 面).
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
@@ -688,6 +696,8 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
emit_result,
|
||||
binds,
|
||||
fs_root,
|
||||
call_lib_path,
|
||||
args_json,
|
||||
json: _,
|
||||
legacy_markup,
|
||||
} => {
|
||||
@@ -708,6 +718,8 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
emit_result: emit_result.clone(),
|
||||
binds: bind_pairs.clone(),
|
||||
fs_root: fs_root.clone(),
|
||||
call_lib_path: call_lib_path.clone(),
|
||||
args_json: args_json.clone(),
|
||||
..RunOptions::dump_all()
|
||||
}
|
||||
} else {
|
||||
@@ -723,6 +735,8 @@ fn try_main(cli: Cli) -> Result<i32> {
|
||||
emit_result,
|
||||
binds: bind_pairs,
|
||||
fs_root,
|
||||
call_lib_path,
|
||||
args_json,
|
||||
..RunOptions::default()
|
||||
}
|
||||
};
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
//! Task control plane: cancel without interpreter lock (M-R3).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::runtime::protocol::RuntimeEventV2;
|
||||
use crate::runtime::scheduler::{AdmissionClass, ScheduleError, Scheduler};
|
||||
use crate::runtime::task_store::{StoreError, TaskRecord, TaskState, TaskStore};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ControlError {
|
||||
Store(StoreError),
|
||||
Schedule(ScheduleError),
|
||||
Forbidden,
|
||||
}
|
||||
|
||||
impl From<StoreError> for ControlError {
|
||||
fn from(e: StoreError) -> Self {
|
||||
Self::Store(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ScheduleError> for ControlError {
|
||||
fn from(e: ScheduleError) -> Self {
|
||||
Self::Schedule(e)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ControlError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Store(e) => write!(f, "{e}"),
|
||||
Self::Schedule(e) => write!(f, "{e}"),
|
||||
Self::Forbidden => write!(f, "forbidden"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ControlService {
|
||||
pub store: Arc<TaskStore>,
|
||||
pub scheduler: Arc<Scheduler>,
|
||||
/// Per-lease cancel token directory (token files, not process-global env).
|
||||
cancel_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl ControlService {
|
||||
pub fn new(store: Arc<TaskStore>, scheduler: Arc<Scheduler>, cancel_dir: impl AsRef<Path>) -> Self {
|
||||
let cancel_dir = cancel_dir.as_ref().to_path_buf();
|
||||
let _ = std::fs::create_dir_all(&cancel_dir);
|
||||
Self {
|
||||
store,
|
||||
scheduler,
|
||||
cancel_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn admit(
|
||||
&self,
|
||||
task_id: &str,
|
||||
run_id: &str,
|
||||
workspace_id: &str,
|
||||
session_id: Option<String>,
|
||||
idempotency_key: &str,
|
||||
payload: &Value,
|
||||
class: AdmissionClass,
|
||||
) -> Result<(TaskRecord, usize), ControlError> {
|
||||
let rec = self.store.admit(
|
||||
task_id,
|
||||
run_id,
|
||||
workspace_id,
|
||||
session_id,
|
||||
idempotency_key,
|
||||
payload,
|
||||
)?;
|
||||
let depth = self.scheduler.enqueue(&rec, class)?;
|
||||
let queued = self.store.cas_state(
|
||||
&rec.task_id,
|
||||
rec.revision,
|
||||
TaskState::Queued,
|
||||
|_| {},
|
||||
)?;
|
||||
Ok((queued, depth))
|
||||
}
|
||||
|
||||
/// Cancel path never enters the Marqdo interpreter lock.
|
||||
pub fn cancel(&self, task_id: &str) -> Result<TaskRecord, ControlError> {
|
||||
let rec = self.store.request_cancel(task_id)?;
|
||||
let tok = self.cancel_token_path(task_id);
|
||||
let _ = std::fs::write(&tok, b"cancelled");
|
||||
let _ = self.store.append_event(
|
||||
task_id,
|
||||
&rec.run_id,
|
||||
&rec.attempt_id,
|
||||
"run.cancel_requested",
|
||||
serde_json::json!({"revision": rec.revision}),
|
||||
);
|
||||
Ok(rec)
|
||||
}
|
||||
|
||||
pub fn cancel_token_path(&self, task_id: &str) -> PathBuf {
|
||||
self.cancel_dir.join(format!("{task_id}.tok"))
|
||||
}
|
||||
|
||||
pub fn mark_cancelled(&self, task_id: &str, expected_revision: u64) -> Result<TaskRecord, ControlError> {
|
||||
Ok(self.store.cas_state(
|
||||
task_id,
|
||||
expected_revision,
|
||||
TaskState::Cancelled,
|
||||
|_| {},
|
||||
)?)
|
||||
}
|
||||
|
||||
pub fn complete(
|
||||
&self,
|
||||
task_id: &str,
|
||||
expected_revision: u64,
|
||||
result: Value,
|
||||
) -> Result<TaskRecord, ControlError> {
|
||||
match self.store.cas_state(task_id, expected_revision, TaskState::Succeeded, |r| {
|
||||
r.result = Some(result.clone());
|
||||
}) {
|
||||
Ok(rec) => Ok(rec),
|
||||
Err(StoreError::AlreadyTerminal(state)) => {
|
||||
// Late result after cancel: append evidence only.
|
||||
let rec = self.store.get(task_id)?;
|
||||
let _ = self.store.append_event(
|
||||
task_id,
|
||||
&rec.run_id,
|
||||
&rec.attempt_id,
|
||||
"run.late_result",
|
||||
serde_json::json!({"ignored_terminal": format!("{state:?}"), "result": result}),
|
||||
);
|
||||
Err(ControlError::Store(StoreError::AlreadyTerminal(state)))
|
||||
}
|
||||
Err(e) => Err(ControlError::Store(e)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn events_since(
|
||||
&self,
|
||||
task_id: &str,
|
||||
after_seq: u64,
|
||||
) -> Result<Vec<RuntimeEventV2>, ControlError> {
|
||||
Ok(self.store.events_after(task_id, after_seq)?)
|
||||
}
|
||||
|
||||
/// Collaboration grace + force-kill budget from the design (§6).
|
||||
pub fn cancel_deadlines() -> (Duration, Duration) {
|
||||
(Duration::from_secs(2), Duration::from_secs(3))
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience wrapper used by HTTP/control adapters.
|
||||
pub fn cancel_task(svc: &ControlService, task_id: &str) -> Result<TaskRecord, ControlError> {
|
||||
svc.cancel(task_id)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::scheduler::SchedulerConfig;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn cancel_writes_token_not_interpreter() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-ctrl-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let store = Arc::new(TaskStore::memory());
|
||||
let sched = Arc::new(Scheduler::new(SchedulerConfig::default()));
|
||||
let ctl = ControlService::new(store, sched, &dir);
|
||||
let (t, _) = ctl
|
||||
.admit("t1", "r1", "ws", None, "k", &json!({}), AdmissionClass::Execute)
|
||||
.unwrap();
|
||||
let c = ctl.cancel(&t.task_id).unwrap();
|
||||
assert_eq!(c.state, TaskState::CancelRequested);
|
||||
let body = std::fs::read_to_string(ctl.cancel_token_path(&t.task_id)).unwrap();
|
||||
assert_eq!(body, "cancelled");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn late_complete_after_cancel_is_evidence_only() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-ctrl2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let store = Arc::new(TaskStore::memory());
|
||||
let sched = Arc::new(Scheduler::new(SchedulerConfig::default()));
|
||||
let ctl = ControlService::new(Arc::clone(&store), sched, &dir);
|
||||
let (t, _) = ctl
|
||||
.admit("t1", "r1", "ws", None, "k", &json!({}), AdmissionClass::Execute)
|
||||
.unwrap();
|
||||
let c = ctl.cancel(&t.task_id).unwrap();
|
||||
ctl.mark_cancelled(&t.task_id, c.revision).unwrap();
|
||||
let err = ctl.complete(&t.task_id, c.revision + 1, json!("late")).unwrap_err();
|
||||
assert!(matches!(err, ControlError::Store(StoreError::AlreadyTerminal(_))));
|
||||
let evs = store.events_after(&t.task_id, 0).unwrap();
|
||||
assert!(evs.iter().any(|e| e.event_type == "run.late_result"));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
//! Process-global control plane via `host_query("runtime", …)` — no INVOKE_LOCK.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::runtime::control::ControlService;
|
||||
use crate::runtime::protocol::{
|
||||
EntryRef, InvokeContext, InvokeRequestV2, LeaseRef, PROTOCOL_VERSION,
|
||||
};
|
||||
use crate::runtime::scheduler::{AdmissionClass, Scheduler, SchedulerConfig};
|
||||
use crate::runtime::supervisor::{Supervisor, SupervisorConfig};
|
||||
use crate::runtime::task_store::{TaskState, TaskStore};
|
||||
|
||||
struct RuntimeHost {
|
||||
control: ControlService,
|
||||
supervisor: Arc<Supervisor>,
|
||||
/// task_id → lease_id
|
||||
leases: Mutex<std::collections::HashMap<String, String>>,
|
||||
base: PathBuf,
|
||||
}
|
||||
|
||||
fn runtime_dir() -> PathBuf {
|
||||
std::env::var_os("MARQDO_RUNTIME_DIR")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| std::env::temp_dir().join("marqdo-runtime"))
|
||||
}
|
||||
|
||||
fn marqdo_bin() -> PathBuf {
|
||||
std::env::var_os("MARQDO_BIN")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|| std::env::current_exe().unwrap_or_else(|_| PathBuf::from("marqdo")))
|
||||
}
|
||||
|
||||
fn ensure_host() -> &'static RuntimeHost {
|
||||
static H: OnceLock<RuntimeHost> = OnceLock::new();
|
||||
static JANITOR: OnceLock<()> = OnceLock::new();
|
||||
let host = H.get_or_init(|| {
|
||||
let base = runtime_dir();
|
||||
let _ = std::fs::create_dir_all(&base);
|
||||
let store = match TaskStore::with_persist(base.join("store")) {
|
||||
Ok(s) => Arc::new(s),
|
||||
Err(_) => Arc::new(TaskStore::memory()),
|
||||
};
|
||||
let scheduler = Arc::new(Scheduler::new(SchedulerConfig::default()));
|
||||
let control = ControlService::new(
|
||||
Arc::clone(&store),
|
||||
Arc::clone(&scheduler),
|
||||
base.join("cancel"),
|
||||
);
|
||||
let supervisor = Arc::new(Supervisor::new(
|
||||
SupervisorConfig::default(),
|
||||
base.join("stage"),
|
||||
marqdo_bin(),
|
||||
base.join("cancel"),
|
||||
base.join("events"),
|
||||
));
|
||||
let _ = supervisor.warm();
|
||||
RuntimeHost {
|
||||
control,
|
||||
supervisor,
|
||||
leases: Mutex::new(std::collections::HashMap::new()),
|
||||
base,
|
||||
}
|
||||
});
|
||||
JANITOR.get_or_init(|| {
|
||||
let sup = Arc::clone(&host.supervisor);
|
||||
let _ = thread::Builder::new()
|
||||
.name("mq-runtime-janitor".into())
|
||||
.spawn(move || loop {
|
||||
thread::sleep(Duration::from_millis(500));
|
||||
let _ = sup.janitor_tick();
|
||||
});
|
||||
});
|
||||
host
|
||||
}
|
||||
|
||||
/// Dispatch `host_query("runtime", {op, ...})`. Never blocks on INVOKE_LOCK.
|
||||
pub fn handle(args: &Value) -> Result<Value, String> {
|
||||
let op = args
|
||||
.get("op")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or_else(|| "runtime requires op".to_string())?;
|
||||
let host = ensure_host();
|
||||
let ctl = &host.control;
|
||||
match op {
|
||||
"ping" | "capabilities" => Ok(json!({
|
||||
"ok": true,
|
||||
"protocol_version": PROTOCOL_VERSION,
|
||||
"features": {
|
||||
"runtime.task_control_v2": 1,
|
||||
"runtime.event_replay": 1,
|
||||
"runtime.isolated_execution": 1,
|
||||
},
|
||||
"runtime_dir": host.base.to_string_lossy(),
|
||||
})),
|
||||
"admit" => {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
let run_id = args
|
||||
.get("run_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(task_id);
|
||||
let workspace_id = args
|
||||
.get("workspace_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("default");
|
||||
let session_id = args
|
||||
.get("session_id")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string());
|
||||
let idem = args
|
||||
.get("idempotency_key")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or(task_id);
|
||||
let class = AdmissionClass::parse(
|
||||
args.get("class").and_then(|v| v.as_str()).unwrap_or("execute"),
|
||||
);
|
||||
let payload = args.get("payload").cloned().unwrap_or(json!({}));
|
||||
let (rec, depth) = ctl
|
||||
.admit(
|
||||
task_id,
|
||||
run_id,
|
||||
workspace_id,
|
||||
session_id,
|
||||
idem,
|
||||
&payload,
|
||||
class,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"task": task_json(&rec),
|
||||
"queue_depth": depth,
|
||||
"cancel_token": ctl.cancel_token_path(&rec.task_id).to_string_lossy(),
|
||||
"event_path": host.supervisor.event_path(&rec.task_id).to_string_lossy(),
|
||||
}))
|
||||
}
|
||||
"dispatch" => dispatch_op(host, args),
|
||||
"cancel" => {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
match ctl.cancel(task_id) {
|
||||
Ok(rec) => {
|
||||
if let Some(lease) = host.leases.lock().unwrap().get(task_id) {
|
||||
let _ = host.supervisor.signal_cancel(lease, task_id);
|
||||
} else {
|
||||
let _ = std::fs::write(ctl.cancel_token_path(task_id), b"cancelled");
|
||||
}
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"task": task_json(&rec),
|
||||
"cancel_token": ctl.cancel_token_path(task_id).to_string_lossy(),
|
||||
}))
|
||||
}
|
||||
Err(crate::runtime::control::ControlError::Store(
|
||||
crate::runtime::task_store::StoreError::NotFound,
|
||||
)) => Ok(json!({"ok": false, "error": "not_found", "status": 404})),
|
||||
Err(crate::runtime::control::ControlError::Store(
|
||||
crate::runtime::task_store::StoreError::AlreadyTerminal(s),
|
||||
)) => Ok(json!({
|
||||
"ok": true,
|
||||
"already_terminal": true,
|
||||
"state": format!("{s:?}").to_ascii_lowercase(),
|
||||
})),
|
||||
Err(e) => Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
"get" => {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
match ctl.store.get(task_id) {
|
||||
Ok(rec) => {
|
||||
let mut out = json!({"ok": true, "task": task_json(&rec)});
|
||||
if let Some(lease) = host.leases.lock().unwrap().get(task_id).cloned() {
|
||||
out["lease_id"] = json!(lease);
|
||||
if let Some(p) = host.supervisor.emit_result_path(&lease) {
|
||||
out["emit_result"] = json!(p.to_string_lossy());
|
||||
}
|
||||
if let Ok(Some(code)) = host.supervisor.try_reap(&lease) {
|
||||
out["exit_code"] = json!(code);
|
||||
host.control
|
||||
.scheduler
|
||||
.release_slot(AdmissionClass::Execute);
|
||||
let _ = ctl.store.cas_state(
|
||||
task_id,
|
||||
rec.revision,
|
||||
if code == 0 {
|
||||
TaskState::Succeeded
|
||||
} else {
|
||||
TaskState::Failed
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
}
|
||||
out["event_path"] =
|
||||
json!(host.supervisor.event_path(task_id).to_string_lossy());
|
||||
Ok(out)
|
||||
}
|
||||
Err(_) => Ok(json!({"ok": false, "error": "not_found", "status": 404})),
|
||||
}
|
||||
}
|
||||
"events" => {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
let after = args.get("after_seq").and_then(|v| v.as_u64()).unwrap_or(0);
|
||||
let path = host.supervisor.event_path(task_id);
|
||||
if path.is_file() {
|
||||
let lines = read_ndjson_lines(&path, after)?;
|
||||
return Ok(json!({
|
||||
"ok": true,
|
||||
"events": lines,
|
||||
"after_seq": after,
|
||||
"source": "worker_ndjson",
|
||||
"event_path": path.to_string_lossy(),
|
||||
}));
|
||||
}
|
||||
match ctl.events_since(task_id, after) {
|
||||
Ok(evs) => Ok(json!({
|
||||
"ok": true,
|
||||
"events": evs,
|
||||
"after_seq": after,
|
||||
"source": "task_store",
|
||||
})),
|
||||
Err(_) => Ok(json!({"ok": false, "error": "not_found", "status": 404})),
|
||||
}
|
||||
}
|
||||
"append_event" => {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
let rec = ctl.store.get(task_id).map_err(|_| "not_found".to_string())?;
|
||||
let et = args
|
||||
.get("type")
|
||||
.and_then(|v| v.as_str())
|
||||
.unwrap_or("message.delta");
|
||||
let payload = args.get("payload").cloned().unwrap_or(json!({}));
|
||||
let ev = ctl
|
||||
.store
|
||||
.append_event(task_id, &rec.run_id, &rec.attempt_id, et, payload)
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(json!({"ok": true, "event": ev}))
|
||||
}
|
||||
other => Err(format!("runtime.unknown_op:{other}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn dispatch_op(host: &RuntimeHost, args: &Value) -> Result<Value, String> {
|
||||
let task_id = req_str(args, "task_id")?;
|
||||
let rec = host
|
||||
.control
|
||||
.store
|
||||
.get(task_id)
|
||||
.map_err(|_| "not_found".to_string())?;
|
||||
let entry = args.get("entry").ok_or("dispatch.entry_required")?;
|
||||
let module = entry
|
||||
.get("module")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("dispatch.module_required")?;
|
||||
let function = entry
|
||||
.get("function")
|
||||
.and_then(|v| v.as_str())
|
||||
.ok_or("dispatch.function_required")?;
|
||||
let fs_root = args
|
||||
.get("fs_root")
|
||||
.and_then(|v| v.as_str())
|
||||
.or_else(|| {
|
||||
args.get("context")
|
||||
.and_then(|c| c.get("fs_root"))
|
||||
.and_then(|v| v.as_str())
|
||||
})
|
||||
.ok_or("dispatch.fs_root_required")?;
|
||||
let args_ref = args
|
||||
.get("args_ref")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|s| s.to_string())
|
||||
.or_else(|| {
|
||||
args.get("args_json")
|
||||
.and_then(|v| v.as_str())
|
||||
.map(|p| format!("file:{p}"))
|
||||
});
|
||||
|
||||
let tok = host.control.cancel_token_path(task_id);
|
||||
if !tok.exists() {
|
||||
std::fs::write(&tok, b"").map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
let epoch = host.control.store.next_lease_epoch();
|
||||
let req = InvokeRequestV2 {
|
||||
schema: "InvokeRequestV2".into(),
|
||||
schema_version: PROTOCOL_VERSION,
|
||||
task_id: task_id.into(),
|
||||
run_id: rec.run_id.clone(),
|
||||
attempt_id: rec.attempt_id.clone(),
|
||||
lease: LeaseRef {
|
||||
id: format!("lease_{task_id}"),
|
||||
epoch,
|
||||
},
|
||||
entry: EntryRef {
|
||||
module: module.into(),
|
||||
function: function.into(),
|
||||
},
|
||||
args_ref,
|
||||
context: InvokeContext {
|
||||
workspace_id: rec.workspace_id.clone(),
|
||||
snapshot_id: None,
|
||||
selection_ref: None,
|
||||
capabilities_ref: None,
|
||||
deadline_at: "2099-01-01T00:00:00Z".into(),
|
||||
fs_root: Some(fs_root.into()),
|
||||
},
|
||||
};
|
||||
|
||||
if host
|
||||
.control
|
||||
.scheduler
|
||||
.try_acquire_slot(AdmissionClass::Execute)
|
||||
.is_err()
|
||||
{
|
||||
return Ok(json!({
|
||||
"ok": false,
|
||||
"error": "no_slot",
|
||||
"status": 429,
|
||||
"Retry-After": 2,
|
||||
}));
|
||||
}
|
||||
|
||||
match host.supervisor.dispatch(req) {
|
||||
Ok(lease_id) => {
|
||||
host.leases
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(task_id.to_string(), lease_id.clone());
|
||||
let _ = host.control.store.cas_state(
|
||||
task_id,
|
||||
rec.revision,
|
||||
TaskState::Running,
|
||||
|r| {
|
||||
r.lease_id = Some(lease_id.clone());
|
||||
r.lease_epoch = Some(epoch);
|
||||
},
|
||||
);
|
||||
Ok(json!({
|
||||
"ok": true,
|
||||
"lease_id": lease_id,
|
||||
"task_id": task_id,
|
||||
"cancel_token": tok.to_string_lossy(),
|
||||
"event_path": host.supervisor.event_path(task_id).to_string_lossy(),
|
||||
"emit_result": host.supervisor.emit_result_path(&lease_id)
|
||||
.map(|p| p.to_string_lossy().to_string()),
|
||||
}))
|
||||
}
|
||||
Err(e) => {
|
||||
host.control
|
||||
.scheduler
|
||||
.release_slot(AdmissionClass::Execute);
|
||||
if e.contains("no_slot") {
|
||||
Ok(json!({
|
||||
"ok": false,
|
||||
"error": "no_slot",
|
||||
"status": 429,
|
||||
"Retry-After": 2,
|
||||
}))
|
||||
} else {
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn read_ndjson_lines(path: &Path, after_seq: u64) -> Result<Vec<Value>, String> {
|
||||
let text = std::fs::read_to_string(path).map_err(|e| e.to_string())?;
|
||||
let mut out = Vec::new();
|
||||
let mut seq = 0u64;
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
seq += 1;
|
||||
if seq <= after_seq {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<Value>(line) {
|
||||
Ok(mut v) => {
|
||||
if v.get("seq").is_none() {
|
||||
if let Some(obj) = v.as_object_mut() {
|
||||
obj.insert("seq".into(), json!(seq));
|
||||
}
|
||||
}
|
||||
out.push(v);
|
||||
}
|
||||
Err(_) => out.push(json!({"seq": seq, "raw": line})),
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn req_str<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
|
||||
args.get(key)
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|s| !s.is_empty())
|
||||
.ok_or_else(|| format!("runtime missing `{key}`"))
|
||||
}
|
||||
|
||||
fn task_json(rec: &crate::runtime::task_store::TaskRecord) -> Value {
|
||||
json!({
|
||||
"task_id": rec.task_id,
|
||||
"run_id": rec.run_id,
|
||||
"attempt_id": rec.attempt_id,
|
||||
"workspace_id": rec.workspace_id,
|
||||
"session_id": rec.session_id,
|
||||
"state": state_str(rec.state),
|
||||
"revision": rec.revision,
|
||||
"idempotency_key": rec.idempotency_key,
|
||||
"created_at": rec.created_at,
|
||||
"updated_at": rec.updated_at,
|
||||
"cancel_requested_at": rec.cancel_requested_at,
|
||||
"result": rec.result,
|
||||
"error": rec.error,
|
||||
"lease_id": rec.lease_id,
|
||||
})
|
||||
}
|
||||
|
||||
fn state_str(s: TaskState) -> &'static str {
|
||||
match s {
|
||||
TaskState::Accepted => "accepted",
|
||||
TaskState::Queued => "queued",
|
||||
TaskState::Running => "running",
|
||||
TaskState::Finalizing => "finalizing",
|
||||
TaskState::Succeeded => "succeeded",
|
||||
TaskState::Failed => "failed",
|
||||
TaskState::CancelRequested => "cancel_requested",
|
||||
TaskState::Cancelled => "cancelled",
|
||||
TaskState::Interrupted => "interrupted",
|
||||
TaskState::NeedsReconciliation => "needs_reconciliation",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn admit_cancel_without_host_context() {
|
||||
let id = format!("rt-{}", std::process::id());
|
||||
let adm = handle(&json!({
|
||||
"op": "admit",
|
||||
"task_id": id,
|
||||
"idempotency_key": id,
|
||||
"payload": {"n": 1}
|
||||
}))
|
||||
.unwrap();
|
||||
assert_eq!(adm["ok"], true);
|
||||
let can = handle(&json!({"op": "cancel", "task_id": id})).unwrap();
|
||||
assert_eq!(can["ok"], true);
|
||||
assert_eq!(can["task"]["state"], "cancel_requested");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Worker lease identity and process lifecycle states (M-R2).
|
||||
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct LeaseId(pub String);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WorkerState {
|
||||
Starting,
|
||||
Ready,
|
||||
Leased,
|
||||
Running,
|
||||
Draining,
|
||||
Unhealthy,
|
||||
Terminating,
|
||||
Exited,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Lease {
|
||||
pub id: LeaseId,
|
||||
pub epoch: u64,
|
||||
pub task_id: String,
|
||||
pub run_id: String,
|
||||
pub attempt_id: String,
|
||||
pub deadline: SystemTime,
|
||||
pub state: WorkerState,
|
||||
}
|
||||
|
||||
impl Lease {
|
||||
pub fn new(
|
||||
id: impl Into<String>,
|
||||
epoch: u64,
|
||||
task_id: impl Into<String>,
|
||||
run_id: impl Into<String>,
|
||||
attempt_id: impl Into<String>,
|
||||
ttl: Duration,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: LeaseId(id.into()),
|
||||
epoch,
|
||||
task_id: task_id.into(),
|
||||
run_id: run_id.into(),
|
||||
attempt_id: attempt_id.into(),
|
||||
deadline: SystemTime::now() + ttl,
|
||||
state: WorkerState::Leased,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn expired(&self) -> bool {
|
||||
SystemTime::now() > self.deadline
|
||||
}
|
||||
|
||||
pub fn matches(&self, lease_id: &str, epoch: u64) -> bool {
|
||||
self.id.0 == lease_id && self.epoch == epoch
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Isolated web runtime (M-R2–M-R4): supervisor, worker IPC, leases, task
|
||||
//! admission/control, and persistent event log.
|
||||
//!
|
||||
//! Design: `doc/design/isolated-web-runtime-development-2026-10-26.md`.
|
||||
//! Until capability probes report version ≥1, callers must treat this as opt-in.
|
||||
|
||||
pub mod control;
|
||||
pub mod host_api;
|
||||
pub mod lease;
|
||||
pub mod protocol;
|
||||
pub mod publish;
|
||||
pub mod scheduler;
|
||||
pub mod supervisor;
|
||||
pub mod task_store;
|
||||
pub mod worker;
|
||||
|
||||
pub use control::{cancel_task, ControlError, ControlService};
|
||||
pub use lease::{Lease, LeaseId, WorkerState};
|
||||
pub use protocol::{
|
||||
InvokeRequestV2, RuntimeEventV2, CONTROL_FRAME_MAX_BYTES, PROTOCOL_VERSION,
|
||||
};
|
||||
pub use publish::{PublishJournal, PublishOutcome, PublishPhase};
|
||||
pub use scheduler::{AdmissionClass, Scheduler, SchedulerConfig};
|
||||
pub use supervisor::{Supervisor, SupervisorConfig};
|
||||
pub use task_store::{TaskRecord, TaskState, TaskStore};
|
||||
pub use worker::{WorkerHandle, WorkerPool};
|
||||
@@ -0,0 +1,158 @@
|
||||
//! Length-prefixed JSON control frames + event channel types (M-R2 / M-R4).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
pub const PROTOCOL_VERSION: u32 = 2;
|
||||
pub const CONTROL_FRAME_MAX_BYTES: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct InvokeRequestV2 {
|
||||
pub schema: String,
|
||||
pub schema_version: u32,
|
||||
pub task_id: String,
|
||||
pub run_id: String,
|
||||
pub attempt_id: String,
|
||||
pub lease: LeaseRef,
|
||||
pub entry: EntryRef,
|
||||
#[serde(default)]
|
||||
pub args_ref: Option<String>,
|
||||
pub context: InvokeContext,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct LeaseRef {
|
||||
pub id: String,
|
||||
pub epoch: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct EntryRef {
|
||||
pub module: String,
|
||||
pub function: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct InvokeContext {
|
||||
pub workspace_id: String,
|
||||
#[serde(default)]
|
||||
pub snapshot_id: Option<String>,
|
||||
#[serde(default)]
|
||||
pub selection_ref: Option<String>,
|
||||
#[serde(default)]
|
||||
pub capabilities_ref: Option<String>,
|
||||
pub deadline_at: String,
|
||||
/// Absolute site filesystem root (`--fs-root` for the worker).
|
||||
#[serde(default)]
|
||||
pub fs_root: Option<String>,
|
||||
}
|
||||
|
||||
impl InvokeRequestV2 {
|
||||
pub fn validate(&self) -> Result<(), String> {
|
||||
if self.schema != "InvokeRequestV2" {
|
||||
return Err(format!("protocol.schema: {}", self.schema));
|
||||
}
|
||||
if self.schema_version != PROTOCOL_VERSION {
|
||||
return Err(format!(
|
||||
"protocol.version: got {} want {PROTOCOL_VERSION}",
|
||||
self.schema_version
|
||||
));
|
||||
}
|
||||
if self.task_id.is_empty() || self.run_id.is_empty() || self.attempt_id.is_empty() {
|
||||
return Err("protocol.ids_required".into());
|
||||
}
|
||||
if self.entry.module.is_empty() || self.entry.function.is_empty() {
|
||||
return Err("protocol.entry_required".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RuntimeEventV2 {
|
||||
pub schema: String,
|
||||
pub schema_version: u32,
|
||||
pub event_id: String,
|
||||
pub seq: u64,
|
||||
pub task_id: String,
|
||||
pub run_id: String,
|
||||
pub attempt_id: String,
|
||||
#[serde(rename = "type")]
|
||||
pub event_type: String,
|
||||
pub payload: Value,
|
||||
}
|
||||
|
||||
impl RuntimeEventV2 {
|
||||
pub fn new(
|
||||
task_id: &str,
|
||||
run_id: &str,
|
||||
attempt_id: &str,
|
||||
seq: u64,
|
||||
event_type: &str,
|
||||
payload: Value,
|
||||
) -> Self {
|
||||
Self {
|
||||
schema: "RuntimeEventV2".into(),
|
||||
schema_version: PROTOCOL_VERSION,
|
||||
event_id: format!("{task_id}:{seq}"),
|
||||
seq,
|
||||
task_id: task_id.into(),
|
||||
run_id: run_id.into(),
|
||||
attempt_id: attempt_id.into(),
|
||||
event_type: event_type.into(),
|
||||
payload,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a control frame: u32 LE length + UTF-8 JSON (≤ CONTROL_FRAME_MAX_BYTES).
|
||||
pub fn encode_frame(value: &Value) -> Result<Vec<u8>, String> {
|
||||
let body = serde_json::to_vec(value).map_err(|e| format!("protocol.encode: {e}"))?;
|
||||
if body.len() > CONTROL_FRAME_MAX_BYTES {
|
||||
return Err("protocol.frame_too_large".into());
|
||||
}
|
||||
let mut out = Vec::with_capacity(4 + body.len());
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Decode one frame from the front of `buf`; returns (value, bytes_consumed).
|
||||
pub fn decode_frame(buf: &[u8]) -> Result<Option<(Value, usize)>, String> {
|
||||
if buf.len() < 4 {
|
||||
return Ok(None);
|
||||
}
|
||||
let len = u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]) as usize;
|
||||
if len > CONTROL_FRAME_MAX_BYTES {
|
||||
return Err("protocol.frame_too_large".into());
|
||||
}
|
||||
if buf.len() < 4 + len {
|
||||
return Ok(None);
|
||||
}
|
||||
let value: Value = serde_json::from_slice(&buf[4..4 + len])
|
||||
.map_err(|e| format!("protocol.decode: {e}"))?;
|
||||
Ok(Some((value, 4 + len)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn frame_round_trip() {
|
||||
let v = json!({"hello": "世界"});
|
||||
let enc = encode_frame(&v).unwrap();
|
||||
let (got, n) = decode_frame(&enc).unwrap().unwrap();
|
||||
assert_eq!(n, enc.len());
|
||||
assert_eq!(got, v);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_frame_waits() {
|
||||
let v = json!({"a": 1});
|
||||
let enc = encode_frame(&v).unwrap();
|
||||
assert!(decode_frame(&enc[..3]).unwrap().is_none());
|
||||
assert!(decode_frame(&enc[..enc.len() - 1]).unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! Publish journal + expected_generation CAS (M-R6).
|
||||
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PublishPhase {
|
||||
Staging,
|
||||
Validated,
|
||||
GenerationRenamed,
|
||||
CurrentSwitched,
|
||||
DbProjected,
|
||||
Aborted,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PublishJournal {
|
||||
pub kb_id: String,
|
||||
pub expected_generation: Option<String>,
|
||||
pub new_generation: String,
|
||||
pub phase: PublishPhase,
|
||||
pub staging_dir: PathBuf,
|
||||
pub generation_dir: PathBuf,
|
||||
pub current_path: PathBuf,
|
||||
pub source_digest: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum PublishOutcome {
|
||||
Published { generation: String },
|
||||
Conflict { current: String, expected: String },
|
||||
Recovered { generation: String },
|
||||
Aborted { reason: String },
|
||||
}
|
||||
|
||||
impl PublishJournal {
|
||||
pub fn begin(
|
||||
out_dir: impl AsRef<Path>,
|
||||
kb_id: impl Into<String>,
|
||||
expected_generation: Option<String>,
|
||||
new_generation: impl Into<String>,
|
||||
source_digest: impl Into<String>,
|
||||
) -> Result<Self, String> {
|
||||
let out_dir = out_dir.as_ref();
|
||||
let new_generation = new_generation.into();
|
||||
let staging_dir = out_dir.join(".publish-staging").join(&new_generation);
|
||||
let generation_dir = out_dir.join("generations").join(&new_generation);
|
||||
let current_path = out_dir.join("CURRENT");
|
||||
fs::create_dir_all(&staging_dir).map_err(|e| e.to_string())?;
|
||||
let j = Self {
|
||||
kb_id: kb_id.into(),
|
||||
expected_generation,
|
||||
new_generation,
|
||||
phase: PublishPhase::Staging,
|
||||
staging_dir,
|
||||
generation_dir,
|
||||
current_path,
|
||||
source_digest: source_digest.into(),
|
||||
};
|
||||
j.write_journal(out_dir)?;
|
||||
Ok(j)
|
||||
}
|
||||
|
||||
fn journal_path(out_dir: &Path) -> PathBuf {
|
||||
out_dir.join("publish_journal.json")
|
||||
}
|
||||
|
||||
fn write_journal(&self, out_dir: &Path) -> Result<(), String> {
|
||||
let path = Self::journal_path(out_dir);
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let body = serde_json::to_vec_pretty(self).map_err(|e| e.to_string())?;
|
||||
fs::write(&tmp, body).map_err(|e| e.to_string())?;
|
||||
// Best-effort fsync via File.
|
||||
let f = fs::OpenOptions::new()
|
||||
.write(true)
|
||||
.open(&tmp)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let _ = f.sync_all();
|
||||
drop(f);
|
||||
fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load(out_dir: impl AsRef<Path>) -> Result<Option<Self>, String> {
|
||||
let path = Self::journal_path(out_dir.as_ref());
|
||||
if !path.is_file() {
|
||||
return Ok(None);
|
||||
}
|
||||
let body = fs::read_to_string(&path).map_err(|e| e.to_string())?;
|
||||
let j: Self = serde_json::from_str(&body).map_err(|e| e.to_string())?;
|
||||
Ok(Some(j))
|
||||
}
|
||||
|
||||
/// CAS: refuse if CURRENT does not match expected_generation.
|
||||
pub fn assert_expected_current(&self) -> Result<String, PublishOutcome> {
|
||||
let current = fs::read_to_string(&self.current_path)
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string();
|
||||
if let Some(exp) = &self.expected_generation {
|
||||
if ¤t != exp {
|
||||
return Err(PublishOutcome::Conflict {
|
||||
current,
|
||||
expected: exp.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
pub fn mark(&mut self, out_dir: &Path, phase: PublishPhase) -> Result<(), String> {
|
||||
self.phase = phase;
|
||||
self.write_journal(out_dir)
|
||||
}
|
||||
|
||||
/// Atomic publish: staging tree already complete → rename into generations → CURRENT.
|
||||
pub fn commit_filesystem(&mut self, out_dir: &Path) -> Result<PublishOutcome, String> {
|
||||
match self.assert_expected_current() {
|
||||
Err(o) => return Ok(o),
|
||||
Ok(_) => {}
|
||||
}
|
||||
self.mark(out_dir, PublishPhase::Validated)?;
|
||||
|
||||
if self.generation_dir.exists() {
|
||||
fs::remove_dir_all(&self.generation_dir).map_err(|e| e.to_string())?;
|
||||
}
|
||||
fs::create_dir_all(self.generation_dir.parent().unwrap()).map_err(|e| e.to_string())?;
|
||||
fs::rename(&self.staging_dir, &self.generation_dir).map_err(|e| e.to_string())?;
|
||||
self.mark(out_dir, PublishPhase::GenerationRenamed)?;
|
||||
|
||||
let tmp = self.current_path.with_extension("tmp");
|
||||
{
|
||||
let mut f = fs::File::create(&tmp).map_err(|e| e.to_string())?;
|
||||
writeln!(f, "{}", self.new_generation).map_err(|e| e.to_string())?;
|
||||
let _ = f.sync_all();
|
||||
}
|
||||
fs::rename(&tmp, &self.current_path).map_err(|e| e.to_string())?;
|
||||
self.mark(out_dir, PublishPhase::CurrentSwitched)?;
|
||||
|
||||
// Clear journal after successful CURRENT switch; DB projection is product-side.
|
||||
let _ = fs::remove_file(Self::journal_path(out_dir));
|
||||
Ok(PublishOutcome::Published {
|
||||
generation: self.new_generation.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Crash recovery: if CURRENT already points at new_generation, treat as done;
|
||||
/// if generation exists but CURRENT old, finish CURRENT switch; else abort staging.
|
||||
pub fn recover(out_dir: impl AsRef<Path>) -> Result<PublishOutcome, String> {
|
||||
let out_dir = out_dir.as_ref();
|
||||
let Some(mut j) = Self::load(out_dir)? else {
|
||||
return Ok(PublishOutcome::Aborted {
|
||||
reason: "no_journal".into(),
|
||||
});
|
||||
};
|
||||
let current = fs::read_to_string(&j.current_path)
|
||||
.unwrap_or_default()
|
||||
.trim()
|
||||
.to_string();
|
||||
if current == j.new_generation {
|
||||
let _ = fs::remove_file(Self::journal_path(out_dir));
|
||||
return Ok(PublishOutcome::Recovered {
|
||||
generation: j.new_generation,
|
||||
});
|
||||
}
|
||||
match j.phase {
|
||||
PublishPhase::GenerationRenamed | PublishPhase::Validated
|
||||
if j.generation_dir.is_dir() =>
|
||||
{
|
||||
let tmp = j.current_path.with_extension("tmp");
|
||||
fs::write(&tmp, format!("{}\n", j.new_generation)).map_err(|e| e.to_string())?;
|
||||
fs::rename(&tmp, &j.current_path).map_err(|e| e.to_string())?;
|
||||
let _ = fs::remove_file(Self::journal_path(out_dir));
|
||||
Ok(PublishOutcome::Recovered {
|
||||
generation: j.new_generation,
|
||||
})
|
||||
}
|
||||
PublishPhase::Staging | PublishPhase::Aborted => {
|
||||
let _ = fs::remove_dir_all(&j.staging_dir);
|
||||
j.mark(out_dir, PublishPhase::Aborted)?;
|
||||
let _ = fs::remove_file(Self::journal_path(out_dir));
|
||||
Ok(PublishOutcome::Aborted {
|
||||
reason: "incomplete_staging".into(),
|
||||
})
|
||||
}
|
||||
other => Ok(PublishOutcome::Aborted {
|
||||
reason: format!("unhandled_phase:{other:?}"),
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable logical document identity independent of generation directory name.
|
||||
pub fn logical_document_id(project_id: &str, relative_path: &str) -> String {
|
||||
let mut h = Sha256::new();
|
||||
h.update(project_id.as_bytes());
|
||||
h.update(b"\0");
|
||||
h.update(relative_path.replace('\\', "/").as_bytes());
|
||||
format!("doc:{:x}", h.finalize())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cas_conflict_and_commit() {
|
||||
let root = std::env::temp_dir().join(format!("mq-pub-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(root.join("generations")).unwrap();
|
||||
fs::write(root.join("CURRENT"), "gen_old\n").unwrap();
|
||||
|
||||
let mut j = PublishJournal::begin(&root, "kb1", Some("gen_old".into()), "gen_new", "digest")
|
||||
.unwrap();
|
||||
fs::write(j.staging_dir.join("manifest.json"), "{}").unwrap();
|
||||
let out = j.commit_filesystem(&root).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
PublishOutcome::Published {
|
||||
generation: "gen_new".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("CURRENT")).unwrap().trim(),
|
||||
"gen_new"
|
||||
);
|
||||
|
||||
let mut j2 =
|
||||
PublishJournal::begin(&root, "kb1", Some("gen_old".into()), "gen_x", "d").unwrap();
|
||||
fs::write(j2.staging_dir.join("x"), "1").unwrap();
|
||||
let conflict = j2.commit_filesystem(&root).unwrap();
|
||||
assert!(matches!(conflict, PublishOutcome::Conflict { .. }));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recover_after_generation_rename() {
|
||||
let root = std::env::temp_dir().join(format!("mq-pub2-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
fs::create_dir_all(root.join("generations/gen_r")).unwrap();
|
||||
fs::write(root.join("CURRENT"), "old\n").unwrap();
|
||||
let mut j =
|
||||
PublishJournal::begin(&root, "kb", Some("old".into()), "gen_r", "d").unwrap();
|
||||
// Simulate crash after generation rename: staging already moved.
|
||||
let _ = fs::remove_dir_all(&j.staging_dir);
|
||||
j.phase = PublishPhase::GenerationRenamed;
|
||||
j.write_journal(&root).unwrap();
|
||||
let out = PublishJournal::recover(&root).unwrap();
|
||||
assert_eq!(
|
||||
out,
|
||||
PublishOutcome::Recovered {
|
||||
generation: "gen_r".into()
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.join("CURRENT")).unwrap().trim(),
|
||||
"gen_r"
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn logical_id_stable_across_generation_paths() {
|
||||
let a = logical_document_id("proj", "docs/a.mq.md");
|
||||
let b = logical_document_id("proj", "docs/a.mq.md");
|
||||
assert_eq!(a, b);
|
||||
assert_ne!(a, logical_document_id("proj", "docs/b.mq.md"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
//! Bounded admission classes and fair queueing (M-R3).
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use crate::runtime::task_store::TaskRecord;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AdmissionClass {
|
||||
Control,
|
||||
Read,
|
||||
Short,
|
||||
Execute,
|
||||
Commit,
|
||||
/// Undeclared endpoints stay on the legacy single-interpreter path.
|
||||
LegacySerial,
|
||||
}
|
||||
|
||||
impl AdmissionClass {
|
||||
pub fn parse(s: &str) -> Self {
|
||||
match s.to_ascii_lowercase().as_str() {
|
||||
"control" => Self::Control,
|
||||
"read" => Self::Read,
|
||||
"short" => Self::Short,
|
||||
"execute" => Self::Execute,
|
||||
"commit" => Self::Commit,
|
||||
_ => Self::LegacySerial,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SchedulerConfig {
|
||||
pub execute_slots: usize,
|
||||
pub short_slots: usize,
|
||||
pub read_slots: usize,
|
||||
pub global_queue_limit: usize,
|
||||
pub workspace_queue_limit: usize,
|
||||
pub session_pending_limit: usize,
|
||||
}
|
||||
|
||||
impl Default for SchedulerConfig {
|
||||
fn default() -> Self {
|
||||
// 4 vCPU / 8 GiB verification machine defaults from the design.
|
||||
Self {
|
||||
execute_slots: 2,
|
||||
short_slots: 1,
|
||||
read_slots: 1,
|
||||
global_queue_limit: 64,
|
||||
workspace_queue_limit: 16,
|
||||
session_pending_limit: 4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ScheduleError {
|
||||
QueueFull,
|
||||
WorkspaceFull,
|
||||
SessionFull,
|
||||
NoSlot,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ScheduleError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::QueueFull => write!(f, "queue_full"),
|
||||
Self::WorkspaceFull => write!(f, "workspace_full"),
|
||||
Self::SessionFull => write!(f, "session_full"),
|
||||
Self::NoSlot => write!(f, "no_slot"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QueueState {
|
||||
global: VecDeque<String>,
|
||||
by_workspace: HashMap<String, VecDeque<String>>,
|
||||
by_session: HashMap<String, usize>,
|
||||
active_execute: usize,
|
||||
active_short: usize,
|
||||
active_read: usize,
|
||||
/// workspace rotation cursor
|
||||
workspace_order: VecDeque<String>,
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
cfg: SchedulerConfig,
|
||||
inner: Mutex<QueueState>,
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
pub fn new(cfg: SchedulerConfig) -> Self {
|
||||
Self {
|
||||
cfg,
|
||||
inner: Mutex::new(QueueState {
|
||||
global: VecDeque::new(),
|
||||
by_workspace: HashMap::new(),
|
||||
by_session: HashMap::new(),
|
||||
active_execute: 0,
|
||||
active_short: 0,
|
||||
active_read: 0,
|
||||
workspace_order: VecDeque::new(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn enqueue(&self, task: &TaskRecord, class: AdmissionClass) -> Result<usize, ScheduleError> {
|
||||
if class == AdmissionClass::Control || class == AdmissionClass::LegacySerial {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
if g.global.len() >= self.cfg.global_queue_limit {
|
||||
return Err(ScheduleError::QueueFull);
|
||||
}
|
||||
let ws_len = g
|
||||
.by_workspace
|
||||
.get(&task.workspace_id)
|
||||
.map(|q| q.len())
|
||||
.unwrap_or(0);
|
||||
if ws_len >= self.cfg.workspace_queue_limit {
|
||||
return Err(ScheduleError::WorkspaceFull);
|
||||
}
|
||||
if let Some(sid) = &task.session_id {
|
||||
let n = g.by_session.entry(sid.clone()).or_insert(0);
|
||||
if *n >= self.cfg.session_pending_limit {
|
||||
return Err(ScheduleError::SessionFull);
|
||||
}
|
||||
*n += 1;
|
||||
}
|
||||
if !g.workspace_order.iter().any(|w| w == &task.workspace_id) {
|
||||
g.workspace_order.push_back(task.workspace_id.clone());
|
||||
}
|
||||
g.by_workspace
|
||||
.entry(task.workspace_id.clone())
|
||||
.or_default()
|
||||
.push_back(task.task_id.clone());
|
||||
g.global.push_back(task.task_id.clone());
|
||||
Ok(g.global.len())
|
||||
}
|
||||
|
||||
pub fn try_acquire_slot(&self, class: AdmissionClass) -> Result<(), ScheduleError> {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
match class {
|
||||
AdmissionClass::Execute => {
|
||||
if g.active_execute >= self.cfg.execute_slots {
|
||||
return Err(ScheduleError::NoSlot);
|
||||
}
|
||||
g.active_execute += 1;
|
||||
}
|
||||
AdmissionClass::Short | AdmissionClass::Commit => {
|
||||
if g.active_short >= self.cfg.short_slots {
|
||||
return Err(ScheduleError::NoSlot);
|
||||
}
|
||||
g.active_short += 1;
|
||||
}
|
||||
AdmissionClass::Read => {
|
||||
if g.active_read >= self.cfg.read_slots {
|
||||
return Err(ScheduleError::NoSlot);
|
||||
}
|
||||
g.active_read += 1;
|
||||
}
|
||||
AdmissionClass::Control | AdmissionClass::LegacySerial => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn release_slot(&self, class: AdmissionClass) {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
match class {
|
||||
AdmissionClass::Execute => {
|
||||
g.active_execute = g.active_execute.saturating_sub(1);
|
||||
}
|
||||
AdmissionClass::Short | AdmissionClass::Commit => {
|
||||
g.active_short = g.active_short.saturating_sub(1);
|
||||
}
|
||||
AdmissionClass::Read => {
|
||||
g.active_read = g.active_read.saturating_sub(1);
|
||||
}
|
||||
AdmissionClass::Control | AdmissionClass::LegacySerial => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fair pop: rotate workspaces, then session FIFO within workspace.
|
||||
pub fn pop_next(&self) -> Option<String> {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
if g.workspace_order.is_empty() {
|
||||
return None;
|
||||
}
|
||||
for _ in 0..g.workspace_order.len() {
|
||||
let ws = g.workspace_order.pop_front()?;
|
||||
if let Some(q) = g.by_workspace.get_mut(&ws) {
|
||||
if let Some(tid) = q.pop_front() {
|
||||
g.workspace_order.push_back(ws);
|
||||
g.global.retain(|id| id != &tid);
|
||||
return Some(tid);
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn queue_depth(&self) -> usize {
|
||||
self.inner.lock().unwrap().global.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::task_store::{TaskRecord, TaskState};
|
||||
|
||||
fn task(id: &str, ws: &str, session: Option<&str>) -> TaskRecord {
|
||||
TaskRecord {
|
||||
task_id: id.into(),
|
||||
run_id: format!("r-{id}"),
|
||||
attempt_id: format!("a-{id}"),
|
||||
workspace_id: ws.into(),
|
||||
session_id: session.map(|s| s.into()),
|
||||
state: TaskState::Queued,
|
||||
revision: 1,
|
||||
idempotency_key: id.into(),
|
||||
payload_hash: "h".into(),
|
||||
lease_id: None,
|
||||
lease_epoch: None,
|
||||
created_at: "0".into(),
|
||||
updated_at: "0".into(),
|
||||
cancel_requested_at: None,
|
||||
result: None,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn workspace_rotation_fairness() {
|
||||
let sched = Scheduler::new(SchedulerConfig::default());
|
||||
sched
|
||||
.enqueue(&task("a1", "wsA", None), AdmissionClass::Execute)
|
||||
.unwrap();
|
||||
sched
|
||||
.enqueue(&task("a2", "wsA", None), AdmissionClass::Execute)
|
||||
.unwrap();
|
||||
sched
|
||||
.enqueue(&task("b1", "wsB", None), AdmissionClass::Execute)
|
||||
.unwrap();
|
||||
assert_eq!(sched.pop_next().as_deref(), Some("a1"));
|
||||
assert_eq!(sched.pop_next().as_deref(), Some("b1"));
|
||||
assert_eq!(sched.pop_next().as_deref(), Some("a2"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Supervisor: lease workers, enforce deadlines, reap orphans (M-R2).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use crate::runtime::lease::{Lease, WorkerState};
|
||||
use crate::runtime::protocol::InvokeRequestV2;
|
||||
use crate::runtime::worker::{WorkerHandle, WorkerPool};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SupervisorConfig {
|
||||
pub execute_slots: usize,
|
||||
pub worker_ttl: Duration,
|
||||
pub cancel_grace: Duration,
|
||||
pub force_kill_after: Duration,
|
||||
}
|
||||
|
||||
impl Default for SupervisorConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
execute_slots: 2,
|
||||
worker_ttl: Duration::from_secs(600),
|
||||
cancel_grace: Duration::from_secs(2),
|
||||
force_kill_after: Duration::from_secs(3),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ActiveWorker {
|
||||
handle: WorkerHandle,
|
||||
cancel_since: Option<Instant>,
|
||||
}
|
||||
|
||||
pub struct Supervisor {
|
||||
cfg: SupervisorConfig,
|
||||
pool: Mutex<WorkerPool>,
|
||||
active: Mutex<HashMap<String, ActiveWorker>>,
|
||||
cancel_dir: PathBuf,
|
||||
event_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Supervisor {
|
||||
pub fn new(
|
||||
cfg: SupervisorConfig,
|
||||
staging_root: impl AsRef<Path>,
|
||||
marqdo_bin: impl AsRef<Path>,
|
||||
cancel_dir: impl AsRef<Path>,
|
||||
event_dir: impl AsRef<Path>,
|
||||
) -> Self {
|
||||
let cancel_dir = cancel_dir.as_ref().to_path_buf();
|
||||
let event_dir = event_dir.as_ref().to_path_buf();
|
||||
let _ = std::fs::create_dir_all(&cancel_dir);
|
||||
let _ = std::fs::create_dir_all(&event_dir);
|
||||
Self {
|
||||
pool: Mutex::new(WorkerPool::new(
|
||||
staging_root,
|
||||
marqdo_bin,
|
||||
cfg.execute_slots,
|
||||
)),
|
||||
cfg,
|
||||
active: Mutex::new(HashMap::new()),
|
||||
cancel_dir,
|
||||
event_dir,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn warm(&self) -> Result<(), String> {
|
||||
self.pool.lock().unwrap().warm()
|
||||
}
|
||||
|
||||
pub fn dispatch(&self, req: InvokeRequestV2) -> Result<String, String> {
|
||||
req.validate()?;
|
||||
{
|
||||
let active = self.active.lock().unwrap();
|
||||
if active.len() >= self.cfg.execute_slots {
|
||||
return Err("supervisor.no_slot".into());
|
||||
}
|
||||
}
|
||||
let mut pool = self.pool.lock().unwrap();
|
||||
let worker = pool.acquire()?;
|
||||
drop(pool);
|
||||
let epoch = Instant::now().elapsed().as_nanos() as u64;
|
||||
let lease = Lease::new(
|
||||
format!("lease_{}", req.task_id),
|
||||
epoch,
|
||||
&req.task_id,
|
||||
&req.run_id,
|
||||
&req.attempt_id,
|
||||
self.cfg.worker_ttl,
|
||||
);
|
||||
let cancel = self.cancel_dir.join(format!("{}.tok", req.task_id));
|
||||
if !cancel.exists() {
|
||||
std::fs::write(&cancel, b"").map_err(|e| e.to_string())?;
|
||||
}
|
||||
let events = self.event_dir.join(format!("{}.ndjson", req.task_id));
|
||||
std::fs::write(&events, b"").map_err(|e| e.to_string())?;
|
||||
// Durable emit path (not under staging — WorkerHandle::Drop removes staging).
|
||||
let emit = self.event_dir.join(format!("{}.result.json", req.task_id));
|
||||
let fs_root = req
|
||||
.context
|
||||
.fs_root
|
||||
.as_ref()
|
||||
.map(PathBuf::from)
|
||||
.filter(|p| p.is_dir())
|
||||
.ok_or_else(|| "supervisor.fs_root_required".to_string())?;
|
||||
let args_path = req.args_ref.as_ref().and_then(|r| {
|
||||
r.strip_prefix("file:")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| {
|
||||
let p = PathBuf::from(r);
|
||||
p.is_file().then_some(p)
|
||||
})
|
||||
});
|
||||
let handle = {
|
||||
if std::env::var_os("MARQDO_RUNTIME_DRY_RUN").is_some() {
|
||||
let mut w = worker;
|
||||
w.lease = Some(lease.clone());
|
||||
w.emit_result = Some(emit.clone());
|
||||
w.state = WorkerState::Running;
|
||||
w
|
||||
} else {
|
||||
self.pool.lock().unwrap().lease_and_start(
|
||||
worker,
|
||||
lease.clone(),
|
||||
&req,
|
||||
&cancel,
|
||||
&events,
|
||||
&fs_root,
|
||||
args_path.as_deref(),
|
||||
&emit,
|
||||
)?
|
||||
}
|
||||
};
|
||||
let lease_id = lease.id.0.clone();
|
||||
self.active.lock().unwrap().insert(
|
||||
lease_id.clone(),
|
||||
ActiveWorker {
|
||||
handle,
|
||||
cancel_since: None,
|
||||
},
|
||||
);
|
||||
Ok(lease_id)
|
||||
}
|
||||
|
||||
pub fn event_path(&self, task_id: &str) -> PathBuf {
|
||||
self.event_dir.join(format!("{task_id}.ndjson"))
|
||||
}
|
||||
|
||||
pub fn cancel_path(&self, task_id: &str) -> PathBuf {
|
||||
self.cancel_dir.join(format!("{task_id}.tok"))
|
||||
}
|
||||
|
||||
pub fn emit_result_path(&self, lease_id: &str) -> Option<PathBuf> {
|
||||
self.active
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(lease_id)
|
||||
.and_then(|w| w.handle.emit_result.clone())
|
||||
}
|
||||
|
||||
/// Non-blocking poll: if worker exited, remove from active and return exit code.
|
||||
pub fn try_reap(&self, lease_id: &str) -> Result<Option<i32>, String> {
|
||||
let mut active = self.active.lock().unwrap();
|
||||
let Some(w) = active.get_mut(lease_id) else {
|
||||
return Ok(None);
|
||||
};
|
||||
match w.handle.try_wait()? {
|
||||
Some(st) => {
|
||||
let code = st.code().unwrap_or(-1);
|
||||
active.remove(lease_id);
|
||||
let _ = self.pool.lock().unwrap().warm();
|
||||
Ok(Some(code))
|
||||
}
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn signal_cancel(&self, lease_id: &str, task_id: &str) -> Result<(), String> {
|
||||
let tok = self.cancel_dir.join(format!("{task_id}.tok"));
|
||||
std::fs::write(&tok, b"cancelled").map_err(|e| e.to_string())?;
|
||||
let mut active = self.active.lock().unwrap();
|
||||
if let Some(w) = active.get_mut(lease_id) {
|
||||
w.cancel_since = Some(Instant::now());
|
||||
w.handle.state = WorkerState::Draining;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reap expired / force-kill after cancel grace. Returns orphan count.
|
||||
pub fn janitor_tick(&self) -> usize {
|
||||
let mut orphans = 0usize;
|
||||
let mut active = self.active.lock().unwrap();
|
||||
let mut done = Vec::new();
|
||||
for (id, w) in active.iter_mut() {
|
||||
if let Some(lease) = &w.handle.lease {
|
||||
if lease.expired() {
|
||||
w.handle.kill_process_group();
|
||||
orphans += 1;
|
||||
done.push(id.clone());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if let Some(since) = w.cancel_since {
|
||||
if since.elapsed() > self.cfg.cancel_grace + self.cfg.force_kill_after {
|
||||
w.handle.kill_process_group();
|
||||
orphans += 1;
|
||||
done.push(id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for id in done {
|
||||
active.remove(&id);
|
||||
}
|
||||
orphans
|
||||
}
|
||||
|
||||
pub fn active_count(&self) -> usize {
|
||||
self.active.lock().unwrap().len()
|
||||
}
|
||||
|
||||
pub fn release(&self, lease_id: &str) {
|
||||
let mut active = self.active.lock().unwrap();
|
||||
if let Some(mut w) = active.remove(lease_id) {
|
||||
w.handle.state = WorkerState::Draining;
|
||||
w.handle.kill_process_group();
|
||||
}
|
||||
// Async replenish hint.
|
||||
let _ = self.pool.lock().unwrap().warm();
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared supervisor handle for HTTP/control wiring.
|
||||
pub type SharedSupervisor = Arc<Supervisor>;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::runtime::protocol::{EntryRef, InvokeContext, LeaseRef};
|
||||
|
||||
fn req(task: &str) -> InvokeRequestV2 {
|
||||
InvokeRequestV2 {
|
||||
schema: "InvokeRequestV2".into(),
|
||||
schema_version: 2,
|
||||
task_id: task.into(),
|
||||
run_id: format!("run_{task}"),
|
||||
attempt_id: format!("attempt_{task}"),
|
||||
lease: LeaseRef {
|
||||
id: format!("lease_{task}"),
|
||||
epoch: 1,
|
||||
},
|
||||
entry: EntryRef {
|
||||
module: "agent/qdagent.mq.md".into(),
|
||||
function: "run".into(),
|
||||
},
|
||||
args_ref: None,
|
||||
context: InvokeContext {
|
||||
workspace_id: "ws".into(),
|
||||
snapshot_id: None,
|
||||
selection_ref: None,
|
||||
capabilities_ref: None,
|
||||
deadline_at: "2099-01-01T00:00:00Z".into(),
|
||||
fs_root: Some("/tmp".into()),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dry_run_two_parallel_leases() {
|
||||
std::env::set_var("MARQDO_RUNTIME_DRY_RUN", "1");
|
||||
let root = std::env::temp_dir().join(format!("mq-sup-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let bin = std::env::current_exe().unwrap();
|
||||
let _ = std::fs::create_dir_all(root.join("fs"));
|
||||
let mut ra = req("a");
|
||||
ra.context.fs_root = Some(root.join("fs").to_string_lossy().into());
|
||||
let mut rb = req("b");
|
||||
rb.context.fs_root = ra.context.fs_root.clone();
|
||||
let mut rc = req("c");
|
||||
rc.context.fs_root = ra.context.fs_root.clone();
|
||||
let sup = Supervisor::new(
|
||||
SupervisorConfig {
|
||||
execute_slots: 2,
|
||||
..SupervisorConfig::default()
|
||||
},
|
||||
root.join("stage"),
|
||||
&bin,
|
||||
root.join("cancel"),
|
||||
root.join("events"),
|
||||
);
|
||||
sup.warm().unwrap();
|
||||
let a = sup.dispatch(ra).unwrap();
|
||||
let b = sup.dispatch(rb).unwrap();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(sup.active_count(), 2);
|
||||
assert!(sup.dispatch(rc).is_err());
|
||||
sup.release(&a);
|
||||
assert_eq!(sup.active_count(), 1);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::env::remove_var("MARQDO_RUNTIME_DRY_RUN");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! Task index with idempotency, revision CAS, and event log (M-R3 / M-R4).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::runtime::protocol::RuntimeEventV2;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum TaskState {
|
||||
Accepted,
|
||||
Queued,
|
||||
Running,
|
||||
Finalizing,
|
||||
Succeeded,
|
||||
Failed,
|
||||
CancelRequested,
|
||||
Cancelled,
|
||||
Interrupted,
|
||||
NeedsReconciliation,
|
||||
}
|
||||
|
||||
impl TaskState {
|
||||
pub fn is_terminal(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Succeeded
|
||||
| Self::Failed
|
||||
| Self::Cancelled
|
||||
| Self::Interrupted
|
||||
| Self::NeedsReconciliation
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TaskRecord {
|
||||
pub task_id: String,
|
||||
pub run_id: String,
|
||||
pub attempt_id: String,
|
||||
pub workspace_id: String,
|
||||
pub session_id: Option<String>,
|
||||
pub state: TaskState,
|
||||
pub revision: u64,
|
||||
pub idempotency_key: String,
|
||||
pub payload_hash: String,
|
||||
pub lease_id: Option<String>,
|
||||
pub lease_epoch: Option<u64>,
|
||||
pub created_at: String,
|
||||
pub updated_at: String,
|
||||
pub cancel_requested_at: Option<String>,
|
||||
pub result: Option<Value>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Inner {
|
||||
tasks: HashMap<String, TaskRecord>,
|
||||
/// idempotency_key → task_id
|
||||
idem: HashMap<String, String>,
|
||||
/// task_id → events (monotonic seq)
|
||||
events: HashMap<String, Vec<RuntimeEventV2>>,
|
||||
next_epoch: u64,
|
||||
}
|
||||
|
||||
pub struct TaskStore {
|
||||
inner: Arc<Mutex<Inner>>,
|
||||
persist_dir: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StoreError {
|
||||
Conflict(String),
|
||||
NotFound,
|
||||
AlreadyTerminal(TaskState),
|
||||
Io(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for StoreError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::Conflict(s) => write!(f, "conflict: {s}"),
|
||||
Self::NotFound => write!(f, "not_found"),
|
||||
Self::AlreadyTerminal(s) => write!(f, "already_terminal:{s:?}"),
|
||||
Self::Io(s) => write!(f, "io: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TaskStore {
|
||||
pub fn memory() -> Self {
|
||||
Self {
|
||||
inner: Arc::new(Mutex::new(Inner::default())),
|
||||
persist_dir: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_persist(dir: impl AsRef<Path>) -> Result<Self, StoreError> {
|
||||
let dir = dir.as_ref().to_path_buf();
|
||||
std::fs::create_dir_all(&dir).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
let store = Self {
|
||||
inner: Arc::new(Mutex::new(Inner::default())),
|
||||
persist_dir: Some(dir.clone()),
|
||||
};
|
||||
store.load()?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
fn now() -> String {
|
||||
let ms = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_millis();
|
||||
format!("{ms}")
|
||||
}
|
||||
|
||||
pub fn payload_hash(payload: &Value) -> String {
|
||||
let bytes = serde_json::to_vec(payload).unwrap_or_default();
|
||||
format!("{:x}", Sha256::digest(&bytes))
|
||||
}
|
||||
|
||||
/// Admit or return existing task for the same idempotency key.
|
||||
/// Same key + different payload hash → Conflict (409).
|
||||
pub fn admit(
|
||||
&self,
|
||||
task_id: impl Into<String>,
|
||||
run_id: impl Into<String>,
|
||||
workspace_id: impl Into<String>,
|
||||
session_id: Option<String>,
|
||||
idempotency_key: impl Into<String>,
|
||||
payload: &Value,
|
||||
) -> Result<TaskRecord, StoreError> {
|
||||
let task_id = task_id.into();
|
||||
let idempotency_key = idempotency_key.into();
|
||||
let payload_hash = Self::payload_hash(payload);
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
if let Some(existing_id) = g.idem.get(&idempotency_key).cloned() {
|
||||
let existing = g.tasks.get(&existing_id).cloned().ok_or(StoreError::NotFound)?;
|
||||
if existing.payload_hash != payload_hash {
|
||||
return Err(StoreError::Conflict(
|
||||
"idempotency key reuse with different payload".into(),
|
||||
));
|
||||
}
|
||||
return Ok(existing);
|
||||
}
|
||||
let now = Self::now();
|
||||
let rec = TaskRecord {
|
||||
task_id: task_id.clone(),
|
||||
run_id: run_id.into(),
|
||||
attempt_id: format!("attempt_{}", task_id),
|
||||
workspace_id: workspace_id.into(),
|
||||
session_id,
|
||||
state: TaskState::Accepted,
|
||||
revision: 1,
|
||||
idempotency_key: idempotency_key.clone(),
|
||||
payload_hash,
|
||||
lease_id: None,
|
||||
lease_epoch: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
cancel_requested_at: None,
|
||||
result: None,
|
||||
error: None,
|
||||
};
|
||||
g.idem.insert(idempotency_key, task_id.clone());
|
||||
g.tasks.insert(task_id, rec.clone());
|
||||
g.events.insert(rec.task_id.clone(), Vec::new());
|
||||
drop(g);
|
||||
self.persist_task(&rec)?;
|
||||
Ok(rec)
|
||||
}
|
||||
|
||||
pub fn get(&self, task_id: &str) -> Result<TaskRecord, StoreError> {
|
||||
self.inner
|
||||
.lock()
|
||||
.unwrap()
|
||||
.tasks
|
||||
.get(task_id)
|
||||
.cloned()
|
||||
.ok_or(StoreError::NotFound)
|
||||
}
|
||||
|
||||
/// CAS state transition. `expected_revision` must match.
|
||||
pub fn cas_state(
|
||||
&self,
|
||||
task_id: &str,
|
||||
expected_revision: u64,
|
||||
next: TaskState,
|
||||
patch: impl FnOnce(&mut TaskRecord),
|
||||
) -> Result<TaskRecord, StoreError> {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
let rec = g.tasks.get_mut(task_id).ok_or(StoreError::NotFound)?;
|
||||
if rec.revision != expected_revision {
|
||||
return Err(StoreError::Conflict(format!(
|
||||
"revision {} != {}",
|
||||
rec.revision, expected_revision
|
||||
)));
|
||||
}
|
||||
if rec.state.is_terminal() && next != rec.state {
|
||||
return Err(StoreError::AlreadyTerminal(rec.state));
|
||||
}
|
||||
rec.state = next;
|
||||
rec.revision += 1;
|
||||
rec.updated_at = Self::now();
|
||||
patch(rec);
|
||||
let out = rec.clone();
|
||||
drop(g);
|
||||
self.persist_task(&out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn request_cancel(&self, task_id: &str) -> Result<TaskRecord, StoreError> {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
let rec = g.tasks.get_mut(task_id).ok_or(StoreError::NotFound)?;
|
||||
if rec.state.is_terminal() {
|
||||
return Err(StoreError::AlreadyTerminal(rec.state));
|
||||
}
|
||||
let rev = rec.revision;
|
||||
rec.state = TaskState::CancelRequested;
|
||||
rec.revision = rev + 1;
|
||||
rec.cancel_requested_at = Some(Self::now());
|
||||
rec.updated_at = Self::now();
|
||||
let out = rec.clone();
|
||||
drop(g);
|
||||
self.persist_task(&out)?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn append_event(
|
||||
&self,
|
||||
task_id: &str,
|
||||
run_id: &str,
|
||||
attempt_id: &str,
|
||||
event_type: &str,
|
||||
payload: Value,
|
||||
) -> Result<RuntimeEventV2, StoreError> {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
if !g.tasks.contains_key(task_id) {
|
||||
return Err(StoreError::NotFound);
|
||||
}
|
||||
let list = g.events.entry(task_id.to_string()).or_default();
|
||||
let seq = list.last().map(|e| e.seq + 1).unwrap_or(1);
|
||||
let ev = RuntimeEventV2::new(task_id, run_id, attempt_id, seq, event_type, payload);
|
||||
list.push(ev.clone());
|
||||
drop(g);
|
||||
self.persist_event(&ev)?;
|
||||
Ok(ev)
|
||||
}
|
||||
|
||||
/// Events with seq > after_seq (Last-Event-ID resume).
|
||||
pub fn events_after(
|
||||
&self,
|
||||
task_id: &str,
|
||||
after_seq: u64,
|
||||
) -> Result<Vec<RuntimeEventV2>, StoreError> {
|
||||
let g = self.inner.lock().unwrap();
|
||||
let list = g.events.get(task_id).ok_or(StoreError::NotFound)?;
|
||||
Ok(list.iter().filter(|e| e.seq > after_seq).cloned().collect())
|
||||
}
|
||||
|
||||
pub fn next_lease_epoch(&self) -> u64 {
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
g.next_epoch += 1;
|
||||
g.next_epoch
|
||||
}
|
||||
|
||||
fn persist_task(&self, rec: &TaskRecord) -> Result<(), StoreError> {
|
||||
let Some(dir) = &self.persist_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let path = dir.join("tasks").join(format!("{}.json", rec.task_id));
|
||||
std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
let body = serde_json::to_vec_pretty(rec).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
std::fs::write(&tmp, body).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
std::fs::rename(&tmp, &path).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn persist_event(&self, ev: &RuntimeEventV2) -> Result<(), StoreError> {
|
||||
let Some(dir) = &self.persist_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let path = dir.join("events").join(format!("{}.ndjson", ev.task_id));
|
||||
std::fs::create_dir_all(path.parent().unwrap()).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
use std::io::Write;
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&path)
|
||||
.map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
let line = serde_json::to_string(ev).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
writeln!(f, "{line}").map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load(&self) -> Result<(), StoreError> {
|
||||
let Some(dir) = &self.persist_dir else {
|
||||
return Ok(());
|
||||
};
|
||||
let tasks_dir = dir.join("tasks");
|
||||
if !tasks_dir.is_dir() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut g = self.inner.lock().unwrap();
|
||||
for ent in std::fs::read_dir(&tasks_dir).map_err(|e| StoreError::Io(e.to_string()))? {
|
||||
let ent = ent.map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
if ent.path().extension().and_then(|e| e.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let body =
|
||||
std::fs::read_to_string(ent.path()).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
let rec: TaskRecord =
|
||||
serde_json::from_str(&body).map_err(|e| StoreError::Io(e.to_string()))?;
|
||||
g.idem
|
||||
.insert(rec.idempotency_key.clone(), rec.task_id.clone());
|
||||
g.events.entry(rec.task_id.clone()).or_default();
|
||||
g.tasks.insert(rec.task_id.clone(), rec);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn idempotent_admit_and_conflict() {
|
||||
let store = TaskStore::memory();
|
||||
let p = json!({"a": 1});
|
||||
let a = store
|
||||
.admit("t1", "r1", "ws", None, "key-1", &p)
|
||||
.unwrap();
|
||||
let b = store
|
||||
.admit("t2", "r2", "ws", None, "key-1", &p)
|
||||
.unwrap();
|
||||
assert_eq!(a.task_id, b.task_id);
|
||||
let err = store
|
||||
.admit("t3", "r3", "ws", None, "key-1", &json!({"a": 2}))
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, StoreError::Conflict(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_cas_terminal() {
|
||||
let store = TaskStore::memory();
|
||||
let t = store
|
||||
.admit("t1", "r1", "ws", None, "k", &json!({}))
|
||||
.unwrap();
|
||||
store
|
||||
.cas_state(&t.task_id, t.revision, TaskState::Succeeded, |r| {
|
||||
r.result = Some(json!("ok"));
|
||||
})
|
||||
.unwrap();
|
||||
let err = store.request_cancel(&t.task_id).unwrap_err();
|
||||
assert!(matches!(err, StoreError::AlreadyTerminal(TaskState::Succeeded)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn event_seq_monotonic_and_resume() {
|
||||
let store = TaskStore::memory();
|
||||
let t = store
|
||||
.admit("t1", "r1", "ws", None, "k", &json!({}))
|
||||
.unwrap();
|
||||
let e1 = store
|
||||
.append_event(&t.task_id, &t.run_id, &t.attempt_id, "message.delta", json!({"n":1}))
|
||||
.unwrap();
|
||||
let e2 = store
|
||||
.append_event(&t.task_id, &t.run_id, &t.attempt_id, "message.delta", json!({"n":2}))
|
||||
.unwrap();
|
||||
assert_eq!(e1.seq, 1);
|
||||
assert_eq!(e2.seq, 2);
|
||||
let after = store.events_after(&t.task_id, 1).unwrap();
|
||||
assert_eq!(after.len(), 1);
|
||||
assert_eq!(after[0].seq, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
//! One-shot Marqdo worker process handles (M-R2).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
use serde_json::{json, Value};
|
||||
|
||||
use crate::runtime::lease::{Lease, WorkerState};
|
||||
use crate::runtime::protocol::{InvokeRequestV2, PROTOCOL_VERSION};
|
||||
|
||||
static WORKER_SEQ: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
pub struct WorkerHandle {
|
||||
pub id: String,
|
||||
pub state: WorkerState,
|
||||
pub lease: Option<Lease>,
|
||||
child: Option<Child>,
|
||||
staging: PathBuf,
|
||||
/// Where the child writes `--emit-result` JSON.
|
||||
pub emit_result: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl WorkerHandle {
|
||||
pub fn staging(&self) -> &Path {
|
||||
&self.staging
|
||||
}
|
||||
|
||||
pub fn take_child(&mut self) -> Option<Child> {
|
||||
self.child.take()
|
||||
}
|
||||
|
||||
pub fn kill_process_group(&mut self) {
|
||||
if let Some(mut child) = self.child.take() {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
}
|
||||
self.state = WorkerState::Exited;
|
||||
}
|
||||
|
||||
pub fn try_wait(&mut self) -> Result<Option<std::process::ExitStatus>, String> {
|
||||
let Some(child) = self.child.as_mut() else {
|
||||
return Ok(None);
|
||||
};
|
||||
child.try_wait().map_err(|e| format!("worker.wait: {e}"))
|
||||
}
|
||||
|
||||
pub fn wait(&mut self) -> Result<std::process::ExitStatus, String> {
|
||||
let Some(mut child) = self.child.take() else {
|
||||
return Err("worker.no_child".into());
|
||||
};
|
||||
let st = child.wait().map_err(|e| format!("worker.wait: {e}"))?;
|
||||
self.state = WorkerState::Exited;
|
||||
Ok(st)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for WorkerHandle {
|
||||
fn drop(&mut self) {
|
||||
self.kill_process_group();
|
||||
let _ = std::fs::remove_dir_all(&self.staging);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WorkerPool {
|
||||
staging_root: PathBuf,
|
||||
marqdo_bin: PathBuf,
|
||||
ready: Vec<WorkerHandle>,
|
||||
target_ready: usize,
|
||||
}
|
||||
|
||||
impl WorkerPool {
|
||||
pub fn new(staging_root: impl AsRef<Path>, marqdo_bin: impl AsRef<Path>, target_ready: usize) -> Self {
|
||||
let staging_root = staging_root.as_ref().to_path_buf();
|
||||
let _ = std::fs::create_dir_all(&staging_root);
|
||||
Self {
|
||||
staging_root,
|
||||
marqdo_bin: marqdo_bin.as_ref().to_path_buf(),
|
||||
ready: Vec::new(),
|
||||
target_ready,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn spawn_ready(&mut self) -> Result<WorkerHandle, String> {
|
||||
let seq = WORKER_SEQ.fetch_add(1, Ordering::Relaxed);
|
||||
let id = format!("worker_{seq}");
|
||||
let staging = self.staging_root.join(&id);
|
||||
std::fs::create_dir_all(&staging).map_err(|e| e.to_string())?;
|
||||
if !self.marqdo_bin.exists() {
|
||||
return Err(format!("worker.binary_missing: {}", self.marqdo_bin.display()));
|
||||
}
|
||||
Ok(WorkerHandle {
|
||||
id,
|
||||
state: WorkerState::Ready,
|
||||
lease: None,
|
||||
child: None,
|
||||
staging,
|
||||
emit_result: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn warm(&mut self) -> Result<(), String> {
|
||||
while self.ready.len() < self.target_ready {
|
||||
let w = self.spawn_ready()?;
|
||||
self.ready.push(w);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn acquire(&mut self) -> Result<WorkerHandle, String> {
|
||||
if self.ready.is_empty() {
|
||||
self.warm()?;
|
||||
}
|
||||
self.ready
|
||||
.pop()
|
||||
.ok_or_else(|| "worker.pool_empty".to_string())
|
||||
}
|
||||
|
||||
pub fn replenish_async_hint(&self) -> usize {
|
||||
self.target_ready.saturating_sub(self.ready.len())
|
||||
}
|
||||
|
||||
/// Lease a worker: spawn `marqdo run --call-lib-path …` with request-scoped env.
|
||||
/// `emit_result` must be outside staging so Drop does not erase the parent's read path.
|
||||
pub fn lease_and_start(
|
||||
&self,
|
||||
mut worker: WorkerHandle,
|
||||
lease: Lease,
|
||||
req: &InvokeRequestV2,
|
||||
cancel_token: &Path,
|
||||
event_sink: &Path,
|
||||
fs_root: &Path,
|
||||
args_json: Option<&Path>,
|
||||
emit_result: &Path,
|
||||
) -> Result<WorkerHandle, String> {
|
||||
req.validate()?;
|
||||
let entry = PathBuf::from(&req.entry.module);
|
||||
if !entry.is_file() {
|
||||
return Err(format!(
|
||||
"worker.entry_missing: {} (need absolute site entry .mq.md)",
|
||||
entry.display()
|
||||
));
|
||||
}
|
||||
if let Some(parent) = emit_result.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let emit = emit_result.to_path_buf();
|
||||
let mut cmd = Command::new(&self.marqdo_bin);
|
||||
cmd.arg("run")
|
||||
.arg(&entry)
|
||||
.arg("--call-lib-path")
|
||||
.arg(&req.entry.function)
|
||||
.arg("--fs-root")
|
||||
.arg(fs_root)
|
||||
.arg("--emit-result")
|
||||
.arg(&emit)
|
||||
// Worker cwd = site root so relative imports resolve; staging only for lease bookkeeping.
|
||||
.current_dir(fs_root)
|
||||
.env("MARQDO_RUN_ID", &req.run_id)
|
||||
.env("MARQDO_TASK_ID", &req.task_id)
|
||||
.env("MARQDO_ATTEMPT_ID", &req.attempt_id)
|
||||
.env("MARQDO_LEASE_ID", &lease.id.0)
|
||||
.env("MARQDO_LEASE_EPOCH", lease.epoch.to_string())
|
||||
.env("MARQDO_CANCEL_TOKEN", cancel_token)
|
||||
.env("MARQDO_EVENT_FORWARD", event_sink)
|
||||
.env("MARQDO_WORKSPACE_ID", &req.context.workspace_id)
|
||||
.env("MARQDO_PROTOCOL_VERSION", PROTOCOL_VERSION.to_string())
|
||||
.env("MARQDO_FS_ROOT", fs_root)
|
||||
.stdin(Stdio::null())
|
||||
// Avoid pipe-buffer deadlock: nobody drains worker stdout/stderr.
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
if let Some(args) = args_json {
|
||||
cmd.arg("--args-json").arg(args);
|
||||
} else if let Some(r) = &req.args_ref {
|
||||
if let Some(path) = r.strip_prefix("file:") {
|
||||
cmd.arg("--args-json").arg(path);
|
||||
}
|
||||
}
|
||||
if let Some(sel) = &req.context.selection_ref {
|
||||
cmd.env("MARQDO_SELECTION_REF", sel);
|
||||
}
|
||||
if let Some(snap) = &req.context.snapshot_id {
|
||||
cmd.env("MARQDO_SNAPSHOT_ID", snap);
|
||||
}
|
||||
if let Some(cap) = &req.context.capabilities_ref {
|
||||
cmd.env("MARQDO_CAPABILITIES_REF", cap);
|
||||
}
|
||||
let child = cmd.spawn().map_err(|e| format!("worker.spawn: {e}"))?;
|
||||
worker.child = Some(child);
|
||||
worker.lease = Some(lease);
|
||||
worker.emit_result = Some(emit);
|
||||
worker.state = WorkerState::Running;
|
||||
Ok(worker)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handshake_ok(report: &Value) -> Result<(), String> {
|
||||
let ver = report
|
||||
.get("protocol_version")
|
||||
.and_then(|v| v.as_u64())
|
||||
.ok_or("handshake.protocol_version")?;
|
||||
if ver != PROTOCOL_VERSION as u64 {
|
||||
return Err(format!("handshake.version_mismatch: {ver}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn fake_handshake() -> Value {
|
||||
json!({
|
||||
"cli": true,
|
||||
"protocol_version": PROTOCOL_VERSION,
|
||||
"capabilities": ["runtime.isolated_execution"],
|
||||
"build": env!("CARGO_PKG_VERSION"),
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn handshake_version_gate() {
|
||||
assert!(handshake_ok(&fake_handshake()).is_ok());
|
||||
assert!(handshake_ok(&json!({"protocol_version": 1})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pool_warm_requires_binary() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-pool-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
let mut pool = WorkerPool::new(&dir, "/no/such/marqdo-bin", 1);
|
||||
assert!(pool.warm().is_err());
|
||||
let self_bin = std::env::current_exe().unwrap();
|
||||
let mut pool = WorkerPool::new(&dir, &self_bin, 1);
|
||||
pool.warm().unwrap();
|
||||
assert_eq!(pool.ready.len(), 1);
|
||||
let w = pool.acquire().unwrap();
|
||||
assert_eq!(w.state, WorkerState::Ready);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_clears_child() {
|
||||
let dir = std::env::temp_dir().join(format!("mq-wh-{}", std::process::id()));
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let mut w = WorkerHandle {
|
||||
id: "w".into(),
|
||||
state: WorkerState::Running,
|
||||
lease: None,
|
||||
child: None,
|
||||
staging: dir.clone(),
|
||||
emit_result: None,
|
||||
};
|
||||
w.kill_process_group();
|
||||
assert_eq!(w.state, WorkerState::Exited);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
}
|
||||
+47
-27
@@ -240,32 +240,24 @@ pub struct Compilation {
|
||||
/// side-effect free: it never loads plugins, evaluates expressions or fetches
|
||||
/// sources.
|
||||
pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
let t_index = std::time::Instant::now();
|
||||
let root = ProjectRoot::new(&options.project_root)?;
|
||||
let index = ProjectIndex::build(root.clone())?;
|
||||
let index_ms = t_index.elapsed().as_millis();
|
||||
// Reuse parsed modules from ProjectIndex — same input snapshot, no second parse (M-R5b).
|
||||
let mut files = BTreeMap::new();
|
||||
let mut diagnostics = Vec::new();
|
||||
for file in root.source_files()? {
|
||||
let text = fs::read_to_string(&file)
|
||||
.with_context(|| format!("read semantic source {}", file.display()))?;
|
||||
match crate::load::parse_source_auto(&text) {
|
||||
Ok(module) => {
|
||||
let module_id = index
|
||||
.modules()
|
||||
.iter()
|
||||
.find_map(|(id, path)| (path == &file).then(|| id.clone()));
|
||||
if let Some(module_id) = module_id {
|
||||
files.insert(module_id, (file, text, module));
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
diagnostics.push(
|
||||
Diagnostic::new(Some(&file), Span::new(1, 1), error.to_string())
|
||||
.with_code("parse.semantic")
|
||||
.with_severity(Severity::Error),
|
||||
);
|
||||
}
|
||||
}
|
||||
for (module_id, parsed) in index.parsed_modules() {
|
||||
files.insert(
|
||||
module_id.clone(),
|
||||
(
|
||||
parsed.path.clone(),
|
||||
parsed.text.clone(),
|
||||
parsed.module.clone(),
|
||||
),
|
||||
);
|
||||
}
|
||||
let _ = index_ms; // ProjectIndex build duration (M-R5b span)
|
||||
|
||||
// Wire import_modules from already-parsed project files so BoundCall path
|
||||
// resolve shares `resolve_for_exec` (no plugin load / no re-parse).
|
||||
@@ -288,12 +280,8 @@ pub fn compile_project(options: &CompileOptions) -> Result<Compilation> {
|
||||
collect_functions(&module.functions, &mut Vec::new(), &mut by_path);
|
||||
let narrative_links = crate::parse::scan_narrative_links(text);
|
||||
let module_prov = super::provenance::parse_module_provenance(text);
|
||||
let module_symbols: Vec<&SymbolDecl> = index
|
||||
.symbols()
|
||||
.iter()
|
||||
.filter(|s| &s.module == module_id)
|
||||
.collect();
|
||||
for symbol in index.symbols().iter().filter(|s| &s.module == module_id) {
|
||||
let module_symbols = index.symbols_in_module(module_id);
|
||||
for symbol in index.symbols_in_module(module_id) {
|
||||
let function = by_path.get(&symbol.declaration_path).expect("symbol collected from module");
|
||||
let owned_links: Vec<_> = narrative_links
|
||||
.iter()
|
||||
@@ -1315,12 +1303,44 @@ pub fn write_semantic_projections(out_dir: &Path, compilation: &Compilation) ->
|
||||
fs::create_dir_all(gen_dir.join("verification"))?;
|
||||
write_generation_tree(&gen_dir, compilation)?;
|
||||
|
||||
// Publish journal + CAS (M-R6): record expected CURRENT before switching.
|
||||
let expected = fs::read_to_string(out_dir.join("CURRENT"))
|
||||
.ok()
|
||||
.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty());
|
||||
let source_digest = {
|
||||
let mut h = Sha256::new();
|
||||
for a in &compilation.semantics.artifacts {
|
||||
h.update(a.hashes.artifact.0.as_bytes());
|
||||
}
|
||||
format!("sha256:{:x}", h.finalize())
|
||||
};
|
||||
// Staging already written under gen_dir; journal tracks CURRENT switch.
|
||||
let mut journal = crate::runtime::PublishJournal::begin(
|
||||
out_dir,
|
||||
&compilation.semantics.project_id,
|
||||
expected,
|
||||
&build_id,
|
||||
&source_digest,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("publish journal: {e}"))?;
|
||||
// Point journal staging at the generation we just wrote (already complete).
|
||||
journal.staging_dir = gen_dir.clone();
|
||||
journal.generation_dir = gen_dir.clone();
|
||||
journal
|
||||
.mark(out_dir, crate::runtime::publish::PublishPhase::Validated)
|
||||
.map_err(|e| anyhow::anyhow!("publish journal mark: {e}"))?;
|
||||
|
||||
// Atomic generation pointer: only publish CURRENT after the tree is complete.
|
||||
let current_tmp = out_dir.join("CURRENT.tmp");
|
||||
fs::write(¤t_tmp, format!("{build_id}\n"))
|
||||
.with_context(|| format!("write {}", current_tmp.display()))?;
|
||||
fs::rename(¤t_tmp, out_dir.join("CURRENT"))
|
||||
.with_context(|| format!("publish CURRENT under {}", out_dir.display()))?;
|
||||
journal
|
||||
.mark(out_dir, crate::runtime::publish::PublishPhase::CurrentSwitched)
|
||||
.map_err(|e| anyhow::anyhow!("publish journal current: {e}"))?;
|
||||
let _ = fs::remove_file(out_dir.join("publish_journal.json"));
|
||||
|
||||
// Compatibility root: stage a full mirror, then swap names (best-effort for
|
||||
// legacy readers that do not follow CURRENT).
|
||||
|
||||
@@ -92,15 +92,29 @@ pub struct SymbolDecl {
|
||||
pub line: u32,
|
||||
}
|
||||
|
||||
/// Parsed module retained so `compile_project` does not re-parse (M-R5b).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ParsedModule {
|
||||
pub path: PathBuf,
|
||||
pub text: String,
|
||||
pub module: crate::ast::Module,
|
||||
}
|
||||
|
||||
/// Deterministic read-only view of all declarations in one project.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProjectIndex {
|
||||
project_id: String,
|
||||
root: ProjectRoot,
|
||||
modules: BTreeMap<ModuleId, PathBuf>,
|
||||
/// path → module id (avoids linear scan per file in compile_project).
|
||||
path_to_module: BTreeMap<PathBuf, ModuleId>,
|
||||
symbols: Vec<SymbolDecl>,
|
||||
by_id: BTreeMap<SymbolId, usize>,
|
||||
by_name: BTreeMap<String, Vec<usize>>,
|
||||
/// module → symbol indexes (avoids filtering the full symbol table per module).
|
||||
symbols_by_module: BTreeMap<ModuleId, Vec<usize>>,
|
||||
/// Shared parsed AST/text for the same input snapshot.
|
||||
parsed: BTreeMap<ModuleId, ParsedModule>,
|
||||
}
|
||||
|
||||
impl ProjectIndex {
|
||||
@@ -108,7 +122,9 @@ impl ProjectIndex {
|
||||
let project_id = project_id(root.path());
|
||||
let files = root.source_files()?;
|
||||
let mut modules = BTreeMap::new();
|
||||
let mut path_to_module = BTreeMap::new();
|
||||
let mut symbols = Vec::new();
|
||||
let mut parsed = BTreeMap::new();
|
||||
|
||||
for file in files {
|
||||
let source = fs::read_to_string(&file)
|
||||
@@ -121,6 +137,7 @@ impl ProjectIndex {
|
||||
file.display()
|
||||
);
|
||||
}
|
||||
path_to_module.insert(file.clone(), module_id.clone());
|
||||
let module = crate::load::parse_source_auto(&source)
|
||||
.with_context(|| format!("parse source {}", file.display()))?;
|
||||
for function in &module.functions {
|
||||
@@ -134,28 +151,47 @@ impl ProjectIndex {
|
||||
&mut symbols,
|
||||
)?;
|
||||
}
|
||||
parsed.insert(
|
||||
module_id.clone(),
|
||||
ParsedModule {
|
||||
path: file,
|
||||
text: source,
|
||||
module,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
symbols.sort_by(|a, b| a.id.cmp(&b.id));
|
||||
let mut by_id = BTreeMap::new();
|
||||
let mut by_name: BTreeMap<String, Vec<usize>> = BTreeMap::new();
|
||||
let mut symbols_by_module: BTreeMap<ModuleId, Vec<usize>> = BTreeMap::new();
|
||||
for (index, symbol) in symbols.iter().enumerate() {
|
||||
if by_id.insert(symbol.id.clone(), index).is_some() {
|
||||
bail!("duplicate symbol id `{}`", symbol.id);
|
||||
}
|
||||
by_name.entry(symbol.name.clone()).or_default().push(index);
|
||||
symbols_by_module
|
||||
.entry(symbol.module.clone())
|
||||
.or_default()
|
||||
.push(index);
|
||||
}
|
||||
for indexes in by_name.values_mut() {
|
||||
indexes.sort_by(|a, b| symbols[*a].id.cmp(&symbols[*b].id));
|
||||
}
|
||||
for indexes in symbols_by_module.values_mut() {
|
||||
indexes.sort_by(|a, b| symbols[*a].id.cmp(&symbols[*b].id));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
project_id,
|
||||
root,
|
||||
modules,
|
||||
path_to_module,
|
||||
symbols,
|
||||
by_id,
|
||||
by_name,
|
||||
symbols_by_module,
|
||||
parsed,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -171,6 +207,21 @@ impl ProjectIndex {
|
||||
&self.modules
|
||||
}
|
||||
|
||||
pub fn module_id_for_path(&self, path: &Path) -> Option<&ModuleId> {
|
||||
self.path_to_module.get(path)
|
||||
}
|
||||
|
||||
pub fn symbols_in_module(&self, module_id: &ModuleId) -> Vec<&SymbolDecl> {
|
||||
self.symbols_by_module
|
||||
.get(module_id)
|
||||
.map(|idxs| idxs.iter().map(|i| &self.symbols[*i]).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn parsed_modules(&self) -> &BTreeMap<ModuleId, ParsedModule> {
|
||||
&self.parsed
|
||||
}
|
||||
|
||||
pub fn symbols(&self) -> &[SymbolDecl] {
|
||||
&self.symbols
|
||||
}
|
||||
|
||||
+359
-86
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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"
|
||||
]
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user