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

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

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

No files matched your search

+202
View File
@@ -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);
}
}
+457
View File
@@ -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");
}
}
+58
View File
@@ -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
}
}
+26
View File
@@ -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};
+158
View File
@@ -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());
}
}
+274
View File
@@ -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 &current != 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"));
}
}
+249
View File
@@ -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"));
}
}
+303
View File
@@ -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");
}
}
+385
View File
@@ -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);
}
}
+259
View File
@@ -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);
}
}