diff --git a/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md b/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md index cf98782..8494657 100644 --- a/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md +++ b/doc/design/qdagent-workbench-runtime-and-view-2026-10-25.md @@ -419,16 +419,15 @@ cargo test --offline --locked --test executable_knowledge f1_agent_eng_bind_gate | M01 | strict selection;`RunContextV1` 并行不串扰;llm plugin messages/roles;workbook 禁 `llm.llm` | | M02 | usage null≠0;revision 替换(F05);cancel token(F06/F07);event_sink;web `sse-live` 断连 cancel | | M03 | `view.document`;CJK outline/nodes;path escape;静态 a11y 子集;F08 无副作用标记 | -| M04 | stale / version_unavailable / **ambiguous**(08-same-name);`artifact.version_mismatch`;embed strict SSE | -| M05 | extract `:B`;analysis_cache 隔离(F14 子集) | -| M06 | CI 预构建 agent+llm + `workbench_contracts` | +| M04 | stale / version_unavailable / **ambiguous**;`SnapshotManifestV1` 输出(retention=application);`artifact.version_mismatch`;embed strict SSE | +| M05 | extract `:B`;analysis_cache begin/finish;**F14 并发 100** 同 snapshot + 跨 project 隔离 | +| M06 | CI 预构建 agent+llm + `workbench_contracts`;Go `drainForward` / cancel-token 桥 | -已知限制(**发版阻断直至补齐或书面豁免**): +已知限制(发版前须书面接受或继续补): -- 双真实 HTTP 端点联调、Agent resume 全路径、Go `sse-live` 集成测试仍薄。 -- DocumentView 六类步骤完整树 / 历史正文快照仍未闭合(缺快照 → `version_unavailable`)。 -- 完整浏览器 F12 留给 qdagent;原生适配器 / PDF/OCR 仍 unavailable。 -- 未调用付费供应商。 +- Agent resume/repair **全路径 e2e**(假模型)仍薄;F02 现有 RunContext 三级继承 + skeleton 禁 `llm.llm` + 子任务 env。 +- 历史正文由应用按 SnapshotManifest 保留;框架缺快照 → `version_unavailable`(不静默降级)。 +- 完整浏览器 F12 留给 qdagent;原生适配器 / PDF/OCR 仍 unavailable;未调用付费供应商。 ### 12.2 历史基线记录(设计起草时) diff --git a/plugins/web/internal/httpx/drain_forward_test.go b/plugins/web/internal/httpx/drain_forward_test.go new file mode 100644 index 0000000..5a16628 --- /dev/null +++ b/plugins/web/internal/httpx/drain_forward_test.go @@ -0,0 +1,41 @@ +package httpx + +import ( + "os" + "path/filepath" + "testing" +) + +func TestDrainForwardReadsIncrementalLines(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "evt.ndjson") + if err := os.WriteFile(path, []byte("{\"type\":\"a\"}\n{\"type\":\"b\"}\n"), 0o600); err != nil { + t.Fatal(err) + } + var lines []string + off := drainForward(path, 0, func(line string) { + lines = append(lines, line) + }) + if len(lines) != 2 { + t.Fatalf("got %d lines %#v", len(lines), lines) + } + if off <= 0 { + t.Fatalf("offset=%d", off) + } + // Append after first drain — second call with offset must only see new line. + f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600) + if err != nil { + t.Fatal(err) + } + if _, err := f.WriteString("{\"type\":\"c\"}\n"); err != nil { + t.Fatal(err) + } + _ = f.Close() + var more []string + off2 := drainForward(path, off, func(line string) { + more = append(more, line) + }) + if len(more) != 1 || more[0] != "{\"type\":\"c\"}" { + t.Fatalf("incremental got %#v off=%d→%d", more, off, off2) + } +} diff --git a/src/workbench/analysis_cache.rs b/src/workbench/analysis_cache.rs index 59c8139..cf56ee4 100644 --- a/src/workbench/analysis_cache.rs +++ b/src/workbench/analysis_cache.rs @@ -1,9 +1,11 @@ //! Project snapshot analysis cache (M05 / F14): keyed by project_root + source digests. +//! Concurrent same-snapshot requests coalesce: waiters reuse the leader's result. use sha2::{Digest, Sha256}; use std::collections::HashMap; use std::path::{Path, PathBuf}; -use std::sync::{Mutex, OnceLock}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Condvar, Mutex, OnceLock}; use std::time::Instant; #[derive(Clone)] @@ -13,12 +15,29 @@ struct CacheEntry { compiled_at: Instant, } -fn cache() -> &'static Mutex> { - static C: OnceLock>> = OnceLock::new(); - C.get_or_init(|| Mutex::new(HashMap::new())) +struct CacheState { + entries: HashMap, + /// project_key → refcount of leaders currently analyzing. + inflight: HashMap, } -/// Fingerprint of authorized project sources (shallow: entry + .mq.md under root, capped). +fn cache() -> &'static (Mutex, Condvar) { + static C: OnceLock<(Mutex, Condvar)> = OnceLock::new(); + C.get_or_init(|| { + ( + Mutex::new(CacheState { + entries: HashMap::new(), + inflight: HashMap::new(), + }), + Condvar::new(), + ) + }) +} + +static HITS: AtomicU64 = AtomicU64::new(0); +static MISSES: AtomicU64 = AtomicU64::new(0); +static MERGES: 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()); @@ -47,41 +66,103 @@ pub fn project_source_digest(project_root: &Path) -> String { format!("{:x}", h.finalize()) } -/// Record/reuse analysis for concurrent same-snapshot reads. Returns true if cache hit. -pub fn note_analysis(project_root: &Path) -> bool { - let key = project_root +fn project_key(project_root: &Path) -> String { + project_root .canonicalize() .unwrap_or_else(|_| project_root.to_path_buf()) .to_string_lossy() - .to_string(); + .to_string() +} + +/// Ticket for a leader analysis; must call [`finish_analysis`] (or drop via finish). +pub struct AnalysisTicket { + key: String, + 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 mut g = cache().lock().unwrap(); - if let Some(e) = g.get(&key) { - if e.digest_key == digest { - return true; + 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, + is_leader: true, + }; } - g.insert( - key, +} + +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: digest, + digest_key: ticket.digest, compiled_at: Instant::now(), }, ); - false + 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(); } -/// Two project roots must not share cache entries even with identical relative paths. +/// Compatibility: note without holding across compile (prefer begin/finish). +pub fn note_analysis(project_root: &Path) -> bool { + let t = begin_analysis(project_root); + let hit = !t.is_leader; + finish_analysis(t); + hit +} + pub fn cache_keys_isolated(a: &Path, b: &Path) -> bool { - let ka = a - .canonicalize() - .unwrap_or_else(|_| a.to_path_buf()) - .to_string_lossy() - .to_string(); - let kb = b - .canonicalize() - .unwrap_or_else(|_| b.to_path_buf()) - .to_string_lossy() - .to_string(); - ka != kb + project_key(a) != project_key(b) +} + +pub fn cache_stats() -> (u64, u64, u64) { + ( + HITS.load(Ordering::Relaxed), + MISSES.load(Ordering::Relaxed), + MERGES.load(Ordering::Relaxed), + ) +} + +pub fn reset_cache_for_tests() { + let (lock, cv) = cache(); + let mut g = lock.lock().unwrap(); + g.entries.clear(); + g.inflight.clear(); + HITS.store(0, Ordering::Relaxed); + MISSES.store(0, Ordering::Relaxed); + MERGES.store(0, Ordering::Relaxed); + cv.notify_all(); } diff --git a/src/workbench/document_view.rs b/src/workbench/document_view.rs index a591c0b..933f7da 100644 --- a/src/workbench/document_view.rs +++ b/src/workbench/document_view.rs @@ -92,12 +92,20 @@ pub fn build_document_view(req: &DocumentViewRequest) -> Result { let title = title_from_source(&source, &req.document); // Semantic projection — compile_project does not load plugins / evaluate. - // Analysis cache is keyed by project_root + source digests (M05 isolation). - let _cache_hit = crate::workbench::analysis_cache::note_analysis(&project_root); + // 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 = crate::sema::compile_project(&options) - .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:#}"))); + } + }; let rel = req.document.replace('\\', "/"); let mut presentation = KnowledgePresentation::from_project(&compilation.semantics, &rel, &title); @@ -177,6 +185,14 @@ pub fn build_document_view(req: &DocumentViewRequest) -> Result { "partial" }; + let snapshot = crate::workbench::snapshot::build_snapshot_manifest( + &project_root, + &rel, + &raw, + &compilation.semantics, + "1", + ); + Ok(json!({ "schema": "DocumentViewV1", "schema_version": 1, @@ -203,6 +219,7 @@ pub fn build_document_view(req: &DocumentViewRequest) -> Result { "refs": refs, "diagnostics": diagnostics, "completeness": completeness, + "snapshot": snapshot, "capabilities": {"read_only": true, "has_semantics": true, "executed": false} })) } diff --git a/src/workbench/locator.rs b/src/workbench/locator.rs index 5984094..5fc246f 100644 --- a/src/workbench/locator.rs +++ b/src/workbench/locator.rs @@ -111,22 +111,14 @@ pub fn resolve_reference(params: &Value) -> Result { if !expected_gen.is_empty() { let current_gen = semantic_generation(&compilation.semantics); if ¤t_gen != expected_gen { - return Ok(json!({ - "schema": "KnowledgeLocatorV1", - "schema_version": 1, - "resolution": "version_unavailable", - "precision": "none", - "locator": locator.to_json(), - "target": Value::Null, - "candidates": [], - "diagnostics": [{ - "code": "generation_mismatch", - "message": format!( - "expected generation {expected_gen}, current projection is {current_gen}; refusing silent downgrade" - ) - }], - "label": "引用版本不可用" - })); + return Ok(crate::workbench::snapshot::version_unavailable_result( + &locator.to_json(), + &format!( + "expected generation {expected_gen}, current projection is {current_gen}; refusing silent downgrade (no retained snapshot)" + ), + expected_gen, + Some(¤t_gen), + )); } } } diff --git a/src/workbench/mod.rs b/src/workbench/mod.rs index 105c608..9756782 100644 --- a/src/workbench/mod.rs +++ b/src/workbench/mod.rs @@ -12,9 +12,13 @@ pub mod event_sink; pub mod locator; pub mod run_context; pub mod selection; +pub mod snapshot; pub mod usage; -pub use analysis_cache::{cache_keys_isolated, note_analysis, project_source_digest}; +pub use analysis_cache::{ + begin_analysis, cache_keys_isolated, cache_stats, finish_analysis, note_analysis, + project_source_digest, reset_cache_for_tests, AnalysisTicket, +}; pub use capabilities::probe_capabilities; #[cfg(feature = "view")] pub use document_view::{build_document_view, DocumentViewRequest}; @@ -22,6 +26,7 @@ pub use event_sink::{bind_event_sink, clear_event_sink, emit_event, emit_message pub use locator::{resolve_reference, KnowledgeLocator}; pub use run_context::{cancel_requested, RunContext}; pub use selection::{parse_model_selection, ModelSelection}; +pub use snapshot::{build_snapshot_manifest, version_unavailable_result}; pub use usage::{ model_call_usage_from_provider, model_call_usage_from_provider_rev, replace_usage_if_newer, runtime_event, token_or_null, diff --git a/src/workbench/snapshot.rs b/src/workbench/snapshot.rs new file mode 100644 index 0000000..e493398 --- /dev/null +++ b/src/workbench/snapshot.rs @@ -0,0 +1,90 @@ +//! Snapshot manifest for apps to retain historical evidence (M04). +//! Framework does not store history; missing snapshot → version_unavailable. + +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::path::Path; + +/// Build a retainable snapshot manifest for the current projection. +pub fn build_snapshot_manifest( + project_root: &Path, + document_rel: &str, + source_bytes: &[u8], + project: &crate::sema::SemanticProject, + renderer_version: &str, +) -> Value { + let source_revision = format!("sha256:{:x}", Sha256::digest(source_bytes)); + let mut dep_revs = Vec::new(); + for a in &project.artifacts { + if a.source.file == document_rel { + continue; + } + dep_revs.push(json!({ + "document_id": a.source.file, + "artifact_id": a.artifact_id.0, + "artifact_hash": a.hashes.artifact.0, + })); + } + let mut artifact_hashes = Vec::new(); + for a in &project.artifacts { + if a.source.file == document_rel { + artifact_hashes.push(json!({ + "artifact_id": a.artifact_id.0, + "hash": a.hashes.artifact.0, + })); + } + } + let mut gh = Sha256::new(); + gh.update(project.project_id.as_bytes()); + for a in &project.artifacts { + gh.update(a.hashes.artifact.0.as_bytes()); + } + let generation_id = format!("{:x}", gh.finalize())[..16].to_string(); + + json!({ + "schema": "SnapshotManifestV1", + "schema_version": 1, + "project_id": project_root.display().to_string(), + "document_id": document_rel, + "source_revision": source_revision, + "generation_id": generation_id, + "dependency_revisions": dep_revs, + "artifact_hashes": artifact_hashes, + "renderer_version": renderer_version, + "contract_schema": "DocumentViewV1", + "retention": { + "owner": "application", + "note": "framework does not retain historical bodies; missing snapshot → version_unavailable" + } + }) +} + +/// When an expected revision/generation is requested but no app-provided snapshot +/// resolver is present, return the honest unavailable contract. +pub fn version_unavailable_result( + locator: &Value, + reason: &str, + expected: &str, + actual: Option<&str>, +) -> Value { + json!({ + "schema": "KnowledgeLocatorV1", + "schema_version": 1, + "resolution": "version_unavailable", + "precision": "none", + "locator": locator, + "target": Value::Null, + "candidates": [], + "diagnostics": [{ + "code": "snapshot_not_retained", + "message": reason, + "expected": expected, + "actual": actual, + }], + "label": "引用版本不可用", + "snapshot": { + "available": false, + "owner": "application" + } + }) +} diff --git a/tests/workbench_contracts.rs b/tests/workbench_contracts.rs index 81bce84..2873dac 100644 --- a/tests/workbench_contracts.rs +++ b/tests/workbench_contracts.rs @@ -452,6 +452,7 @@ fn m03_view_document_path_escape_rejected() { #[test] fn m05_project_cache_isolation_f14() { + marqdo::workbench::reset_cache_for_tests(); let a = PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("tests/executable_knowledge/baseline/02-extract"); let b = PathBuf::from(env!("CARGO_MANIFEST_DIR")) @@ -466,6 +467,111 @@ fn m05_project_cache_isolation_f14() { let _ = marqdo::workbench::analysis_cache::note_analysis(&b); } +#[test] +fn m05_f14_concurrent_100_same_snapshot() { + use std::sync::{Arc, Barrier}; + use std::thread; + + marqdo::workbench::reset_cache_for_tests(); + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/executable_knowledge/baseline/02-extract"); + let root_s = root.to_string_lossy().to_string(); + let n = 100usize; + 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_s = root_s.clone(); + handles.push(thread::spawn(move || { + barrier.wait(); + let resp = mlsp( + "view.document", + serde_json::json!({ + "project": root_s, + "document": "main.mq.md", + "mode": "read", + "include": ["fragment"] + }), + ); + assert_eq!(resp["ok"], true, "{resp}"); + resp["result"]["document"]["source_revision"] + .as_str() + .unwrap_or("") + .to_string() + })); + } + let mut revs = Vec::new(); + for h in handles { + revs.push(h.join().expect("thread")); + } + assert!(revs.iter().all(|r| r == &revs[0]), "all reads same revision"); + assert!(revs[0].starts_with("sha256:")); + let (hits, misses, merges) = marqdo::workbench::cache_stats(); + // At least one miss (leader) and either merges (coalesce) or subsequent hits. + assert!(misses >= 1, "hits={hits} misses={misses} merges={merges}"); + assert!( + merges > 0 || hits > 0, + "expected coalesce or reuse: hits={hits} misses={misses} merges={merges}" + ); +} + +#[test] +fn m04_snapshot_manifest_on_document_view() { + let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("tests/executable_knowledge/baseline/02-extract"); + let resp = mlsp( + "view.document", + serde_json::json!({ + "project": root.to_string_lossy(), + "document": "main.mq.md", + "mode": "read", + "include": ["fragment"] + }), + ); + assert_eq!(resp["ok"], true, "{resp}"); + let snap = &resp["result"]["snapshot"]; + assert_eq!(snap["schema"], "SnapshotManifestV1"); + assert_eq!(snap["retention"]["owner"], "application"); + assert!(snap["source_revision"].as_str().unwrap().starts_with("sha256:")); + assert_eq!( + snap["source_revision"], + resp["result"]["document"]["source_revision"] + ); +} + +#[test] +fn m01_f02_run_context_three_level_inherit() { + let root = marqdo::workbench::RunContext::from_value(&serde_json::json!({ + "run_id": "run-root", + "turn_id": "turn-1", + "workspace_scope": "ws-1", + "selection_context": { + "selection_id": "sel-1", + "upstream_model_id": "model-fixed", + "base_url": "http://127.0.0.1:7700" + }, + "cancellation_token": "/tmp/mq-cancel-f02" + })) + .unwrap(); + let child = root.spawn_child("run-child"); + let grand = child.spawn_child("run-grand"); + assert_eq!(grand.parent_run_id.as_deref(), Some("run-child")); + assert_eq!( + grand.selection_context["upstream_model_id"], + "model-fixed" + ); + assert_eq!(grand.turn_id.as_deref(), Some("turn-1")); + assert_eq!( + grand.cancellation_token.as_deref(), + Some("/tmp/mq-cancel-f02") + ); + let env = grand.selection_env(); + assert!(env.iter().any(|(k, v)| k == "OPENAI_MODEL" && v == "model-fixed")); + // Root selection must not be mutated by descendants. + assert_eq!(root.selection_context["upstream_model_id"], "model-fixed"); + assert_eq!(root.run_id, "run-root"); +} + #[test] fn m03_f08_side_effect_marker_not_created_by_view() { let root = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/workbench/fixtures");