Stack t2: a font read while the search's guards change is never returned, and the read-only MCP test cleans up after a failure

A font lookup that finds the folders or guards changed during its read now
searches again under the new ones (a few times at most) instead of returning a
font a new guard may refuse. The MCP read-only test works in a folder of its
own, removed also when it fails. docs/mcp.md says a refusal -WBLOCK reports at
its own prompt is only in output.
This commit is contained in:
Tanish Manku
2026-11-20 01:45:03 -07:00
parent 43d7a19256
commit ecf231d02a
4 changed files with 122 additions and 14 deletions
+20 -7
View File
@@ -245,9 +245,21 @@ pub fn generation() -> u64 {
table().generation
}
/// Most times [`find`] looks again because the folders or guards changed while it read.
const MAX_LOOKUPS: usize = 4;
/// The SHX font file a style or linetype names, if CADCraft can find and read it.
///
/// A font read while what the search may open changed is never given: the read could have used a
/// folder or guard since dropped (a folder whose new guard refuses the file). The search runs again
/// under the new ones, and a table that keeps changing gives no font.
pub fn find(name: &str) -> Option<Arc<ShxFont>> {
let mut k = key(name)?;
(0..MAX_LOOKUPS).find_map(|_| lookup(name)).flatten()
}
/// One search for [`find`]: `None` when the table changed while the file was read.
fn lookup(name: &str) -> Option<Option<Arc<ShxFont>>> {
let Some(mut k) = key(name) else { return Some(None) };
let (provider, folders, (guarded, overflow), generation) = {
let t = table();
// The font map renames once (a map can't loop).
@@ -255,10 +267,10 @@ pub fn find(name: &str) -> Option<Arc<ShxFont>> {
k = to;
}
if let Some(f) = t.registered.get(&k) {
return Some(f.clone());
return Some(Some(f.clone()));
}
if let Some(r) = t.resolved.get(&k) {
return r.clone();
return Some(r.clone());
}
let folders: Vec<PathBuf> = t.drawing_dirs.iter().chain(t.font_dirs.iter()).chain(t.search_path.iter()).cloned().collect();
let guarded: Vec<(PathBuf, Vec<OpenGuard>)> =
@@ -290,9 +302,10 @@ pub fn find(name: &str) -> Option<Arc<ShxFont>> {
.and_then(|b| ShxFont::parse(&b).ok())
.map(Arc::new);
let mut t = table();
// Something changed while the file was read: keep the result out of the new cache.
// Something changed while the file was read: the result may come from a folder or under a
// guard that no longer applies, so it is neither kept nor given.
if t.generation != generation {
return font;
return None;
}
if t.resolved.len() >= MAX_FONTS * 4 {
t.resolved.clear();
@@ -301,11 +314,11 @@ pub fn find(name: &str) -> Option<Arc<ShxFont>> {
let size = font.as_ref().map_or(0, |f| f.data.len());
if t.loaded_bytes.saturating_add(size) > MAX_LOADED_BYTES {
// Over the memory bound: used, not kept.
return font;
return Some(font);
}
t.loaded_bytes += size;
t.resolved.insert(k, font.clone());
font
Some(font)
}
/// Most directory entries looked at for a font file whose name differs only in case.
+67
View File
@@ -0,0 +1,67 @@
//! A guard given to a folder while a font search reads it: the search never gives a font that the
//! new guard refuses.
// Integration tests: unwrapping on failure is fine here, unlike in shipped code (AGENTS.md).
#![allow(clippy::unwrap_used, clippy::expect_used)]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use cadcraft_fonts::shx;
const FONT: &str = "*0,4,race\n6,2,0,0\n*65,7,UCA\n1,064,040,06C,2,020,0\n";
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
/// test ends, also when it fails.
struct TestDir(PathBuf);
impl Drop for TestDir {
/// Removes the folder and all it holds.
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A new folder for `tag`: creating it must not find one already there.
fn fresh_dir(tag: &str) -> TestDir {
let mut n = 0u32;
loop {
let dir = std::env::temp_dir().join(format!("cadcraft-shx-{tag}-{}-{n}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => return TestDir(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
Err(e) => panic!("{}: {e}", dir.display()),
}
}
}
/// A provider with no fonts that, the first time it is asked, gives `dir` a guard refusing every
/// file. The search asks it after taking its view of the folders and before reading them, so the
/// guard arrives while the search is under way.
struct LateGuard {
dir: PathBuf,
fired: AtomicBool,
}
impl shx::FontProvider for LateGuard {
fn load(&self, _file_name: &str) -> Option<Vec<u8>> {
if !self.fired.swap(true, Ordering::SeqCst) {
shx::add_drawing_dir_guarded(&self.dir, "late", Arc::new(|_: &Path| false));
}
None
}
}
#[test]
fn a_guard_given_during_a_search_refuses_the_font_it_was_reading() {
let bytes = shx::compile(FONT).unwrap();
let owner = fresh_dir("race");
let dir = owner.0.clone();
std::fs::write(dir.join("cadcraft-race.shx"), &bytes).unwrap();
shx::set_font_dirs(vec![dir.clone()]);
assert!(shx::find("cadcraft-race.shx").is_some(), "found while nothing guards the folder");
shx::set_provider(Some(Arc::new(LateGuard { dir: dir.clone(), fired: AtomicBool::new(false) })));
assert!(shx::find("cadcraft-race.shx").is_none(), "a font the folder's new guard refuses was given");
// Asked again, the guard still holds.
assert!(shx::find("cadcraft-race.shx").is_none());
}
+31 -5
View File
@@ -413,16 +413,43 @@ fn legacy_protocol_routing_and_version_negotiation() {
);
}
/// A folder of this test's own, made here so nothing else put it there first, and removed when the
/// test ends, also when it fails.
struct TestDir(std::path::PathBuf);
impl TestDir {
/// A new folder named after `tag`: creating it must not find one already there, such as one a
/// failed run with the same process id left behind.
fn fresh(tag: &str) -> TestDir {
let mut n = 0u32;
loop {
let dir = std::env::temp_dir().join(format!("{tag}-{}-{n}", std::process::id()));
match std::fs::create_dir(&dir) {
Ok(()) => return TestDir(dir),
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => n += 1,
Err(e) => panic!("{}: {e}", dir.display()),
}
}
}
}
impl Drop for TestDir {
/// Removes the folder and all it holds.
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// With a read root and no write root (the read-only use #1931 asks for), an agent still draws,
/// reads and renders, but no route writes a file outside: the save tool, `execute` of the
/// writers, a save hidden mid-line at the command line and one in a script. Carried from #1973's
/// read-only mode tests.
#[test]
fn a_read_root_alone_still_draws_but_writes_nothing() {
let base = std::env::temp_dir().join(format!("cc-mcp-readonly-{}", std::process::id()));
let (inside, outside) = (base.join("in"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let base = TestDir::fresh("cc-mcp-readonly");
let (inside, outside) = (base.0.join("in"), base.0.join("outside"));
std::fs::create_dir(&inside).unwrap();
std::fs::create_dir(&outside).unwrap();
let roots = cadcraft_engine::file_access::AutomationRoots::new(Some(&inside), None).unwrap();
let mut s = Server::new(Box::new(Headless::default().with_automation_roots(roots)));
let _ = call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
@@ -446,5 +473,4 @@ fn a_read_root_alone_still_draws_but_writes_nothing() {
let _ = call(&mut s, 96, "tools/call", json!({"name": "script", "arguments": {"text": format!("circle 0,0 1\nsave {}\n", out("f.dxf"))}}));
let written: Vec<_> = std::fs::read_dir(&outside).unwrap().filter_map(Result::ok).map(|e| e.file_name()).collect();
assert!(written.is_empty(), "nothing is written outside the roots: {written:?}");
let _ = std::fs::remove_dir_all(&base);
}
+4 -2
View File
@@ -75,8 +75,10 @@ configuration works across the suite) keep the agent to the folders you give it:
same server and share: \\203.0.113.5\s\x.dwg`, or `automation filesystem access is not granted:
write authority is absent: /work/project/out/x.png`.
- A refused path in a `command_line` line is not a tool error: the reply is an ordinary result, with
the refusal in its `error` field (and echoed in `output`) and without `isError`. A client that
drives `command_line` has to read `error`.
the refusal in its `error` field (and echoed in `output`) and without `isError`. A command that
reports the refusal at its own prompt and finishes, as `-WBLOCK` does when the file it is about to
write is refused, has no `error` field: the refusal is only in `output`. A client that drives
`command_line` has to read `error` and `output`.
- A file a drawing names is held to the roots too: an image or xref saved with a path outside them is
not loaded from there, and the answer doesn't say whether the file exists. As without roots, a file
of the same name beside the host drawing is tried next, so when one is there and inside the roots