Batch filesystem metadata checks for instruction and skill discovery (#63266)

## Why

Discovering project instructions and repository skill directories can
require several metadata checks per ancestor directory. Batching those
checks reduces remote executor round trips and sandbox helper launches.

## What changed

Add bounded metadata batches that return a result or error for each
path in input order. Remote executors advertise support for
`fs/getMetadataBatch`, and sandboxed filesystems can process a batch in
one helper invocation.

Check project root markers alongside the first working-directory
instruction candidate, then batch the next candidate across unresolved
directories in filename priority order. Batch checks for
`.agents/skills` directories between the project root and the working
directory. Fall back to individual checks when batching is unsupported.

## Testing

Extend tests to assert batch counts for shallow and nested `AGENTS.md`
discovery and verify that metadata batches preserve result order and
per-path errors.

GitOrigin-RevId: 6cb04202a905d783454908348d008def95b9a5d6
This commit is contained in:
dozaki-openai
2026-11-23 05:39:53 +00:00
committed by copyberry
parent 794584993e
commit 5f645d732c
17 changed files with 537 additions and 45 deletions
+104 -9
View File
@@ -30,6 +30,8 @@ use codex_exec_server::ReadFileOptions;
use codex_extension_api::Instructions;
use codex_file_system::FileSystemSandboxContext;
use codex_file_system::FindUpErrorPolicy;
use codex_file_system::MAX_METADATA_BATCH_BYTES;
use codex_file_system::MAX_METADATA_BATCH_PROBES;
use codex_file_system::find_nearest_ancestor_with_markers;
use codex_utils_absolute_path::AbsolutePathBuf;
use codex_utils_path_uri::PathConvention;
@@ -219,6 +221,13 @@ async fn agents_md_paths(
default_project_root_markers()
}
};
let filenames = candidate_filenames(config, cwd);
match batched_instruction_paths(fs, cwd, &project_root_markers, &filenames, sandbox).await {
Ok(paths) => return Ok(paths),
Err(err) if err.kind() == io::ErrorKind::Unsupported => {}
Err(err) => return Err(err),
}
let project_root = find_nearest_ancestor_with_markers(
fs,
&dir,
@@ -246,22 +255,18 @@ async fn agents_md_paths(
vec![dir]
};
let candidate_filenames = candidate_filenames(config, cwd);
let candidate_filenames = &candidate_filenames;
let candidate_filenames = &filenames;
let mut results = futures::stream::iter(search_dirs)
.map(|directory| async move {
for name in candidate_filenames {
let candidate = directory
.join(name)
.map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
match fs
let metadata = fs
.get_metadata(&candidate, GetMetadataOptions::default(), sandbox)
.await
{
Ok(metadata) if metadata.is_file => return Ok(Some(candidate)),
Ok(_) => {}
Err(err) if err.kind() == io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
.await;
if let Some(result) = select_instruction(candidate, metadata) {
return result.map(Some);
}
}
Ok(None)
@@ -276,6 +281,96 @@ async fn agents_md_paths(
Ok(found)
}
/// Start with the working directory, which is always in scope. The first batch
/// also checks root markers to find any other directories to include. Each round
/// checks just the next filename in each unresolved directory.
async fn batched_instruction_paths(
fs: &dyn ExecutorFileSystem,
cwd: &PathUri,
markers: &[String],
names: &[&str],
sandbox: Option<&FileSystemSandboxContext>,
) -> io::Result<Vec<PathUri>> {
let search_directory = |dir| (dir, names.iter(), None);
let mut directories = vec![search_directory(cwd.clone())];
let mut check_markers = !markers.is_empty();
loop {
let mut paths = Vec::new();
let mut bytes = 0usize;
let mut add_path = |dir: &PathUri, name: &str| {
let path = dir.join(name).map_err(|_| io::ErrorKind::Unsupported)?;
bytes = bytes.saturating_add(path.to_string().len());
if paths.len() >= MAX_METADATA_BATCH_PROBES || bytes > MAX_METADATA_BATCH_BYTES {
return Err(io::ErrorKind::Unsupported);
}
paths.push(path);
Ok(())
};
let mut instruction_slots = Vec::new();
for (dir, remaining, found) in directories.iter_mut().rev() {
if matches!(found, Some(Err(_))) {
break;
}
if found.is_none()
&& let Some(name) = remaining.next()
{
add_path(dir, name)?;
instruction_slots.push(found);
}
}
if instruction_slots.is_empty() {
break;
}
if check_markers {
for dir in cwd.ancestors() {
for marker in markers {
add_path(&dir, marker)?;
}
}
check_markers = false;
}
let results = fs
.get_metadata_batch(&paths, GetMetadataOptions::default(), sandbox)
.await?;
if results.len() != paths.len() {
return Err(io::ErrorKind::InvalidData.into());
}
// Marker results, when present, follow the instruction results, nearest directory first.
let nearest_marker = results[instruction_slots.len()..]
.iter()
.position(Result::is_ok);
for ((slot, path), result) in instruction_slots.into_iter().zip(paths).zip(results) {
*slot = select_instruction(path, result);
}
if let Some(index) = nearest_marker {
let depth = index / markers.len();
directories.extend(cwd.ancestors().skip(1).take(depth).map(search_directory));
}
}
directories
.into_iter()
.rev()
.filter_map(|(_, _, found)| found)
.collect()
}
fn select_instruction(
path: PathUri,
result: io::Result<codex_file_system::FileMetadata>,
) -> Option<io::Result<PathUri>> {
match result {
Ok(metadata) if metadata.is_file => Some(Ok(path)),
Ok(_) => None,
Err(err) if err.kind() == io::ErrorKind::NotFound => None,
Err(err) => Some(Err(err)),
}
}
fn candidate_filenames<'a>(config: &'a Config, cwd: &PathUri) -> Vec<&'a str> {
let mut names: Vec<&str> = Vec::with_capacity(2 + config.project_doc_fallback_filenames.len());
names.push(LOCAL_AGENTS_MD_FILENAME);
+43
View File
@@ -46,6 +46,8 @@ use std::ops::DerefMut;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use tempfile::TempDir;
use tokio::sync::Notify;
use tokio::sync::Semaphore;
@@ -67,6 +69,7 @@ struct FailingFileSystem {
}
struct MetadataCallCounts {
batch_calls: Option<Arc<AtomicUsize>>,
paths: Mutex<Vec<PathUri>>,
started: Notify,
release: Semaphore,
@@ -75,6 +78,7 @@ struct MetadataCallCounts {
impl Default for MetadataCallCounts {
fn default() -> Self {
Self {
batch_calls: None,
paths: Mutex::new(Vec::new()),
started: Notify::new(),
release: Semaphore::new(0),
@@ -272,6 +276,21 @@ impl ExecutorFileSystem for FailingFileSystem {
))
}
fn get_metadata_batch<'a>(
&'a self,
paths: &'a [PathUri],
options: GetMetadataOptions,
sandbox: Option<&'a FileSystemSandboxContext>,
) -> ExecutorFileSystemFuture<'a, Vec<io::Result<FileMetadata>>> {
Box::pin(async move {
let Some(calls) = &self.metadata_calls.batch_calls else {
return Err(io::ErrorKind::Unsupported.into());
};
calls.fetch_add(1, Ordering::Relaxed);
codex_file_system::resolve_metadata_batch(self, paths, options, sandbox).await
})
}
fn read_directory<'a>(
&'a self,
path: &'a PathUri,
@@ -1103,6 +1122,30 @@ async fn finds_doc_in_repo_root() {
let res = get_user_instructions(&cfg).await.expect("doc expected");
assert_eq!(res, "root level doc");
let batch_calls = Arc::new(AtomicUsize::new(0));
let metadata_calls = Arc::new(MetadataCallCounts {
batch_calls: Some(Arc::clone(&batch_calls)),
..MetadataCallCounts::default()
});
let filesystem = FailingFileSystem {
path: cfg.cwd.join("unused"),
failure: InjectedFailure::Read(io::ErrorKind::PermissionDenied),
metadata_calls: Arc::clone(&metadata_calls),
};
let cwd = PathUri::from_abs_path(&cfg.cwd);
assert_eq!(
super::agents_md_paths(&cfg.config, &cwd, &filesystem, /*sandbox*/ None)
.await
.expect("batched nested discovery"),
vec![PathUri::from_abs_path(&repo.path().join("AGENTS.md").abs())]
);
assert_eq!(batch_calls.load(Ordering::Relaxed), 3);
batch_calls.store(0, Ordering::Relaxed);
let cwd = PathUri::from_abs_path(&repo.abs());
super::agents_md_paths(&cfg.config, &cwd, &filesystem, /*sandbox*/ None)
.await
.expect("batched shallow discovery");
assert_eq!(batch_calls.load(Ordering::Relaxed), 2);
}
/// Explicitly setting the byte-limit to zero disables project docs.