codex: disambiguate Git attribute sentinel states

This commit is contained in:
Chris Bookholt
2026-07-06 21:10:39 -07:00
parent 27bf6d5c29
commit 555c1fdd5f
7 changed files with 731 additions and 66 deletions
+55
View File
@@ -1089,6 +1089,61 @@ mod tests {
assert_ne!(r.exit_code, 0, "non-zero exit on missing index");
}
#[cfg(unix)]
#[test]
fn missing_index_three_way_classification_does_not_run_post_index_change_hook() {
use std::os::unix::fs::PermissionsExt;
let _g = env_lock().lock().unwrap();
let repo = init_repo();
let root = repo.path();
let hooks = root.join(".githooks");
std::fs::create_dir(&hooks).expect("create hooks directory");
let hook = hooks.join("post-index-change");
std::fs::write(&hook, "#!/bin/sh\nprintf ran > \"$PWD/hook-ran\"\n")
.expect("write post-index-change hook");
let mut permissions = std::fs::metadata(&hook)
.expect("hook metadata")
.permissions();
permissions.set_mode(0o755);
std::fs::set_permissions(&hook, permissions).expect("make hook executable");
assert_eq!(
run(root, &["git", "config", "core.hooksPath", ".githooks"]).0,
0
);
std::fs::write(root.join("new.txt"), b"local\n").expect("write untracked path");
assert!(
!root.join(".git/index").exists(),
"fixture has a real index"
);
let result = apply_git_patch(&ApplyGitRequest {
cwd: root.to_path_buf(),
diff: "diff --git a/new.txt b/new.txt\nnew file mode 100644\nindex 0000000000000000000000000000000000000000..893adcd31e963b01dfbbcfe3ec58a008f0d81201\n--- /dev/null\n+++ b/new.txt\n@@ -0,0 +1 @@\n+patched\n".to_string(),
revert: false,
preflight: false,
})
.expect("classify missing-index three-way fallback");
assert_ne!(
result.exit_code, 0,
"untracked destination must not be replaced"
);
assert!(result.cmd_for_log.contains("--3way"), "{result:?}");
assert!(
!root.join("hook-ran").exists(),
"post-index-change hook ran"
);
assert!(
!root.join(".git/index").exists(),
"scratch initialization created the real index"
);
assert_eq!(
std::fs::read(root.join("new.txt")).expect("read untracked path"),
b"local\n"
);
}
#[test]
fn apply_then_revert_success() {
let _g = env_lock().lock().unwrap();
+79 -2
View File
@@ -23,6 +23,7 @@ use crate::git_executable::windows_path_requires_fail_closed;
use crate::repository_authority::RepositoryAuthority;
#[cfg(test)]
use crate::repository_authority::parse_marker_path as parse_git_marker_path;
use crate::safe_git::DISABLED_HOOKS_PATH;
use crate::safe_git::isolate_git_command_environment;
/// A Git executable outside the repository-controlled roots for one operation.
@@ -62,7 +63,7 @@ pub(crate) struct IsolatedGitStorage {
}
impl IsolatedGitStorage {
fn index_path(&self) -> PathBuf {
pub(crate) fn index_path(&self) -> PathBuf {
self.root.path().join("index")
}
@@ -332,7 +333,36 @@ impl GitRunner {
"owned isolated Git scratch storage",
)?;
std::fs::create_dir(root.path().join("objects"))?;
copy_regular_file_without_follow(&source_index, &root.path().join("index"))?;
let isolated_index = root.path().join("index");
match copy_regular_file_without_follow(&source_index, &isolated_index) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {
// An unborn repository may not have materialized an index
// yet. Create the equivalent empty index through trusted Git
// in operation-owned storage; an empty file is not a valid
// index, and hand-encoding one would couple this path to the
// repository hash algorithm and index checksum format.
let mut command = self.command_for_cwd(self.authority.active_worktree_root())?;
let disabled_hooks = format!("core.hooksPath={DISABLED_HOOKS_PATH}");
command.args([
"-c",
&disabled_hooks,
"-c",
"core.fsmonitor=false",
"read-tree",
"--empty",
]);
let output = self.output_with_new_isolated_index(command, &isolated_index)?;
if !output.status.success() {
return Err(io::Error::other(format!(
"failed to initialize an empty isolated Git index (status {}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
}
Err(error) => return Err(error),
}
// A copied split index resolves its content-addressed base beside the
// active per-worktree index, not in a distinct common directory. Copy
// only well-formed names from that authoritative Git directory; Git
@@ -346,6 +376,27 @@ impl GitRunner {
Ok(storage)
}
fn output_with_new_isolated_index(
&self,
mut command: GitCommand,
index_path: &Path,
) -> io::Result<std::process::Output> {
self.revalidate_active_repository_metadata()?;
self.authority
.ensure_config_source_is_not_worktree_controlled(
index_path,
"owned isolated Git scratch index",
)?;
isolate_git_command_environment(&mut command.inner);
command.inner.env("GIT_INDEX_FILE", index_path);
command.inner.env("GIT_OPTIONAL_LOCKS", "0");
command.inner.envs(crate::local_only_git_env());
harden_git_launch_environment(&mut command.inner, &self.safe_path);
let output = command.inner.output()?;
self.revalidate_active_repository_metadata()?;
Ok(output)
}
pub(crate) fn output(&self, mut command: GitCommand) -> io::Result<std::process::Output> {
self.revalidate_active_repository_metadata()?;
isolate_git_command_environment(&mut command.inner);
@@ -371,6 +422,32 @@ impl GitRunner {
self.output_in_isolated_common_dir_with_storage(command, isolated, Some(storage))
}
/// Run against an operation-owned copy of the active index while retaining
/// the repository's normal config and attribute sources. This is used only
/// for nonmutating classification and `update-index --info-only` setup;
/// callers cannot redirect the object database or common directory.
pub(crate) fn output_with_isolated_index(
&self,
mut command: GitCommand,
storage: &IsolatedGitStorage,
) -> io::Result<std::process::Output> {
self.revalidate_active_repository_metadata()?;
storage.validate()?;
self.authority
.ensure_config_source_is_not_worktree_controlled(
storage.root.path(),
"owned isolated Git scratch storage",
)?;
isolate_git_command_environment(&mut command.inner);
command.inner.env("GIT_INDEX_FILE", storage.index_path());
command.inner.envs(crate::local_only_git_env());
harden_git_launch_environment(&mut command.inner, &self.safe_path);
let output = command.inner.output()?;
self.revalidate_active_repository_metadata()?;
storage.validate()?;
Ok(output)
}
fn output_in_isolated_common_dir_with_storage(
&self,
mut command: GitCommand,
@@ -20,6 +20,23 @@ const REPOSITORY_FORMAT_CONFIG_PATTERN: &str =
const SANITIZED_CONFIG_PATTERN: &str = r"^(core\.(filemode|symlinks|ignorecase|precomposeunicode|protecthfs|protectntfs|trustctime|checkstat|longpaths|fscache|splitindex|sparsecheckout|sparsecheckoutcone|autocrlf|eol|safecrlf|checkroundtripencoding|bigfilethreshold)|index\.(sparse|version)|merge\.conflictstyle)$";
// Git ignores an attribute line whose content length is at least this value.
const GIT_ATTRIBUTE_LINE_LENGTH_LIMIT: usize = 2048;
const THREE_WAY_ATTRIBUTE_NAMES: [&str; 9] = [
"merge",
"whitespace",
"conflict-marker-size",
"text",
"crlf",
"eol",
"ident",
"filter",
"working-tree-encoding",
];
// `ls-files` has no pathspec-from-file mode on the oldest supported Git. Keep
// each discriminator command comfortably below the Windows command-line
// limit after accounting for the fixed Git and config arguments.
const SENTINEL_PATHSPEC_BYTES_LIMIT: usize = 16 * 1024;
const SENTINEL_PROBE_OUTPUT_BYTES_LIMIT: usize = 4 * 1024 * 1024;
const SENTINEL_PROBE_PATHS_LIMIT: usize = 4_096;
/// A complete, fresh merge-config read bound to one authorized operation.
///
@@ -75,12 +92,8 @@ impl BuiltinMergeDriver {
}
}
/// Per-path apply semantics frozen at the strict `check-attr` probe.
///
/// Git's public `check-attr` format conflates special states with the literal
/// values `set`, `unset`, and `unspecified`. This snapshot intentionally uses
/// Git's conventional rendering for those uncommon literal spellings. Every
/// other safely representable value is retained byte-for-byte.
/// Per-path apply semantics frozen at the strict `check-attr` probe and its
/// attribute-pathspec discriminator.
struct MergeAttributeSnapshot {
owner: Arc<CapabilityIdentity>,
paths: BTreeMap<String, FrozenPathApplyAttributes>,
@@ -95,6 +108,7 @@ struct FrozenPathApplyAttributes {
#[derive(Clone, Debug, Eq, PartialEq)]
struct ParsedPathApplyAttributes {
merge: String,
merge_sentinel: Option<AttributeSentinel>,
safe: SafeApplyAttributes,
}
@@ -106,23 +120,62 @@ enum ProjectedAttribute {
Unset,
Unspecified,
Value(Vec<u8>),
Ambiguous(AttributeSentinel),
}
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
enum AttributeSentinel {
Set,
Unset,
Unspecified,
}
impl AttributeSentinel {
fn from_check_attr(value: &[u8]) -> Option<Self> {
match value {
b"set" => Some(Self::Set),
b"unset" => Some(Self::Unset),
b"unspecified" => Some(Self::Unspecified),
_ => None,
}
}
fn spelling(self) -> &'static str {
match self {
Self::Set => "set",
Self::Unset => "unset",
Self::Unspecified => "unspecified",
}
}
fn special_requirement(self, name: &str) -> String {
match self {
Self::Set => name.to_string(),
Self::Unset => format!("-{name}"),
Self::Unspecified => format!("!{name}"),
}
}
fn projected(self) -> ProjectedAttribute {
match self {
Self::Set => ProjectedAttribute::Set,
Self::Unset => ProjectedAttribute::Unset,
Self::Unspecified => ProjectedAttribute::Unspecified,
}
}
}
impl ProjectedAttribute {
fn from_check_attr(value: &[u8]) -> io::Result<Self> {
// `git check-attr` deliberately renders both special states and the
// literal values `=set`, `=unset`, and `=unspecified` with the same
// sentinel text. Match Git's documented convention for this bounded
// PR while retaining all other raw values.
match value {
b"set" => Ok(Self::Set),
b"unset" => Ok(Self::Unset),
b"unspecified" => Ok(Self::Unspecified),
value => {
validate_projected_attribute_value(value)?;
Ok(Self::Value(value.to_vec()))
}
// bytes. Keep them unresolved until an attribute-aware pathspec has
// proved which meaning Git selected.
if let Some(sentinel) = AttributeSentinel::from_check_attr(value) {
return Ok(Self::Ambiguous(sentinel));
}
validate_projected_attribute_value(value)?;
Ok(Self::Value(value.to_vec()))
}
fn projected_token(&self, name: &str) -> Vec<u8> {
@@ -137,6 +190,7 @@ impl ProjectedAttribute {
token.extend_from_slice(value);
token
}
Self::Ambiguous(_) => Vec::new(),
}
}
}
@@ -156,6 +210,77 @@ struct SafeApplyAttributes {
_filter: ProjectedAttribute,
}
impl ParsedPathApplyAttributes {
fn ambiguous_sentinel(&self, name: &str) -> io::Result<Option<AttributeSentinel>> {
if name == "merge" {
return Ok(self.merge_sentinel);
}
let attribute = self.safe.attribute(name)?;
Ok(match attribute {
ProjectedAttribute::Ambiguous(sentinel) => Some(*sentinel),
_ => None,
})
}
fn resolve_special_sentinel(
&mut self,
name: &str,
sentinel: AttributeSentinel,
) -> io::Result<()> {
if name == "merge" {
if self.merge_sentinel != Some(sentinel) || self.merge != sentinel.spelling() {
return Err(invalid_attribute_output(
"Git merge sentinel changed during disambiguation",
));
}
self.merge_sentinel = None;
return Ok(());
}
let attribute = self.safe.attribute_mut(name)?;
if *attribute != ProjectedAttribute::Ambiguous(sentinel) {
return Err(invalid_attribute_output(
"Git apply sentinel changed during disambiguation",
));
}
*attribute = sentinel.projected();
Ok(())
}
}
impl SafeApplyAttributes {
fn attribute(&self, name: &str) -> io::Result<&ProjectedAttribute> {
match name {
"whitespace" => Ok(&self.whitespace),
"conflict-marker-size" => Ok(&self.conflict_marker_size),
"text" => Ok(&self.text),
"crlf" => Ok(&self.crlf),
"eol" => Ok(&self.eol),
"ident" => Ok(&self.ident),
"filter" => Ok(&self._filter),
"working-tree-encoding" => Ok(&self.working_tree_encoding),
_ => Err(invalid_attribute_output(
"unexpected Git attribute discriminator name",
)),
}
}
fn attribute_mut(&mut self, name: &str) -> io::Result<&mut ProjectedAttribute> {
match name {
"whitespace" => Ok(&mut self.whitespace),
"conflict-marker-size" => Ok(&mut self.conflict_marker_size),
"text" => Ok(&mut self.text),
"crlf" => Ok(&mut self.crlf),
"eol" => Ok(&mut self.eol),
"ident" => Ok(&mut self.ident),
"filter" => Ok(&mut self._filter),
"working-tree-encoding" => Ok(&mut self.working_tree_encoding),
_ => Err(invalid_attribute_output(
"unexpected Git attribute discriminator name",
)),
}
}
}
impl MergeAttributeSnapshot {
fn from_effective(
owner: &Arc<CapabilityIdentity>,
@@ -358,6 +483,10 @@ impl<'git> GuardedGitConfig<'git> {
) -> io::Result<()> {
let paths = self.apply_filter_paths()?;
let snapshot = self.read_merge_config_snapshot()?;
let repository_format = self
.sources
.read_direct_common_config(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")?;
let object_format = index_object_format(&repository_format)?;
let input = merge_attribute_input(&paths)?;
let output = self.query_merge_attributes(&snapshot, input)?;
if !output.status.success() {
@@ -368,6 +497,13 @@ impl<'git> GuardedGitConfig<'git> {
)));
}
let parsed_attributes = parse_three_way_attributes(&output.stdout, &paths)?;
let parsed_attributes = self.disambiguate_attribute_sentinels(
&snapshot,
&paths,
parsed_attributes,
&output,
object_format,
)?;
let merge_attributes = parsed_attributes
.iter()
.map(|(path, attributes)| (path.clone(), attributes.merge.clone()))
@@ -400,6 +536,7 @@ impl<'git> GuardedGitConfig<'git> {
paths,
selected_custom,
custom_destinations,
repository_format,
)?;
self.attach_merge_override(isolated)
}
@@ -459,6 +596,215 @@ impl<'git> GuardedGitConfig<'git> {
self.sources.git.output(command)
}
fn disambiguate_attribute_sentinels(
&self,
snapshot: &MergeConfigSnapshot,
paths: &[String],
mut attributes: BTreeMap<String, ParsedPathApplyAttributes>,
initial: &std::process::Output,
object_format: IndexObjectFormat,
) -> io::Result<BTreeMap<String, ParsedPathApplyAttributes>> {
snapshot.ensure_owner(&self.identity)?;
if paths.len() > SENTINEL_PROBE_PATHS_LIMIT {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"too many paths for bounded Git attribute sentinel classification",
));
}
let mut unresolved = BTreeMap::<&'static str, Vec<(String, AttributeSentinel)>>::new();
for name in THREE_WAY_ATTRIBUTE_NAMES {
let mut entries = Vec::new();
for path in paths {
let parsed = attributes
.get(path)
.ok_or_else(|| invalid_attribute_output("missing parsed Git attribute path"))?;
if let Some(sentinel) = parsed.ambiguous_sentinel(name)? {
entries.push((path.clone(), sentinel));
}
}
if !entries.is_empty() {
unresolved.insert(name, entries);
}
}
if unresolved.is_empty() {
return Ok(attributes);
}
let storage = self.sources.git.create_isolated_git_storage()?;
self.populate_attribute_probe_phantoms(&storage, paths, object_format)?;
for (name, entries) in unresolved {
let literal = self.run_attribute_sentinel_probe(
&storage,
name,
&entries,
SentinelProbeKind::Literal,
)?;
let special = self.run_attribute_sentinel_probe(
&storage,
name,
&entries,
SentinelProbeKind::Special,
)?;
for (path, sentinel) in entries {
match (literal.contains(&path), special.contains(&path)) {
(true, false) => {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
format!(
"refusing a three-way apply because {name}={:?} is a literal Git attribute value for {path:?}",
sentinel.spelling()
),
));
}
(false, true) => attributes
.get_mut(&path)
.ok_or_else(|| {
invalid_attribute_output("missing parsed Git attribute path")
})?
.resolve_special_sentinel(name, sentinel)?,
(false, false) | (true, true) => {
return Err(invalid_attribute_output(
"inconclusive Git attribute sentinel classification",
));
}
}
}
}
// A second exact nine-attribute snapshot brackets all attribute-aware
// pathspec reads. If any effective source changed to a different
// public state, the operation fails before scratch or real mutation.
let recheck = self.query_merge_attributes(snapshot, merge_attribute_input(paths)?)?;
if recheck.status != initial.status
|| recheck.stdout != initial.stdout
|| recheck.stderr != initial.stderr
{
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
"Git attributes changed during sentinel classification",
));
}
Ok(attributes)
}
fn populate_attribute_probe_phantoms(
&self,
storage: &IsolatedGitStorage,
paths: &[String],
object_format: IndexObjectFormat,
) -> io::Result<()> {
let mut command = self.command_with_attached_overlays()?;
command.env("GIT_OPTIONAL_LOCKS", "0");
command.args([
"--literal-pathspecs",
"ls-files",
"--cached",
"--full-name",
"-z",
"--",
]);
command.args(paths);
let output = self
.sources
.git
.output_with_isolated_index(command, storage)?;
if !output.status.success() {
return Err(io::Error::other(format!(
"failed to inspect copied Git index for attribute probes (status {}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
let expected = paths.iter().cloned().collect::<BTreeSet<_>>();
let present = parse_sentinel_probe_paths(&output.stdout, &expected)?;
let missing = paths
.iter()
.filter(|path| !present.contains(*path))
.collect::<Vec<_>>();
if missing.is_empty() {
return Ok(());
}
use std::io::Seek;
let mut input = tempfile::tempfile()?;
let object_id = match object_format {
IndexObjectFormat::Sha1 => "1".repeat(40),
IndexObjectFormat::Sha256 => "1".repeat(64),
};
for path in missing {
input.write_all(b"100644 ")?;
input.write_all(object_id.as_bytes())?;
input.write_all(b"\t")?;
input.write_all(path.as_bytes())?;
input.write_all(&[0])?;
}
input.rewind()?;
let mut command = self.command_with_attached_overlays()?;
command
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["update-index", "--add", "--info-only", "-z", "--index-info"])
.stdin(Stdio::from(input));
let output = self
.sources
.git
.output_with_isolated_index(command, storage)?;
if !output.status.success() {
return Err(io::Error::other(format!(
"failed to populate copied Git index for attribute probes (status {}): {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
Ok(())
}
fn run_attribute_sentinel_probe(
&self,
storage: &IsolatedGitStorage,
name: &str,
entries: &[(String, AttributeSentinel)],
kind: SentinelProbeKind,
) -> io::Result<BTreeSet<String>> {
let mut pathspecs = Vec::with_capacity(entries.len());
let mut pathspec_bytes = 0_usize;
let mut expected = BTreeSet::new();
for (path, sentinel) in entries {
let requirement = match kind {
SentinelProbeKind::Literal => format!("{name}={}", sentinel.spelling()),
SentinelProbeKind::Special => sentinel.special_requirement(name),
};
let pathspec = format!(":(top,literal,attr:{requirement}){path}");
pathspec_bytes = pathspec_bytes
.checked_add(pathspec.len() + 1)
.ok_or_else(|| invalid_attribute_output("Git attribute pathspec size overflow"))?;
if pathspec_bytes > SENTINEL_PATHSPEC_BYTES_LIMIT {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
"Git attribute sentinel pathspec budget exceeded",
));
}
expected.insert(path.clone());
pathspecs.push(pathspec);
}
let mut command = self.command_with_attached_overlays()?;
command.env("GIT_OPTIONAL_LOCKS", "0");
command.args(["ls-files", "--cached", "--full-name", "-z", "--"]);
command.args(pathspecs);
let output = self
.sources
.git
.output_with_isolated_index(command, storage)?;
if !output.status.success() {
return Err(io::Error::other(format!(
"Git attribute sentinel probe failed with status {}: {}",
output.status,
String::from_utf8_lossy(&output.stderr).trim()
)));
}
parse_sentinel_probe_paths(&output.stdout, &expected)
}
fn build_merge_override(
&self,
snapshot: &MergeConfigSnapshot,
@@ -466,6 +812,7 @@ impl<'git> GuardedGitConfig<'git> {
effective_paths: Vec<String>,
selected_custom: BTreeMap<String, String>,
custom_destinations: BTreeSet<String>,
repository_format: BTreeMap<String, GitConfigEntry>,
) -> io::Result<SealedMergeConfigOverride> {
snapshot.ensure_owner(&self.identity)?;
attributes.ensure_owner(&self.identity)?;
@@ -485,9 +832,6 @@ impl<'git> GuardedGitConfig<'git> {
.as_ref()
.map(normalize_shared_repository)
.transpose()?;
let repository_format = self
.sources
.read_direct_common_config(REPOSITORY_FORMAT_CONFIG_PATTERN, "repository format")?;
let object_format = index_object_format(&repository_format)?;
let common_dir = self.sources.git.create_isolated_common_dir()?;
let config_path = common_dir.config_path();
@@ -1238,6 +1582,7 @@ fn append_projected_attribute_lines(
#[derive(Default)]
struct PendingPathApplyAttributes {
merge: Option<String>,
merge_sentinel: Option<AttributeSentinel>,
whitespace: Option<ProjectedAttribute>,
conflict_marker_size: Option<ProjectedAttribute>,
text: Option<ProjectedAttribute>,
@@ -1251,6 +1596,7 @@ struct PendingPathApplyAttributes {
impl PendingPathApplyAttributes {
fn insert(&mut self, attribute: &[u8], value: &[u8]) -> io::Result<()> {
if attribute == b"merge" {
let sentinel = AttributeSentinel::from_check_attr(value);
let value = std::str::from_utf8(value)
.map_err(|_| invalid_attribute_output("non-UTF-8 Git merge attribute value"))?;
if self.merge.replace(value.to_string()).is_some() {
@@ -1258,6 +1604,7 @@ impl PendingPathApplyAttributes {
"duplicate Git merge attribute record",
));
}
self.merge_sentinel = sentinel;
return Ok(());
}
@@ -1288,6 +1635,7 @@ impl PendingPathApplyAttributes {
fn finish(self) -> io::Result<ParsedPathApplyAttributes> {
Ok(ParsedPathApplyAttributes {
merge: required_attribute(self.merge, "merge")?,
merge_sentinel: self.merge_sentinel,
safe: SafeApplyAttributes {
whitespace: required_attribute(self.whitespace, "whitespace")?,
conflict_marker_size: required_attribute(
@@ -1312,6 +1660,50 @@ fn required_attribute<T>(value: Option<T>, name: &str) -> io::Result<T> {
value.ok_or_else(|| invalid_attribute_output(&format!("missing Git {name} attribute record")))
}
#[derive(Clone, Copy)]
enum SentinelProbeKind {
Literal,
Special,
}
fn parse_sentinel_probe_paths(
output: &[u8],
expected: &BTreeSet<String>,
) -> io::Result<BTreeSet<String>> {
if output.len() > SENTINEL_PROBE_OUTPUT_BYTES_LIMIT {
return Err(invalid_attribute_output(
"Git attribute sentinel probe output exceeded its byte budget",
));
}
if output.is_empty() {
return Ok(BTreeSet::new());
}
let body = output.strip_suffix(&[0]).ok_or_else(|| {
invalid_attribute_output("unterminated Git attribute sentinel probe output")
})?;
if body.is_empty() {
return Err(invalid_attribute_output(
"empty Git attribute sentinel probe record",
));
}
let mut found = BTreeSet::new();
for path in body.split(|byte| *byte == 0) {
let path = std::str::from_utf8(path)
.map_err(|_| invalid_attribute_output("non-UTF-8 Git attribute sentinel probe path"))?;
if !expected.contains(path) {
return Err(invalid_attribute_output(
"unexpected Git attribute sentinel probe path",
));
}
// Do not rely on `ls-files --deduplicate`: older supported Git
// versions lack it, and an unmerged index legitimately emits one
// record per stage. Every repeated record is still exact, expected,
// NUL framed, and covered by the aggregate byte bound.
found.insert(path.to_string());
}
Ok(found)
}
/// Parse the strict NUL-framed output of the one fixed nine-attribute query.
/// Every authorized path must have exactly one record for every consumed name;
/// extra, duplicate, malformed, or unrepresentable data fails closed.
@@ -262,6 +262,7 @@ fn sealed_merge_override_rejects_another_operation_identity() {
"file.txt".to_string(),
ParsedPathApplyAttributes {
merge: "unspecified".to_string(),
merge_sentinel: None,
safe: unspecified_safe_attributes(),
},
)]),
@@ -275,6 +276,7 @@ fn sealed_merge_override_rejects_another_operation_identity() {
vec!["file.txt".to_string()],
BTreeMap::new(),
BTreeSet::new(),
BTreeMap::new(),
)
.expect("build isolated merge config");
let error = second
@@ -515,13 +517,16 @@ fn projected_whitespace_states_mask_lower_sources() {
.values()
.map(|attributes| attributes.safe.whitespace.clone())
.collect::<Vec<_>>(),
whitespace
);
assert!(
actual
.values()
.all(|attributes| attributes.safe._filter == ProjectedAttribute::Unspecified)
vec![
ProjectedAttribute::Ambiguous(AttributeSentinel::Set),
ProjectedAttribute::Ambiguous(AttributeSentinel::Unset),
ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified),
whitespace[3].clone(),
]
);
assert!(actual.values().all(|attributes| {
attributes.safe._filter == ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified)
}));
}
#[test]
@@ -657,7 +662,7 @@ fn projected_attribute_lines_split_below_git_limit_or_fail_closed() {
}
#[test]
fn native_check_attr_conflates_sentinels_for_every_projected_name() {
fn native_check_attr_marks_conflated_sentinels_unresolved_for_every_projected_name() {
let repo = tempfile::tempdir().expect("repo");
let root = repo.path();
run_git(root, &["init", "-q"]);
@@ -753,16 +758,21 @@ fn native_check_attr_conflates_sentinels_for_every_projected_name() {
let expected_paths = paths.map(str::to_string).to_vec();
let parsed = parse_three_way_attributes(&output.stdout, &expected_paths)
.expect("parse conventional sentinel rendering");
// The bounded implementation accepts this documented residual: literal
// sentinel values are projected as their same-spelled special states.
assert_eq!(parsed["literal-set"].safe.text, ProjectedAttribute::Set);
assert_eq!(
parsed["literal-set"].safe.text,
ProjectedAttribute::Ambiguous(AttributeSentinel::Set)
);
assert_eq!(
parsed["literal-unset"].safe.ident,
ProjectedAttribute::Unset
ProjectedAttribute::Ambiguous(AttributeSentinel::Unset)
);
assert_eq!(
parsed["literal-unspecified"].safe._filter,
ProjectedAttribute::Unspecified
ProjectedAttribute::Ambiguous(AttributeSentinel::Unspecified)
);
assert_eq!(
parsed["literal-set"].merge_sentinel,
Some(AttributeSentinel::Set)
);
}
@@ -187,6 +187,23 @@ fn assert_mutation_happened_between_probe_and_three_way(trace: &Path) {
assert!(mutation < three_way, "final Git started before mutation");
}
fn assert_mutation_happened_after_probe_before_refusal(trace: &Path) {
let contents = std::fs::read_to_string(trace).expect("read completed trace");
let probe_start = contents.find("check-attr").expect("merge attribute probe");
let probe_exit = probe_start
+ contents[probe_start..]
.find("\"event\":\"exit\"")
.expect("merge attribute probe exit");
let mutation = contents
.find(TRACE_MUTATION_MARKER)
.expect("mutation trace marker");
assert!(probe_exit < mutation, "mutation preceded probe exit");
assert!(
!contents[mutation..].contains("--3way"),
"a three-way apply started after an incoherent attribute snapshot"
);
}
fn append_driver_config(root: &Path, driver: &str, command: &str) {
let mut config = OpenOptions::new()
.append(true)
@@ -329,10 +346,10 @@ fn selected_empty_and_equals_named_drivers_reject_without_marker_or_index_mutati
}
#[test]
fn post_probe_attribute_change_cannot_run_empty_named_driver() {
fn post_probe_attribute_change_refuses_before_empty_named_driver() {
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
run_isolated_test(
"merge_driver::race_tests::post_probe_attribute_change_cannot_run_empty_named_driver",
"merge_driver::race_tests::post_probe_attribute_change_refuses_before_empty_named_driver",
);
return;
}
@@ -355,20 +372,20 @@ fn post_probe_attribute_change_cannot_run_empty_named_driver() {
observed
});
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect("neutralized three-way apply");
let error = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect_err("attribute mutation during sentinel classification must fail closed");
assert!(watcher.join().expect("attribute watcher"));
assert_mutation_happened_between_probe_and_three_way(&trace);
assert_ne!(result.exit_code, 0);
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}");
assert_mutation_happened_after_probe_before_refusal(&trace);
assert!(!configured_marker_exists(root, "codex.oldmergeran"));
}
#[test]
fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() {
fn post_probe_attribute_and_driver_change_refuses_before_helper_dispatch() {
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
run_isolated_test(
"merge_driver::race_tests::post_probe_attribute_and_same_driver_command_change_stays_neutralized",
"merge_driver::race_tests::post_probe_attribute_and_driver_change_refuses_before_helper_dispatch",
);
return;
}
@@ -395,21 +412,21 @@ fn post_probe_attribute_and_same_driver_command_change_stays_neutralized() {
observed
});
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect("neutralized three-way apply");
let error = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect_err("attribute mutation during sentinel classification must fail closed");
assert!(watcher.join().expect("config watcher"));
assert_mutation_happened_between_probe_and_three_way(&trace);
assert_ne!(result.exit_code, 0);
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}");
assert_mutation_happened_after_probe_before_refusal(&trace);
assert!(!configured_marker_exists(root, "codex.oldmergeran"));
assert!(!configured_marker_exists(root, "codex.newmergeran"));
}
#[test]
fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() {
fn post_probe_worktree_attribute_change_refuses_snapshot_drift() {
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
run_isolated_test(
"merge_driver::race_tests::post_probe_worktree_attribute_change_preserves_probed_union_semantics",
"merge_driver::race_tests::post_probe_worktree_attribute_change_refuses_snapshot_drift",
);
return;
}
@@ -431,16 +448,12 @@ fn post_probe_worktree_attribute_change_preserves_probed_union_semantics() {
observed
});
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect("run frozen union three-way apply");
let error = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect_err("attribute mutation during sentinel classification must fail closed");
assert!(watcher.join().expect("attribute watcher"));
assert_mutation_happened_between_probe_and_three_way(&trace);
assert_eq!(result.exit_code, 0, "{}", result.stderr);
let contents = read_file_normalized(&root.join("target.txt"));
assert!(contents.contains("ours\n"), "{contents}");
assert!(contents.contains("theirs\n"), "{contents}");
assert!(!contents.contains("<<<<<<<"), "{contents}");
assert_eq!(error.kind(), io::ErrorKind::PermissionDenied, "{error}");
assert_mutation_happened_after_probe_before_refusal(&trace);
}
#[test]
@@ -507,13 +520,19 @@ fn isolated_three_way_config_blocks_driver_namespace_introduction_races() {
let outcome = apply_git_patch(&request(root, patch, /*revert*/ false));
assert!(watcher.join().expect("namespace watcher"), "{race:?}");
assert_mutation_happened_between_probe_and_three_way(&trace);
if matches!(race, DriverNamespaceRace::KnownEmpty) {
if matches!(race, DriverNamespaceRace::BrandNewAttribute) {
let error = outcome
.expect_err("attribute mutation during sentinel classification must fail closed");
assert_eq!(error.kind(), io::ErrorKind::InvalidData, "{error}");
assert_mutation_happened_after_probe_before_refusal(&trace);
} else if matches!(race, DriverNamespaceRace::KnownEmpty) {
assert_mutation_happened_between_probe_and_three_way(&trace);
let error = outcome.expect_err(
"an explicit empty driver is a selected namespace and must refuse when reachable",
);
assert_eq!(error.kind(), io::ErrorKind::Unsupported, "{error}");
} else {
assert_mutation_happened_between_probe_and_three_way(&trace);
let result = outcome.expect("run isolated three-way apply");
assert_ne!(result.exit_code, 0, "{race:?}");
assert!(result.cmd_for_log.contains("GIT_COMMON_DIR=<isolated>"));
@@ -524,10 +543,10 @@ fn isolated_three_way_config_blocks_driver_namespace_introduction_races() {
}
#[test]
fn isolated_three_way_config_scrubs_command_config_channels() {
fn post_probe_command_config_selection_refuses_snapshot_drift() {
if std::env::var_os("CODEX_GIT_UTILS_MERGE_RACE_CHILD").is_none() {
run_isolated_test_with_env(
"merge_driver::race_tests::isolated_three_way_config_scrubs_command_config_channels",
"merge_driver::race_tests::post_probe_command_config_selection_refuses_snapshot_drift",
&[
("GIT_CONFIG_COUNT", OsStr::new("1")),
("GIT_CONFIG_KEY_0", OsStr::new("merge.env-selected.driver")),
@@ -564,12 +583,16 @@ fn isolated_three_way_config_scrubs_command_config_channels() {
observed
});
let result = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect("run isolated three-way apply");
let error = apply_git_patch(&request(root, patch, /*revert*/ false))
.expect_err("attribute mutation during sentinel classification must fail closed");
assert!(watcher.join().expect("config-channel watcher"), "{driver}");
assert_mutation_happened_between_probe_and_three_way(&trace);
assert_ne!(result.exit_code, 0, "{driver}");
assert_eq!(
error.kind(),
io::ErrorKind::InvalidData,
"{driver}: {error}"
);
assert_mutation_happened_after_probe_before_refusal(&trace);
assert!(!configured_marker_exists(root, "codex.envmergeran"));
assert!(!configured_marker_exists(root, "codex.basemergeran"));
}
+110 -2
View File
@@ -15,6 +15,114 @@ use pretty_assertions::assert_eq;
use std::ffi::OsStr;
use std::path::Path;
#[test]
fn three_way_refuses_literal_text_set_before_mutating_index_or_worktree() {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join(".gitattributes"), "f.txt text=set\n")
.expect("write literal attribute");
std::fs::write(root.join("f.txt"), b"x\n").expect("write base");
assert_eq!(run(root, &["git", "add", "."]).0, 0);
assert_eq!(run(root, &["git", "commit", "-m", "base"]).0, 0);
std::fs::write(root.join("f.txt"), b"y\n").expect("write patch side");
let (diff_code, diff, diff_err) = run(root, &["git", "diff", "--full-index", "--", "f.txt"]);
assert_eq!(diff_code, 0, "create patch: {diff_err}");
assert_eq!(run(root, &["git", "checkout", "--", "f.txt"]).0, 0);
std::fs::write(root.join("f.txt"), b"x\r\n").expect("write CRLF worktree state");
let before_index = run(root, &["git", "rev-parse", ":f.txt"]).1;
let before_worktree = std::fs::read(root.join("f.txt")).expect("read before worktree");
let error = apply_git_patch(&ApplyGitRequest {
cwd: root.to_path_buf(),
diff,
revert: false,
preflight: false,
})
.expect_err("literal text=set must fail closed");
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
assert!(error.to_string().contains("text=\"set\""), "{error}");
assert_eq!(run(root, &["git", "rev-parse", ":f.txt"]).1, before_index);
assert_eq!(
std::fs::read(root.join("f.txt")).expect("read after worktree"),
before_worktree
);
}
#[test]
fn sentinel_probe_populates_an_absent_path_in_its_copied_index() {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join(".gitattributes"), "new.txt text\n").expect("write attributes");
assert_eq!(run(root, &["git", "add", ".gitattributes"]).0, 0);
assert_eq!(run(root, &["git", "commit", "-m", "attributes"]).0, 0);
assert_eq!(run(root, &["git", "update-index", "--split-index"]).0, 0);
install_merge_policy(root, &["new.txt".to_string()])
.expect("classify special attributes for an absent patch destination");
assert_eq!(run(root, &["git", "ls-files", "--", "new.txt"]).1, "");
}
#[test]
fn three_way_sentinel_classifier_distinguishes_special_and_literal_states() {
for (attribute, spelling, special_token) in [
("merge", "set", "merge"),
("text", "unset", "-text"),
("whitespace", "unspecified", "!whitespace"),
] {
for (label, token, literal) in [
("special", special_token.to_string(), false),
("literal", format!("{attribute}={spelling}"), true),
] {
let repo = init_repo();
let root = repo.path();
std::fs::write(root.join(".gitattributes"), format!("f.txt {token}\n"))
.expect("write sentinel attributes");
std::fs::write(root.join("f.txt"), "content\n").expect("write tracked path");
assert_eq!(run(root, &["git", "add", "."]).0, 0);
assert_eq!(run(root, &["git", "commit", "-m", "fixture"]).0, 0);
let result = install_merge_policy(root, &["f.txt".to_string()]);
if literal {
let error = result.expect_err("literal sentinel must fail closed");
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
assert!(
error
.to_string()
.contains(&format!("{attribute}=\"{spelling}\"")),
"{attribute} {label}: {error}"
);
} else {
result.unwrap_or_else(|error| {
panic!("{attribute} {label} sentinel must be preserved: {error}")
});
}
}
}
}
#[test]
fn sentinel_probe_populates_an_absent_path_in_a_sha256_copied_index() {
let repo = tempfile::tempdir().expect("repo tempdir");
let root = repo.path();
let init = run(root, &["git", "init", "--object-format=sha256"]);
assert_eq!(init.0, 0, "initialize SHA-256 repository: {}", init.2);
assert_eq!(
run(root, &["git", "config", "user.email", "codex@example.com"]).0,
0
);
assert_eq!(run(root, &["git", "config", "user.name", "Codex"]).0, 0);
assert_eq!(run(root, &["git", "config", "core.autocrlf", "false"]).0, 0);
std::fs::write(root.join(".gitattributes"), "new.txt text\n").expect("write attributes");
assert_eq!(run(root, &["git", "add", ".gitattributes"]).0, 0);
assert_eq!(run(root, &["git", "commit", "-m", "attributes"]).0, 0);
install_merge_policy(root, &["new.txt".to_string()])
.expect("classify special attributes with a SHA-256 phantom entry");
assert_eq!(run(root, &["git", "ls-files", "--", "new.txt"]).1, "");
}
#[test]
fn apply_allows_unused_global_merge_driver() {
if std::env::var_os("CODEX_GIT_UTILS_MERGE_ENV_CHILD").is_none() {
@@ -134,7 +242,7 @@ fn apply_rejects_global_merge_driver_before_three_way() {
.expect_err("reject global merge driver");
assert_eq!(config_source_authorization_count(), 1);
assert_eq!(merge_config_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 2);
assert_eq!(merge_overlay_count(), 1);
assert_eq!(error.kind(), io::ErrorKind::Unsupported);
let (marker_code, _, _) = run(root, &["git", "config", "--get", "codex.mergeran"]);
@@ -818,7 +926,7 @@ fn three_way_apply_allows_unrelated_local_merge_driver() {
.expect("allow unrelated local merge driver during three-way fallback");
assert_eq!(config_source_authorization_count(), 1);
assert_eq!(merge_config_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 2);
assert_eq!(merge_overlay_count(), 1);
assert_eq!(result.exit_code, 0, "three-way apply: {}", result.stderr);
assert!(result.cmd_for_log.contains("--3way"));
@@ -804,6 +804,6 @@ fn reverse_three_way_with_staging_candidate_uses_one_authorization() {
assert_eq!(config_source_authorization_count(), 1);
assert_eq!(filter_policy_read_count(), 2);
assert_eq!(merge_config_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 1);
assert_eq!(merge_attribute_read_count(), 2);
assert_eq!(read_file_normalized(&root.join("file.txt")), expected);
}