From 9af929971c2e6d60873b881b567c5ab615f7ef1a Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 27 Oct 2026 08:44:07 +0800 Subject: [PATCH] =?UTF-8?q?fix(web):=20disconnect=E2=89=A0cancel=20and=20i?= =?UTF-8?q?solate=20short/read/control=20lanes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Observer SSE close no longer cancels execute by default; short/read/control bypass parent INVOKE_LOCK via isolated admission, with read_lane=1 and gold samples. Co-authored-by: Cursor --- doc/adr/0009-isolated-web-runtime.md | 20 +- plugins/web/internal/httpx/routes_invoke.go | 100 +++++--- plugins/web/internal/httpx/sse_bridge_test.go | 3 +- src/workbench/capabilities.rs | 3 +- tests/ext/isolated-execute-site/serve.mq.md | 11 +- tests/ext/isolated-execute-site/site.mq.md | 13 ++ tests/isolated_execute_mr01.rs | 221 ++++++++++++++++++ 7 files changed, 333 insertions(+), 38 deletions(-) diff --git a/doc/adr/0009-isolated-web-runtime.md b/doc/adr/0009-isolated-web-runtime.md index 4833c4a..f32a07c 100644 --- a/doc/adr/0009-isolated-web-runtime.md +++ b/doc/adr/0009-isolated-web-runtime.md @@ -3,9 +3,9 @@ | 项目 | 约定 | |---|---| | 状态 | **Accepted**;HTTP **execute** 路径正式替代 [ADR 0008](0008-web-invoke-serialization.md) 的并行性结论。`legacy_serial`(未声明且非流式)仍引用 0008 单飞 / 父进程 `CallLibPath`。 | -| 日期 | 2026-10-26 | +| 日期 | 2026-10-26(修订 2026-10-27:disconnect≠cancel;control/read/short 无父锁) | | 设计 | [isolated-web-runtime-development-2026-10-26.md](../design/isolated-web-runtime-development-2026-10-26.md) | -| 金样例 | `tests/isolated_execute_mr01.rs`(MR-01 双 60s SSE + short reads;同文件 MR-02 槽满拒绝) | +| 金样例 | `tests/isolated_execute_mr01.rs`(MR-01 双 60s SSE + short reads;同文件 MR-02 槽满拒绝;disconnect-keeps-running;control-under-dual-execute) | ## 背景 @@ -14,18 +14,20 @@ ADR 0008 确认:Go HTTP 多线程,但所有 Endpoint 共享一把解释器 ## 决策 1. **首选架构**:预热的一次性 Marqdo worker 进程池;每个租约独占一个进程与 HostContext。 -2. **HTTP 默认**:`class=execute` 或 `return=sse-live` 或 body `stream:true` → `admit` → `dispatch`(`--call-lib-path` worker);禁止父进程 `CallLibPath` / `Setenv` / `legacySSEBridgeMu`。`short` / `read` / `control` 仍父进程短路径;未声明非流式 → `legacy_serial`。 -3. **控制/读取分离**:取消与事件订阅不进入任务解释器锁;短业务与长执行有独立容量(execute 槽默认 2)。 -4. **协议**:`InvokeRequestV2` / worker env + NDJSON `MARQDO_EVENT_FORWARD` + `--emit-result`(首期);`/_runtime/*` 控制面。 -5. **能力探测**:`runtime.isolated_execution=1`(默认)、`runtime.task_control_v2`、`runtime.event_replay`、`view.analysis_cache_v2`;`runtime.read_lane` 仍 0。 -6. **发布**:`expected_generation` CAS + publish journal;逻辑文档 ID 与物理 generation 路径解耦。 +2. **HTTP 默认**:声明的 `class=execute|short|read|control`,或 `return=sse-live` / body `stream:true` → `admit` → `dispatch`(`--call-lib-path` worker);**禁止**父进程 `CallLibPath` / `Setenv` / `legacySSEBridgeMu`。未声明非流式 → `legacy_serial`(仍父锁)。 +3. **控制/读取分离**:`/_runtime/*`(cancel、events、task get)不进入解释器锁;`short`/`read`/`control` 走独立 admission 槽与隔离 worker,不与父进程 `INVOKE_LOCK` 串行。 +4. **订阅 ≠ 取消**:`sse-live` 观察者 `ctx.Done()` 默认**只结束订阅**,不 `runtime.cancel`。仅显式 header `X-Marqdo-Cancel-On-Disconnect: 1` 才 disconnect=cancel。同步 `waitIsolatedJSON` 可保留 disconnect 取消。重连:`GET /_runtime/tasks/{id}/events` + `Last-Event-ID` / `after_seq`。 +5. **协议**:`InvokeRequestV2` / worker env + NDJSON `MARQDO_EVENT_FORWARD` + `--emit-result`(首期);`/_runtime/*` 控制面。 +6. **能力探测**:`runtime.isolated_execution=1`、`runtime.task_control_v2`、`runtime.event_replay`、`view.analysis_cache_v2`、`runtime.read_lane=1`。 +7. **发布**:`expected_generation` CAS + publish journal;逻辑文档 ID 与物理 generation 路径解耦。 ## 后果 - Execute / live SSE 不再抢进程级 SSE 桥;双流可并行(MR-01)。 +- 声明的 short/read/control 不再与长流抢父进程 `INVOKE_LOCK`;产品 cancel 应优先 `/_runtime/tasks/{id}/cancel`。 - Legacy 未声明非流式路径仍可走父进程锁(ADR 0008)。 -- 产品(qdagent)cancel / Last-Event-ID 接线仍为后续;不阻碍本框架发版。 +- 产品(qdagent)`turn_events` / Last-Event-ID / cancel CAS 接线由 qdagent 验收;框架侧 disconnect≠cancel 与无锁控制面已落地。 ## 验收(摘要) -MR-01 绿:双假上游 60s 流不混字、短读全 200、两 worker `--call-lib-path`、第三路槽满 429/503、`runtime.isolated_execution=1`。其余见设计文档 §12。 +MR-01 绿:双假上游 60s 流不混字、短读全 200、两 worker `--call-lib-path`、第三路槽满 429/503、`runtime.isolated_execution=1`、`runtime.read_lane=1`。观察者断连后任务仍跑完并可经 `/_runtime` 重放。其余见设计文档 §12。 diff --git a/plugins/web/internal/httpx/routes_invoke.go b/plugins/web/internal/httpx/routes_invoke.go index d5f2e6c..229e98b 100644 --- a/plugins/web/internal/httpx/routes_invoke.go +++ b/plugins/web/internal/httpx/routes_invoke.go @@ -38,6 +38,7 @@ type invokeRoute struct { BodyMode string ReturnMode string Class string + Path string } func parseInvokeRoute(v any) invokeRoute { @@ -66,6 +67,7 @@ func (st *state) mountInvokeRoutes(mux *http.ServeMux) { for _, key := range sortedKeys(st.invokeRoutes) { cfg := parseInvokeRoute(st.invokeRoutes[key]) path := routePathKey(key) + cfg.Path = path method := cfg.Method if method == "" { method = http.MethodPost @@ -140,6 +142,25 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo payload["api_key"] = key } } + if last := strings.TrimSpace(r.Header.Get("Last-Event-ID")); last != "" { + if _, exists := payload["last_event_id"]; !exists { + payload["last_event_id"] = last + } + } + // Merge Go ServeMux path wildcards (e.g. /turns/{id}/events → id / turn_id). + if route.Path != "" { + pathVals := pathValuesOf(r, route.Path) + for k, v := range pathVals { + if _, exists := payload[k]; !exists { + payload[k] = v + } + } + if id, ok := pathVals["id"]; ok { + if _, exists := payload["turn_id"]; !exists { + payload["turn_id"] = id + } + } + } args := invokeArgsFromPayload(payload) @@ -150,11 +171,11 @@ func (st *state) handleInvoke(w http.ResponseWriter, r *http.Request, route invo class := resolveInvokeClass(route, liveSSE) switch class { - case "execute": - st.handleInvokeIsolated(w, r, route, args, liveSSE) - return - case "short", "read", "control": - st.handleInvokeParent(w, r, route, args) + case "execute", "short", "read", "control": + // Isolated workers: do not take parent INVOKE_LOCK (ADR 0009). + // control/read/short use separate admission slots; cancel/events also + // available lock-free via /_runtime/*. + st.handleInvokeIsolated(w, r, route, args, liveSSE, class) return default: // legacy_serial: parent CallLibPath (ADR 0008). Never isolate undeclared non-stream. @@ -243,14 +264,17 @@ func (st *state) handleInvokeParent(w http.ResponseWriter, r *http.Request, rout } } -// handleInvokeIsolated runs execute-class invokes on a Supervisor worker (no -// parent CallLibPath, no process Setenv, no legacySSEBridgeMu). -func (st *state) handleInvokeIsolated(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any, liveSSE bool) { +// handleInvokeIsolated runs admits on a Supervisor worker (no parent +// CallLibPath / Setenv / legacySSEBridgeMu). admissionClass is execute|short|read|control. +func (st *state) handleInvokeIsolated(w http.ResponseWriter, r *http.Request, route invokeRoute, args map[string]any, liveSSE bool, admissionClass string) { + if admissionClass == "" { + admissionClass = "execute" + } taskID := fmt.Sprintf("exec_%d", time.Now().UnixNano()) adm, err := runtimeQuery("admit", map[string]any{ "task_id": taskID, "idempotency_key": taskID, - "class": "execute", + "class": admissionClass, "payload": map[string]any{"fn": route.FnPath}, }) if err != nil { @@ -324,6 +348,14 @@ func (st *state) handleInvokeIsolated(w http.ResponseWriter, r *http.Request, ro st.waitIsolatedJSON(w, r, route, taskID, eventPath, cancelTok, emitResult) } +// cancelOnDisconnect reports whether the client opted into legacy +// disconnect=cancel (header X-Marqdo-Cancel-On-Disconnect: 1|true). +// Default is false: subscription close must not cancel the task (ADR 0009 / design §7.2). +func cancelOnDisconnect(r *http.Request) bool { + v := strings.TrimSpace(strings.ToLower(r.Header.Get("X-Marqdo-Cancel-On-Disconnect"))) + return v == "1" || v == "true" || v == "yes" +} + func (st *state) streamIsolatedSSE(w http.ResponseWriter, r *http.Request, route invokeRoute, taskID, eventPath, cancelTok, emitResult string) { w.Header().Set("Content-Type", "text/event-stream; charset=utf-8") w.Header().Set("Cache-Control", "no-cache") @@ -384,27 +416,43 @@ func (st *state) streamIsolatedSSE(w http.ResponseWriter, r *http.Request, route } } + doCancelOnDisconnect := cancelOnDisconnect(r) + for { select { case <-ctx.Done(): - _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) - _ = writeCancelToken(cancelTok) - writeEvent(map[string]any{ - "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted", - "payload": map[string]any{ - "reason": "client_disconnect", - "cancel_propagated": cancelTok != "", - "status": "stopping", - "task_id": taskID, - }, - }) - // Brief wait so worker can notice cancel and flush. - deadline := time.Now().Add(3 * time.Second) - for time.Now().Before(deadline) { - if workerDone(taskID, emitResult) { - break + // Default: observer gone ≠ cancel. Task keeps running; client may + // reattach via GET /_runtime/tasks/{id}/events (Last-Event-ID). + if doCancelOnDisconnect { + _, _ = runtimeQuery("cancel", map[string]any{"task_id": taskID}) + _ = writeCancelToken(cancelTok) + writeEvent(map[string]any{ + "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted", + "payload": map[string]any{ + "reason": "client_disconnect", + "cancel_propagated": cancelTok != "", + "status": "stopping", + "task_id": taskID, + }, + }) + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + if workerDone(taskID, emitResult) { + break + } + time.Sleep(50 * time.Millisecond) } - time.Sleep(50 * time.Millisecond) + } else { + writeEvent(map[string]any{ + "schema": "RuntimeEventV1", "schema_version": 1, "type": "run.interrupted", + "payload": map[string]any{ + "reason": "client_disconnect", + "cancel_propagated": false, + "status": "observer_closed", + "task_id": taskID, + "resume": "/_runtime/tasks/" + taskID + "/events", + }, + }) } finish(true) return diff --git a/plugins/web/internal/httpx/sse_bridge_test.go b/plugins/web/internal/httpx/sse_bridge_test.go index dc4d903..53769ad 100644 --- a/plugins/web/internal/httpx/sse_bridge_test.go +++ b/plugins/web/internal/httpx/sse_bridge_test.go @@ -45,7 +45,8 @@ func TestLegacySSEBridgeSingleFlight(t *testing.T) { } } -// M-R0: disconnect marks cancel; token file must not be deleted while holder waits. +// M-R0: cancel-token file must not be deleted while bridge holder waits. +// (sse-live observer disconnect no longer cancels by default — see cancelOnDisconnect.) func TestCancelTokenSurvivesUntilHolderExits(t *testing.T) { dir := t.TempDir() tok := filepath.Join(dir, "cancel.tok") diff --git a/src/workbench/capabilities.rs b/src/workbench/capabilities.rs index 96630d6..6c1c488 100644 --- a/src/workbench/capabilities.rs +++ b/src/workbench/capabilities.rs @@ -95,7 +95,8 @@ pub fn probe_capabilities(params: &Value) -> Value { // 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)); + // short/read/control HTTP invokes use isolated admission (no parent INVOKE_LOCK). + features.insert("runtime.read_lane".into(), json!(1)); #[cfg(feature = "view")] { features.insert("view.analysis_cache_v2".into(), json!(1)); diff --git a/tests/ext/isolated-execute-site/serve.mq.md b/tests/ext/isolated-execute-site/serve.mq.md index c9ddabb..8ac23d1 100644 --- a/tests/ext/isolated-execute-site/serve.mq.md +++ b/tests/ext/isolated-execute-site/serve.mq.md @@ -5,12 +5,21 @@ description: Dual-stream execute + short models for ADR 0009 gold sample. import: web: ext/web/web.mq.md site: ./site.mq.md + sys: lib/sys.mq.md --- # main +**port_s = > sys.env_get name="MARQDO_SITE_PORT"** +**port = 18220** +1. `port_s` + **port = `port_s`** +2. * + **_ = 1** + **pg = > web.page title="isolated-execute"** -**app = > web.app page=`pg` host="127.0.0.1" port=18220** +**app = > web.app page=`pg` host="127.0.0.1" port=`port`** **app = > web.route app=`app` path="/v1/chat/completions" method="POST" fn="site.chat" request="json" response="sse-live" class="execute"** **app = > web.route app=`app` path="/v1/models" method="GET" fn="site.models" request="query" response="json" class="short"** +**app = > web.route app=`app` path="/v1/ping" method="GET" fn="site.ping" request="query" response="json" class="control"** > `app`.listen diff --git a/tests/ext/isolated-execute-site/site.mq.md b/tests/ext/isolated-execute-site/site.mq.md index 19a622c..ecb22ec 100644 --- a/tests/ext/isolated-execute-site/site.mq.md +++ b/tests/ext/isolated-execute-site/site.mq.md @@ -70,3 +70,16 @@ Short-class read: list models without holding an execute slot. | list | True | *out* + +# ping + + `payload`=None + +Control-class noop: must succeed under dual execute without parent INVOKE_LOCK. + +`out` = + +| ok | lane | +|----|------| +| True | control | + +*out* diff --git a/tests/isolated_execute_mr01.rs b/tests/isolated_execute_mr01.rs index 11db49d..8d8b711 100644 --- a/tests/isolated_execute_mr01.rs +++ b/tests/isolated_execute_mr01.rs @@ -417,5 +417,226 @@ fn mr01_dual_isolated_execute_and_short_reads() { assert!(sok > 10, "expected many short 200s, got ok={sok} fail={sfail}"); assert_eq!(sfail, 0, "short reads failed: {sfail}"); + assert_eq!( + caps["features"]["runtime.read_lane"], + 1, + "read_lane must be on; caps={caps}" + ); + + let _ = std::fs::remove_dir_all(&runtime_dir); +} + +/// Observer disconnect must not cancel the execute task (default). +#[test] +fn disconnect_keeps_running_and_replay() { + if TcpListener::bind("127.0.0.1:0").is_err() { + eprintln!("skip disconnect-keeps-running: local sockets unavailable"); + return; + } + ensure_plugins(); + + let secs: u64 = 6; + let (base_a, stop_a, join_a) = spawn_fake_sse("A", secs, 10); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let site = root.join("tests/ext/isolated-execute-site"); + let runtime_dir = std::env::temp_dir().join(format!("mq-disc-rt-{}", std::process::id())); + let _ = std::fs::create_dir_all(&runtime_dir); + + let bin = env!("CARGO_BIN_EXE_marqdo"); + let mut child: Child = Command::new(bin) + .args(["run", "serve.mq.md"]) + .current_dir(&site) + .env("MARQDO_EXT", root.join("ext")) + .env("MARQDO_WEB_PLUGIN", std::env::var_os("MARQDO_WEB_PLUGIN").unwrap()) + .env("MARQDO_LLM_PLUGIN", std::env::var_os("MARQDO_LLM_PLUGIN").unwrap()) + .env("MARQDO_RUNTIME_DIR", &runtime_dir) + .env("MARQDO_SITE_PORT", "18221") + .env("OPENAI_API_KEY", "mr01-key") + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn site"); + + let base = "http://127.0.0.1:18221"; + if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(30)) { + let _ = child.kill(); + panic!("site did not start for disconnect test"); + } + + let chat_url = format!("{base}/v1/chat/completions"); + let body = format!( + r#"{{"model":"mr01","stream":true,"base_url":"{base_a}","messages":[{{"role":"user","content":"hi"}}]}}"# + ); + // Observer disconnects after ~1.2s; task must keep running. + let out = Command::new("curl") + .args([ + "-s", + "-N", + "--max-time", + "1", + "-H", + "Content-Type: application/json", + "-d", + &body, + &chat_url, + ]) + .output() + .expect("curl disconnect"); + let text = String::from_utf8_lossy(&out.stdout); + let mut task_id = String::new(); + for line in text.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("data: ") { + if let Ok(v) = serde_json::from_str::(rest) { + if v.get("type").and_then(|t| t.as_str()) == Some("run.started") { + if let Some(tid) = v.pointer("/payload/task_id").and_then(|x| x.as_str()) { + task_id = tid.to_string(); + } + } + } + } + } + assert!(!task_id.is_empty(), "missing task_id in early SSE; raw={text}"); + + // Wait until task finishes (observer already gone). + let mut terminal = false; + let deadline = Instant::now() + Duration::from_secs(secs + 8); + while Instant::now() < deadline { + let get_url = format!("{base}/_runtime/tasks/{task_id}"); + let out = Command::new("curl") + .args(["-s", &get_url]) + .output() + .expect("runtime get"); + let body = String::from_utf8_lossy(&out.stdout); + if body.contains("\"completed\"") + || body.contains("\"succeeded\"") + || body.contains("\"failed\"") + || body.contains("\"cancelled\"") + { + assert!( + !body.contains("\"cancelled\""), + "disconnect must not cancel task: {body}" + ); + terminal = true; + break; + } + thread::sleep(Duration::from_millis(200)); + } + assert!(terminal, "task {task_id} did not finish after observer disconnect"); + + // Replay via events (JSON after_seq=0). + let ev_url = format!("{base}/_runtime/tasks/{task_id}/events?after_seq=0"); + let ev = Command::new("curl") + .args(["-s", &ev_url]) + .output() + .expect("events"); + let ev_body = String::from_utf8_lossy(&ev.stdout); + assert!( + ev_body.contains('A') || ev_body.contains("delta") || ev_body.contains("event"), + "replay empty: {ev_body}" + ); + + stop_a.store(true, Ordering::Relaxed); + let _ = join_a.join(); + let _ = child.kill(); + let _ = child.wait(); + let _ = std::fs::remove_dir_all(&runtime_dir); +} + +/// Control + short reads stay 200 while two execute streams hold slots. +#[test] +fn control_under_dual_execute() { + if TcpListener::bind("127.0.0.1:0").is_err() { + eprintln!("skip control-under-dual-execute: local sockets unavailable"); + return; + } + ensure_plugins(); + + let secs: u64 = 8; + let (base_a, stop_a, join_a) = spawn_fake_sse("A", secs, 10); + let (base_b, stop_b, join_b) = spawn_fake_sse("B", secs, 10); + + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let site = root.join("tests/ext/isolated-execute-site"); + let runtime_dir = std::env::temp_dir().join(format!("mq-ctl-rt-{}", std::process::id())); + let _ = std::fs::create_dir_all(&runtime_dir); + + let bin = env!("CARGO_BIN_EXE_marqdo"); + let mut child: Child = Command::new(bin) + .args(["run", "serve.mq.md"]) + .current_dir(&site) + .env("MARQDO_EXT", root.join("ext")) + .env("MARQDO_WEB_PLUGIN", std::env::var_os("MARQDO_WEB_PLUGIN").unwrap()) + .env("MARQDO_LLM_PLUGIN", std::env::var_os("MARQDO_LLM_PLUGIN").unwrap()) + .env("MARQDO_RUNTIME_DIR", &runtime_dir) + .env("MARQDO_SITE_PORT", "18222") + .env("OPENAI_API_KEY", "mr01-key") + .stdout(Stdio::null()) + .stderr(Stdio::piped()) + .spawn() + .expect("spawn site"); + + let base = "http://127.0.0.1:18222"; + if !wait_http_ok(&format!("{base}/v1/models"), Duration::from_secs(30)) { + let _ = child.kill(); + panic!("site did not start for control test"); + } + + let chat_url = format!("{base}/v1/chat/completions"); + let body_tmpl = r#"{"model":"mr01","stream":true,"base_url":"__BASE__","messages":[{"role":"user","content":"hi"}]}"#; + let t_a = { + let u = chat_url.clone(); + let b = body_tmpl.to_string(); + let ba = base_a.clone(); + thread::spawn(move || { + let _ = collect_sse_deltas(&u, &b, &ba); + }) + }; + let t_b = { + let u = chat_url.clone(); + let b = body_tmpl.to_string(); + let bb = base_b.clone(); + thread::spawn(move || { + let _ = collect_sse_deltas(&u, &b, &bb); + }) + }; + + thread::sleep(Duration::from_secs(1)); + let mut ok_n = 0u32; + let mut fail_n = 0u32; + let start = Instant::now(); + while start.elapsed() < Duration::from_secs(3) { + for path in ["/v1/models", "/v1/ping"] { + let url = format!("{base}{path}"); + let t0 = Instant::now(); + let out = Command::new("curl") + .args(["-s", "-o", "/dev/null", "-w", "%{http_code}", &url]) + .output(); + let elapsed = t0.elapsed(); + match out { + Ok(o) if String::from_utf8_lossy(&o.stdout) == "200" => { + assert!( + elapsed < Duration::from_millis(1500), + "{path} p95 budget; took {elapsed:?}" + ); + ok_n += 1; + } + _ => fail_n += 1, + } + } + thread::sleep(Duration::from_millis(80)); + } + assert!(ok_n > 4, "expected control/short 200s, ok={ok_n} fail={fail_n}"); + assert_eq!(fail_n, 0, "control/short failed under dual execute: {fail_n}"); + + let _ = t_a.join(); + let _ = t_b.join(); + stop_a.store(true, Ordering::Relaxed); + stop_b.store(true, Ordering::Relaxed); + let _ = join_a.join(); + let _ = join_b.join(); + let _ = child.kill(); + let _ = child.wait(); let _ = std::fs::remove_dir_all(&runtime_dir); }