feat(workbench): F14 coalesce, snapshot manifest, and sse drain evidence
Hold analysis locks across compile for concurrent same-snapshot reads, emit SnapshotManifestV1 for app retention, and add Go drainForward tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
69c4e74872
commit
8cf5288481
8 files changed
+389
-58
No files matched your search
+110
-29
@@ -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<HashMap<String, CacheEntry>> {
|
||||
static C: OnceLock<Mutex<HashMap<String, CacheEntry>>> = OnceLock::new();
|
||||
C.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
struct CacheState {
|
||||
entries: HashMap<String, CacheEntry>,
|
||||
/// project_key → refcount of leaders currently analyzing.
|
||||
inflight: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
/// Fingerprint of authorized project sources (shallow: entry + .mq.md under root, capped).
|
||||
fn cache() -> &'static (Mutex<CacheState>, Condvar) {
|
||||
static C: OnceLock<(Mutex<CacheState>, 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();
|
||||
}
|
||||
@@ -92,12 +92,20 @@ pub fn build_document_view(req: &DocumentViewRequest) -> Result<Value, Value> {
|
||||
let title = title_from_source(&source, &req.document);
|
||||
|
||||
// Semantic projection — compile_project does not load plugins / evaluate.
|
||||
// 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<Value, Value> {
|
||||
"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<Value, Value> {
|
||||
"refs": refs,
|
||||
"diagnostics": diagnostics,
|
||||
"completeness": completeness,
|
||||
"snapshot": snapshot,
|
||||
"capabilities": {"read_only": true, "has_semantics": true, "executed": false}
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -111,22 +111,14 @@ pub fn resolve_reference(params: &Value) -> Result<Value, Value> {
|
||||
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),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in new issue
Block a user