diff --git a/crates/twigpine-node/src/api/pulls.rs b/crates/twigpine-node/src/api/pulls.rs index c6891cbfb..302d13dfe 100644 --- a/crates/twigpine-node/src/api/pulls.rs +++ b/crates/twigpine-node/src/api/pulls.rs @@ -224,6 +224,16 @@ pub async fn get_pr_diff( }))) } +fn merge_git_app_error(e: anyhow::Error) -> AppError { + if e.downcast_ref::() + .is_some() + { + AppError::RepoUnavailable + } else { + AppError::Git(e.to_string()) + } +} + /// POST /api/v1/repos/:owner/:repo/pulls/:number/merge pub async fn merge_pr( State(state): State, @@ -255,42 +265,145 @@ pub async fn merge_pr( .map_err(|e| crate::api::repos::acquire_write_app_error(&e, &name))?; let disk_path = guard.path().to_path_buf(); let merger_did = auth.0; + let git_timeout = std::time::Duration::from_secs(state.config.git_service_timeout_secs); + let Some(merge_deadline) = guard.hold_deadline(git_timeout) else { + let _ = guard.release(false).await; + return Err(AppError::RepoUnavailable); + }; + let git_bin = state.git_bin.clone(); // The source head this merge is about to consume, read under the write lock. // The PR row above was loaded before the lock, so a push landing in between // already moved the branch and the row's own `head_commit` is stale; the // value frozen on the merged PR has to be what was merged. `None` when the // ref cannot be resolved, which leaves whatever the push path last stored. + let source_ref = store::local_branch_ref(&pr.source_branch); let merged_source_head = - store::read_ref(&disk_path, &store::local_branch_ref(&pr.source_branch)) - .ok() - .flatten(); - // Snapshot the target ref's pre-merge OID so a refused durable upload can - // rewind the local merge, mirroring the close_issue / create_issue - // compensating pattern. A read failure or an absent ref (a first-commit - // merge onto an unborn branch) yields no rollback closure: the merge still - // applies and a refused publish still surfaces as 5xx. + match store::read_ref_at_deadline(&git_bin, &disk_path, &source_ref, merge_deadline) { + Ok(head) => head, + Err(e) => { + let app_error = merge_git_app_error(e); + let _ = guard.release(false).await; + return Err(app_error); + } + }; + // Snapshot the target ref's pre-merge OID so a refused durable upload or a + // merge child killed after it committed can rewind the local merge. An + // absent ref means no pre-merge tip could be proven, so there is no + // rollback closure: the merge still applies and a refused publish still + // surfaces as 5xx. let target_ref = format!("refs/heads/{}", pr.target_branch); - let git_timeout = std::time::Duration::from_secs(state.config.git_service_timeout_secs); - let prior_tip = store::read_ref_bounded(&state.git_bin, &disk_path, &target_ref, git_timeout) - .await - .ok() - .flatten(); + let prior_tip = + match store::read_ref_at_deadline(&git_bin, &disk_path, &target_ref, merge_deadline) { + Ok(tip) => tip, + Err(e) => { + let app_error = merge_git_app_error(e); + let _ = guard.release(false).await; + return Err(app_error); + } + }; let merge_result = store::merge_branch( + &git_bin, &disk_path, &pr.target_branch, &pr.source_branch, &merger_did, &pr.title, + merge_deadline, ); - // Always release the advisory lock — even on error; upload to Tigris only on success. - // Short-circuit on a refused publish before the PR is marked merged and + let merge_sha = match merge_result { + Ok(sha) => sha, + Err(store::MergeError::BeforeMerge(e)) => { + let app_error = merge_git_app_error(e); + let _ = guard.release(false).await; + return Err(app_error); + } + Err(store::MergeError::Merge(e)) => { + let recovery_deadline = std::time::Instant::now() + git_timeout; + let observed = + store::read_ref_at_deadline(&git_bin, &disk_path, &target_ref, recovery_deadline); + let restored = match observed { + Ok(observed) if observed == prior_tip => true, + Ok(Some(observed_tip)) => match prior_tip.as_deref() { + Some(prior_tip) => { + match store::update_ref_at_deadline( + &git_bin, + &disk_path, + &target_ref, + prior_tip, + &observed_tip, + recovery_deadline, + ) { + Ok(()) => true, + Err(rewind_error) => { + tracing::warn!( + repo = %name, + err = %rewind_error, + "could not rewind the target after a failed merge" + ); + false + } + } + } + None => false, + }, + Ok(None) => false, + Err(read_error) => { + tracing::warn!( + repo = %name, + err = %read_error, + "could not read the target after a failed merge" + ); + false + } + }; + if restored { + let app_error = merge_git_app_error(e); + let _ = guard.release(false).await; + return Err(app_error); + } + tracing::error!( + repo = %name, + "a failed merge could not be restored to its pre-merge tip; quarantining the tree" + ); + drop(guard); + return Err(AppError::RepoUnavailable); + } + Err(store::MergeError::AfterMerge(e)) => { + let recovery_deadline = std::time::Instant::now() + git_timeout; + match store::read_ref_at_deadline(&git_bin, &disk_path, &target_ref, recovery_deadline) + { + Ok(Some(sha)) => sha, + Ok(None) => { + tracing::error!( + repo = %name, + err = %e, + "a completed merge left no readable target ref; quarantining the tree" + ); + drop(guard); + return Err(AppError::RepoUnavailable); + } + Err(read_error) => { + tracing::error!( + repo = %name, + err = %read_error, + "a completed merge's target ref could not be read; quarantining the tree" + ); + drop(guard); + return Err(AppError::RepoUnavailable); + } + } + } + }; + + // Publish the successful merge and release the advisory lock. Short-circuit + // on a refused publish before the PR is marked merged and // before the webhook fires. Both are irreversible announcements of a merge // commit that only exists on this node's disk. - let release_result = match (merge_result.is_ok(), prior_tip) { - (true, Some(tip)) => { + let release_result = match prior_tip { + Some(tip) => { let git_bin = state.git_bin.clone(); let deadline = std::time::Instant::now() + git_timeout; guard @@ -307,12 +420,10 @@ pub async fn merge_pr( .await .into_result() } - _ => guard.release(merge_result.is_ok()).await.into_result(), + None => guard.release(true).await.into_result(), }; release_result?; - let merge_sha = merge_result.map_err(|e| AppError::Git(e.to_string()))?; - state .db .merge_pr(&pr.id, &merger_did, merged_source_head.as_deref()) @@ -553,6 +664,18 @@ mod tests { const OWNER_DID: &str = "did:key:z6MkpTHR8VNsBxYAAWHut2Geadd9jSwuBV8xRoAnwWsdvktH"; const STALE_SHA: &str = "9999999999999999999999999999999999999999"; + #[test] + fn merge_git_timeout_maps_to_repo_unavailable() { + let timeout: anyhow::Error = crate::git::smart_http::GitServiceTimeout.into(); + assert!(matches!( + merge_git_app_error(timeout), + AppError::RepoUnavailable + )); + assert!(matches!( + merge_git_app_error(anyhow::anyhow!("plain git failure")), + AppError::Git(_) + )); + } fn git(dir: &std::path::Path, args: &[&str]) { let out = Command::new("git") @@ -820,6 +943,403 @@ mod merge_rollback_tests { (root, tip2) } + #[allow(clippy::too_many_arguments)] + async fn merge_handler_fixture( + pool: &PgPool, + owner: &str, + repo_name: &str, + git_timeout_secs: u64, + tigris: Option, + ) -> ( + AppState, + tempfile::TempDir, + std::path::PathBuf, + String, + String, + ) { + let mut state = crate::test_support::test_state_with(pool.clone(), |c| { + c.git_service_timeout_secs = git_timeout_secs + }) + .await; + let disk = tempfile::TempDir::new().unwrap(); + let live = crate::git::repo_store::validated_repo_disk_path(disk.path(), owner, repo_name) + .expect("repo path"); + let (main_tip, _feature_tip) = seeded_merge_repo(&live); + + let mut seeded = crate::db::RepoRecord { + id: Uuid::new_v4().to_string(), + name: repo_name.to_string(), + owner_did: owner.to_string(), + description: None, + is_public: true, + default_branch: "main".to_string(), + created_at: Utc::now(), + updated_at: Utc::now(), + disk_path: String::new(), + forked_from: None, + machine_id: None, + }; + seeded.disk_path = live.to_string_lossy().to_string(); + let repo_id = seeded.id.clone(); + state.db.create_repo(&seeded).await.expect("seed repo"); + let now = Utc::now().to_rfc3339(); + state + .db + .create_pr(&PullRequest { + id: Uuid::new_v4().to_string(), + repo_id: repo_id.clone(), + number: 1, + title: "bounded".to_string(), + body: None, + author_did: owner.to_string(), + source_branch: "feature".to_string(), + target_branch: "main".to_string(), + status: "open".to_string(), + merged_by_did: None, + merged_at: None, + head_commit: None, + created_at: now.clone(), + updated_at: now, + }) + .await + .expect("seed PR"); + let lock_pool = + crate::git::repo_store::build_lock_pool(pool, 1, std::time::Duration::from_secs(1)); + state.repo_store = match tigris { + Some(tigris) => crate::git::repo_store::RepoStore::for_testing_with_tigris( + disk.path().to_path_buf(), + lock_pool, + tigris, + ), + None => { + crate::git::repo_store::RepoStore::for_testing(disk.path().to_path_buf(), lock_pool) + } + }; + (state, disk, live.to_path_buf(), repo_id, main_tip) + } + + async fn assert_pr_open(pool: &PgPool, repo_id: &str) { + let pr: (String,) = + sqlx::query_as("SELECT status FROM pull_requests WHERE repo_id = $1 AND number = 1") + .bind(repo_id) + .fetch_one(pool) + .await + .expect("read PR status"); + assert_eq!(pr.0, "open", "a failed merge must leave the PR open"); + } + + async fn assert_no_merged_webhook(pool: &PgPool) { + tokio::task::yield_now().await; + let count: (i64,) = sqlx::query_as( + "SELECT COUNT(*) FROM webhook_deliveries WHERE event = 'pull_request.merged'", + ) + .fetch_one(pool) + .await + .expect("count webhook deliveries"); + assert_eq!( + count.0, 0, + "a failed merge must not fire pull_request.merged" + ); + } + + async fn assert_lock_is_free(state: &AppState, owner: &str, repo_name: &str) { + let guard = state + .repo_store + .acquire_write(owner, repo_name) + .await + .expect("the merge must return the write lock promptly"); + guard + .release(false) + .await + .into_result() + .expect("probe release"); + } + + #[cfg(unix)] + fn write_shell_git(dir: &std::path::Path, body: &str) -> String { + use std::os::unix::fs::PermissionsExt; + let path = dir.join("git-wrapper"); + std::fs::write(&path, body).unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o755)).unwrap(); + path.to_str().unwrap().to_string() + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_hung_merge_is_503_leaves_pr_open_and_frees_the_lock(pool: PgPool) { + use crate::test_support::git_shim; + + let owner = "did:key:zMERGEHANGAAAAAAAAAAAAAAAAAAAAAAAAA"; + let repo_name = "hung-merge"; + let (mut state, _disk, live, repo_id, main_tip) = + merge_handler_fixture(&pool, owner, repo_name, 1, None).await; + state + .db + .create_webhook(&crate::db::Webhook { + id: Uuid::new_v4().to_string(), + repo_id: repo_id.clone(), + url: "http://127.0.0.1:1/hook".to_string(), + secret: None, + events: vec!["pull_request.merged".to_string()], + created_by_did: owner.to_string(), + created_at: Utc::now().to_rfc3339(), + active: true, + }) + .await + .expect("seed webhook"); + let shim = git_shim::create( + "gl-merge-pr-hang-git", + git_shim::Behavior::HangSubcommand("merge"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let started = std::time::Instant::now(); + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + let elapsed = started.elapsed(); + + let err = res.expect_err("a hung merge must be refused"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE, + "a merge child killed at the deadline is a retryable 503" + ); + assert!( + elapsed < std::time::Duration::from_secs(7), + "the merge must stop at its deadline plus teardown, not run the shim's 30s hang: {elapsed:?}" + ); + assert_pr_open(&pool, &repo_id).await; + assert_no_merged_webhook(&pool).await; + assert_eq!( + git(&live, &["rev-parse", "refs/heads/main"]), + main_tip, + "a merge killed before committing must leave main unmoved" + ); + assert_lock_is_free(&state, owner, repo_name).await; + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_rewinds_a_merge_that_committed_before_its_child_hung(pool: PgPool) { + use crate::git::repo_store::tests as rs_tests; + use crate::test_support::git_shim; + + let owner = "did:key:zMERGEREWINDHANGAAAAAAAAAAAAAAAAAAA"; + let repo_name = "rewind-hung-merge"; + let mock = rs_tests::S3Mock::start().await; + let (mut state, _disk, live, repo_id, main_tip) = merge_handler_fixture( + &pool, + owner, + repo_name, + 1, + Some(rs_tests::mock_tigris(&mock)), + ) + .await; + let shim = git_shim::create( + "gl-merge-pr-commit-hang-git", + git_shim::Behavior::CommitThenHang("merge"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + + let err = res.expect_err("a merge killed after committing must be refused"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE + ); + assert!( + shim.parent().unwrap().join("committed").exists(), + "the merge must have committed before the kill, or the rewind assertion is vacuous" + ); + assert_eq!( + git(&live, &["rev-parse", "refs/heads/main"]), + main_tip, + "the handler must rewind the possibly-published local merge" + ); + assert!( + !crate::git::repo_store::live_tree_publish_unresolved(&live), + "a successful rewind is released clean rather than quarantined" + ); + assert_pr_open(&pool, &repo_id).await; + mock.shutdown(); + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_quarantines_when_the_rewind_cannot_complete(pool: PgPool) { + use crate::git::repo_store::tests as rs_tests; + use crate::test_support::git_shim; + + let owner = "did:key:zMERGEQUARANTINEAAAAAAAAAAAAAAAAAA"; + let repo_name = "quarantine-merge"; + let mock = rs_tests::S3Mock::start().await; + let (mut state, _disk, live, _repo_id, _main_tip) = merge_handler_fixture( + &pool, + owner, + repo_name, + 1, + Some(rs_tests::mock_tigris(&mock)), + ) + .await; + let shim = git_shim::create( + "gl-merge-pr-rewind-stall-git", + git_shim::Behavior::CommitThenHangThenStall("merge", "update-ref"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + + let err = res.expect_err("an unrewound merge must be refused"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE + ); + assert!( + crate::git::repo_store::live_tree_publish_unresolved(&live), + "when the rewind cannot prove the pre-merge tip, the tree must be quarantined" + ); + mock.shutdown(); + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_rewind_failure_on_a_local_only_node_is_503_without_a_marker(pool: PgPool) { + use crate::test_support::git_shim; + + let owner = "did:key:zMERGELOCALONLYAAAAAAAAAAAAAAAAAAAA"; + let repo_name = "local-only-merge"; + let (mut state, _disk, live, _repo_id, _main_tip) = + merge_handler_fixture(&pool, owner, repo_name, 1, None).await; + let shim = git_shim::create( + "gl-merge-pr-local-rewind-stall-git", + git_shim::Behavior::CommitThenHangThenStall("merge", "update-ref"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + + let err = res.expect_err("an unrewound merge must be refused"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE + ); + assert!( + !crate::git::repo_store::live_tree_publish_unresolved(&live), + "a local-only node writes no quarantine marker" + ); + assert_lock_is_free(&state, owner, repo_name).await; + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_hung_source_head_read_is_503_before_the_merge(pool: PgPool) { + use crate::test_support::git_shim; + + let owner = "did:key:zMERGESOURCEHANGAAAAAAAAAAAAAAAAAAA"; + let repo_name = "source-hang-merge"; + let (mut state, _disk, live, repo_id, main_tip) = + merge_handler_fixture(&pool, owner, repo_name, 1, None).await; + let shim = git_shim::create( + "gl-merge-pr-source-hang-git", + git_shim::Behavior::HangSubcommand("rev-parse"), + ); + state.git_bin = shim.to_str().unwrap().to_string(); + + let started = std::time::Instant::now(); + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + let elapsed = started.elapsed(); + + let err = res.expect_err("a hung bounded read must refuse the merge"); + assert_eq!( + err.into_response().status(), + StatusCode::SERVICE_UNAVAILABLE + ); + assert!( + elapsed < std::time::Duration::from_secs(5), + "the source-head read must stop at the merge deadline: {elapsed:?}" + ); + assert_eq!( + git(&live, &["rev-parse", "refs/heads/main"]), + main_tip, + "the merge must not run when its source head cannot be read" + ); + assert_pr_open(&pool, &repo_id).await; + assert_lock_is_free(&state, owner, repo_name).await; + } + + #[cfg(unix)] + #[sqlx::test] + async fn merge_pr_after_merge_read_recovery_never_rewinds_a_completed_merge(pool: PgPool) { + let owner = "did:key:zMERGEAFTERMERGEAAAAAAAAAAAAAAAAAA"; + let repo_name = "after-merge-recovery"; + let (mut state, _disk, live, repo_id, _main_tip) = + merge_handler_fixture(&pool, owner, repo_name, 1, None).await; + let bin_dir = tempfile::TempDir::new().unwrap(); + let wrapper = write_shell_git( + bin_dir.path(), + r#"#!/bin/sh +dir=$(dirname "$0") +if [ "$1" = "merge" ]; then + git "$@" + code=$? + if [ "$code" -eq 0 ]; then + : > "$dir/hang-rev-parse" + fi + exit "$code" +fi +if [ "$1" = "rev-parse" ] && [ -e "$dir/hang-rev-parse" ]; then + rm -f "$dir/hang-rev-parse" + sleep 30 + exit 1 +fi +exec git "$@" +"#, + ); + state.git_bin = wrapper; + + let res = merge_pr( + State(state.clone()), + Extension(AuthenticatedDid(owner.to_string())), + Path((owner.to_string(), repo_name.to_string(), 1)), + ) + .await; + + let ok = res.expect("a readable post-merge target must continue as a successful merge"); + let sha = ok["merge_sha"].as_str().expect("merge sha").to_string(); + assert_eq!( + sha, + git(&live, &["rev-parse", "refs/heads/main"]), + "the observed target SHA is the merge result" + ); + let merged = state.db.get_pr(&repo_id, 1).await.unwrap().unwrap(); + assert_eq!(merged.status, "merged"); + } + /// On a definite publish refusal, the local merge commit must be rewound: /// the client got a 5xx, so the repo cannot show a merge the mirror never /// learned about (same contract create_issue's rollback enforces). diff --git a/crates/twigpine-node/src/git/repo_store.rs b/crates/twigpine-node/src/git/repo_store.rs index 4eecb54e5..006b72adf 100644 --- a/crates/twigpine-node/src/git/repo_store.rs +++ b/crates/twigpine-node/src/git/repo_store.rs @@ -512,12 +512,12 @@ impl RepoStore { .await } - /// For writers whose under-lock work never consults the hold deadline - /// (merge). Stamping one would only turn a slow but completed merge into a - /// refused publish and a rollback at release, while its unbounded git - /// already holds the lock past it. Issue writes keep the deadline: their - /// git is one ref write, so the deadline is what bounds their refresh and - /// publish. + /// For writers whose under-lock work must be allowed to finish once it has + /// started (merge). Merge bounds its own git children; stamping a lock-hold + /// deadline here would only make release refuse the publish and quarantine + /// a merge that had already completed. Issue writes keep the deadline: + /// their git is one ref write, so the deadline is what bounds their + /// refresh and publish. pub async fn acquire_write_without_hold_deadline( &self, owner_did: &str, diff --git a/crates/twigpine-node/src/git/store.rs b/crates/twigpine-node/src/git/store.rs index 32a0fcd81..2c0897b60 100644 --- a/crates/twigpine-node/src/git/store.rs +++ b/crates/twigpine-node/src/git/store.rs @@ -2416,17 +2416,15 @@ fn reject_revision_shorthand(name: &str) -> Option<&'static str> { /// advance refs/heads/{target}. /// /// Storage boundaries call this via [`validate_git_ref_with_git`] with the configured -/// git binary. Sink functions call [`validate_git_ref`] (system `git`) then prefix -/// before building argv, so the property holds for every caller and every row, -/// including legacy rows and any writer that skipped the boundary check. +/// git binary. Sink functions validate the local shape, then run the full git check +/// through the same bounded child budget as the sink, so the property holds for +/// every caller and every row, including legacy rows and any writer that skipped +/// the boundary check. pub fn validate_git_ref(name: &str) -> std::result::Result<(), GitRefValidationError> { validate_git_ref_with_git("git", name) } -pub(crate) fn validate_git_ref_with_git( - git_bin: &str, - name: &str, -) -> std::result::Result<(), GitRefValidationError> { +fn validate_git_ref_shape(name: &str) -> std::result::Result<(), GitRefValidationError> { if name.is_empty() { return Err(GitRefValidationError::Invalid( "branch ref must not be empty".into(), @@ -2450,6 +2448,14 @@ pub(crate) fn validate_git_ref_with_git( if let Some(reason) = reject_revision_shorthand(name) { return Err(GitRefValidationError::Invalid(reason.into())); } + Ok(()) +} + +pub(crate) fn validate_git_ref_with_git( + git_bin: &str, + name: &str, +) -> std::result::Result<(), GitRefValidationError> { + validate_git_ref_shape(name)?; let full_ref = local_branch_ref(name); // allow-unbounded-git: stateless check-ref-format on a fully qualified ref; no repo acquire or concurrency permit let output = Command::new(git_bin) @@ -2471,8 +2477,6 @@ pub(crate) fn validate_git_ref_with_git( } } -/// Reject both refs at the sink, so an option-shaped ref can never reach a git -/// argv element regardless of how it was stored. fn map_ref_validation_to_anyhow(which: &str, err: GitRefValidationError) -> anyhow::Error { match err { GitRefValidationError::Invalid(msg) => { @@ -2482,9 +2486,30 @@ fn map_ref_validation_to_anyhow(which: &str, err: GitRefValidationError) -> anyh } } -fn guard_refs(target_branch: &str, source_branch: &str) -> Result<()> { - validate_git_ref(target_branch).map_err(|e| map_ref_validation_to_anyhow("target", e))?; - validate_git_ref(source_branch).map_err(|e| map_ref_validation_to_anyhow("source", e))?; +fn guard_refs( + git_bin: &str, + repo_path: &Path, + target_branch: &str, + source_branch: &str, + deadline: std::time::Instant, +) -> Result<()> { + for (which, name) in [("target", target_branch), ("source", source_branch)] { + validate_git_ref_shape(name).map_err(|e| map_ref_validation_to_anyhow(which, e))?; + let full_ref = local_branch_ref(name); + let (status, _, _) = run_merge_child( + git_bin, + &["check-ref-format", &full_ref], + repo_path, + deadline, + &[], + )?; + if !status.success() { + return Err(map_ref_validation_to_anyhow( + which, + GitRefValidationError::Invalid("branch ref is not a valid Git branch name".into()), + )); + } + } Ok(()) } @@ -2502,7 +2527,7 @@ pub fn branch_diff( source_branch: &str, deadline: std::time::Instant, ) -> Result { - guard_refs(target_branch, source_branch)?; + guard_refs(git_bin, repo_path, target_branch, source_branch, deadline)?; let target = local_branch_ref(target_branch); let source = local_branch_ref(source_branch); let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( @@ -2531,7 +2556,7 @@ pub fn branch_diff_names( source_branch: &str, deadline: std::time::Instant, ) -> Result> { - guard_refs(target_branch, source_branch)?; + guard_refs(git_bin, repo_path, target_branch, source_branch, deadline)?; let target = local_branch_ref(target_branch); let source = local_branch_ref(source_branch); let (status, stdout, stderr) = crate::git::visibility_pack::run_bounded_git_raw( @@ -2556,16 +2581,118 @@ pub fn branch_diff_names( .collect()) } -/// Merge source_branch into target_branch in a bare repo using a temporary worktree. -/// Returns the new merge commit hash. +/// How far merge_branch got before failing. The handler reconciles only the +/// phases in which the target ref may have moved. +#[derive(Debug)] +pub enum MergeError { + BeforeMerge(anyhow::Error), + Merge(anyhow::Error), + AfterMerge(anyhow::Error), +} + +impl MergeError { + pub(crate) fn inner(&self) -> &anyhow::Error { + match self { + Self::BeforeMerge(e) | Self::Merge(e) | Self::AfterMerge(e) => e, + } + } +} + +impl std::fmt::Display for MergeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.inner().fmt(f) + } +} + +impl std::error::Error for MergeError {} + +fn run_merge_child( + git_bin: &str, + args: &[&str], + repo_path: &Path, + deadline: std::time::Instant, + env: &[(&str, &str)], +) -> Result<(std::process::ExitStatus, Vec, Vec)> { + if deadline + .saturating_duration_since(std::time::Instant::now()) + .is_zero() + { + return Err(crate::git::smart_http::GitServiceTimeout.into()); + } + crate::git::visibility_pack::run_bounded_git_raw_with_env( + git_bin, args, repo_path, b"", deadline, env, + ) +} + +/// Deadline-bounded single-ref read using rev-parse's present/absent split. +pub fn read_ref_at_deadline( + git_bin: &str, + repo_path: &Path, + ref_name: &str, + deadline: std::time::Instant, +) -> Result> { + let (status, stdout, stderr) = run_merge_child( + git_bin, + &["rev-parse", "--verify", "--quiet", ref_name], + repo_path, + deadline, + &[], + )?; + match status.code() { + Some(0) => { + let sha = String::from_utf8(stdout) + .context("git rev-parse output is not utf-8")? + .trim() + .to_string(); + Ok((!sha.is_empty()).then_some(sha)) + } + Some(1) => Ok(None), + _ => bail!( + "git rev-parse --verify {ref_name} failed: {}", + String::from_utf8_lossy(&stderr).trim() + ), + } +} + +/// Deadline-bounded compare-and-swap ref write. A nonzero exit is an error: +/// after a merge failure the caller must know whether the rewind landed. +pub fn update_ref_at_deadline( + git_bin: &str, + repo_path: &Path, + ref_name: &str, + new_value: &str, + old_value: &str, + deadline: std::time::Instant, +) -> Result<()> { + let (status, _, stderr) = run_merge_child( + git_bin, + &["update-ref", ref_name, new_value, old_value], + repo_path, + deadline, + &[], + )?; + if !status.success() { + bail!( + "git update-ref {ref_name} failed: {}", + String::from_utf8_lossy(&stderr).trim() + ); + } + Ok(()) +} + +/// Merge source_branch into target_branch in a bare repo using a temporary worktree, +/// with every child on the supplied deadline. Returns the new merge commit hash. pub fn merge_branch( + git_bin: &str, repo_path: &Path, target_branch: &str, source_branch: &str, author_did: &str, pr_title: &str, -) -> Result { - guard_refs(target_branch, source_branch)?; + deadline: std::time::Instant, +) -> std::result::Result { + guard_refs(git_bin, repo_path, target_branch, source_branch, deadline) + .map_err(MergeError::BeforeMerge)?; let source_ref = local_branch_ref(source_branch); let target_ref = local_branch_ref(target_branch); let worktree_path = repo_path.join("_merge_worktree"); @@ -2578,16 +2705,30 @@ pub fn merge_branch( // separate prune adds nothing: over every leftover state that can reach // here (registered/unregistered x directory present/gone/locked/corrupt) // `remove -f -f` plus the removal below already clears the registration. - let _ = Command::new("git") - .args([ + match run_merge_child( + git_bin, + &[ "worktree", "remove", "--force", "--force", "_merge_worktree", - ]) - .current_dir(repo_path) - .output(); + ], + repo_path, + deadline, + &[], + ) { + Ok((status, _, stderr)) if !status.success() => { + tracing::warn!( + stderr = %String::from_utf8_lossy(&stderr), + "merge worktree cleanup failed" + ); + } + Err(e) => { + tracing::warn!(err = %e, "merge worktree cleanup failed"); + } + _ => {} + } let _ = std::fs::remove_dir_all(&worktree_path); }; @@ -2611,20 +2752,18 @@ pub fn merge_branch( // --verify matches the full refname literally — no DWIM, no abbreviation — // so a same-named tag with no local branch fails here instead of being // silently resolved. - // - // allow-unbounded-git: read-only `show-ref --verify` on one literal refname, - // no network and no object walk. It also sits alongside the pre-existing bare - // `git diff`, `git merge` and `git rev-parse` spawns in this same function, - // all under the same acquire_write lock, so bounding only this one would not - // change the function's exposure. Bounding merge_branch as a whole is a - // separate change against already-reviewed code, tracked as follow-up. - let target_exists = Command::new("git") - .args(["show-ref", "--verify", "--quiet", &target_ref]) - .current_dir(repo_path) - .output() - .context("failed to run git show-ref")?; - if !target_exists.status.success() { - bail!("target branch {target_ref} does not exist as a local branch"); + let target_exists = run_merge_child( + git_bin, + &["show-ref", "--verify", "--quiet", &target_ref], + repo_path, + deadline, + &[], + ) + .map_err(MergeError::BeforeMerge)?; + if !target_exists.0.success() { + return Err(MergeError::BeforeMerge(anyhow::anyhow!( + "target branch {target_ref} does not exist as a local branch" + ))); } // (2) Check out the local target branch in the worktree. The bare short @@ -2632,21 +2771,19 @@ pub fn merge_branch( // refs/heads/{name} would detach, so a successful merge would not advance // refs/heads/{target}); step (1) guarantees the branch exists, so an // attached checkout is the only acceptable outcome — verified right below. - // - // allow-unbounded-git: local `worktree add`, no network. Same reasoning as the - // show-ref spawn above: the surrounding function's other git children are - // already bare under this lock, so this one is not the thing that would need - // bounding first. - let wt = Command::new("git") - .args(["worktree", "add", "_merge_worktree", target_branch]) - .current_dir(repo_path) - .output() - .context("failed to create worktree")?; - if !wt.status.success() { - bail!( + let wt = run_merge_child( + git_bin, + &["worktree", "add", "_merge_worktree", target_branch], + repo_path, + deadline, + &[], + ) + .map_err(MergeError::BeforeMerge)?; + if !wt.0.success() { + return Err(MergeError::BeforeMerge(anyhow::anyhow!( "git worktree add failed: {}", - String::from_utf8_lossy(&wt.stderr) - ); + String::from_utf8_lossy(&wt.2) + ))); } // The worktree's HEAD must be a symbolic ref to exactly refs/heads/{target}. @@ -2654,50 +2791,53 @@ pub fn merge_branch( // something other than the local target branch; a merge committed on it // would be thrown away by cleanup, so refuse before merging rather than // relying on any denylist of symbolic shapes. - // - // allow-unbounded-git: read-only `symbolic-ref` resolving one local HEAD, no - // network. Same reasoning as the two spawns above. - let head_ref = Command::new("git") - .args(["symbolic-ref", "--quiet", "HEAD"]) - .current_dir(&worktree_path) - .output() - .context("failed to run git symbolic-ref")?; - let head_ref_name = String::from_utf8_lossy(&head_ref.stdout).trim().to_string(); - if !head_ref.status.success() || head_ref_name != target_ref { + let head_ref = run_merge_child( + git_bin, + &["symbolic-ref", "--quiet", "HEAD"], + &worktree_path, + deadline, + &[], + ) + .map_err(MergeError::BeforeMerge)?; + let head_ref_name = String::from_utf8_lossy(&head_ref.1).trim().to_string(); + if !head_ref.0.success() || head_ref_name != target_ref { remove_worktree(); - bail!("merge worktree is not attached to {target_ref} (HEAD is {head_ref_name:?})"); + return Err(MergeError::BeforeMerge(anyhow::anyhow!( + "merge worktree is not attached to {target_ref} (HEAD is {head_ref_name:?})" + ))); } - // Run merge in worktree - let merge = Command::new("git") - .args([ - "merge", - "--no-ff", - &source_ref, - "-m", - &format!( - "Merge branch '{}' into {} ({})", - source_branch, target_branch, pr_title - ), - ]) - .current_dir(&worktree_path) - .env("GIT_AUTHOR_NAME", author_did) - .env("GIT_AUTHOR_EMAIL", format!("{}@gitlawb", author_did)) - .env("GIT_COMMITTER_NAME", author_did) - .env("GIT_COMMITTER_EMAIL", format!("{}@gitlawb", author_did)) - .output() - .context("failed to run git merge")?; - - let success = merge.status.success(); + let author_email = format!("{}@gitlawb", author_did); + let merge_message = format!( + "Merge branch '{}' into {} ({})", + source_branch, target_branch, pr_title + ); + let merge = run_merge_child( + git_bin, + &["merge", "--no-ff", &source_ref, "-m", &merge_message], + &worktree_path, + deadline, + &[ + ("GIT_AUTHOR_NAME", author_did), + ("GIT_AUTHOR_EMAIL", &author_email), + ("GIT_COMMITTER_NAME", author_did), + ("GIT_COMMITTER_EMAIL", &author_email), + ], + ); - // Always remove worktree + // Always remove worktree while deadline budget remains, including when the + // merge child itself was killed or never spawned. A skipped or failed + // cleanup is healed by the leading cleanup on the next merge. remove_worktree(); + let merge = merge.map_err(MergeError::Merge)?; + + let success = merge.0.success(); + let merge_stderr = String::from_utf8_lossy(&merge.2).into_owned(); if !success { - bail!( - "git merge failed: {}", - String::from_utf8_lossy(&merge.stderr) - ); + return Err(MergeError::Merge(anyhow::anyhow!( + "git merge failed: {merge_stderr}" + ))); } // (3) The merge only counts if the exact target ref now points at a commit. @@ -2707,19 +2847,23 @@ pub fn merge_branch( // the caller would mark the PR merged and fire the webhook. --verify plus // ^{commit} plus an explicit status check turn "target ref missing or not a // commit" into a hard failure before any of that happens. - let head = Command::new("git") - .args(["rev-parse", "--verify", &format!("{target_ref}^{{commit}}")]) - .current_dir(repo_path) - .output() - .context("failed to get merge commit")?; - if !head.status.success() { - bail!( + let verify_spec = format!("{target_ref}^{{commit}}"); + let head = run_merge_child( + git_bin, + &["rev-parse", "--verify", &verify_spec], + repo_path, + deadline, + &[], + ) + .map_err(MergeError::AfterMerge)?; + if !head.0.success() { + return Err(MergeError::AfterMerge(anyhow::anyhow!( "merge completed but {target_ref} does not resolve to a commit: {}", - String::from_utf8_lossy(&head.stderr) - ); + String::from_utf8_lossy(&head.2) + ))); } - Ok(String::from_utf8_lossy(&head.stdout).trim().to_string()) + Ok(String::from_utf8_lossy(&head.1).trim().to_string()) } /// Resolve a repo disk path: {repos_dir}/{owner_slug}/{repo_name}.git @@ -2786,6 +2930,424 @@ mod tests { ); } + #[cfg(unix)] + fn bare_merge_fixture(conflict: bool) -> (tempfile::TempDir, std::path::PathBuf, String) { + let td = tempfile::TempDir::new().unwrap(); + let work = td.path().join("work"); + std::fs::create_dir_all(&work).unwrap(); + let g = |args: &[&str], dir: &Path| { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .output() + .unwrap(); + assert!( + out.status.success(), + "git {args:?}: {}", + String::from_utf8_lossy(&out.stderr) + ); + }; + g(&["init", "-q"], &work); + g(&["config", "user.email", "t@t"], &work); + g(&["config", "user.name", "t"], &work); + std::fs::write(work.join("base.txt"), b"base\n").unwrap(); + g(&["add", "."], &work); + g(&["commit", "-qm", "base"], &work); + let main = { + let out = Command::new("git") + .args(["symbolic-ref", "--short", "HEAD"]) + .current_dir(&work) + .output() + .unwrap(); + String::from_utf8_lossy(&out.stdout).trim().to_string() + }; + g(&["checkout", "-q", "-b", "feature"], &work); + if conflict { + std::fs::write(work.join("base.txt"), b"feature\n").unwrap(); + } else { + std::fs::write(work.join("feat.txt"), b"feat\n").unwrap(); + } + g(&["add", "."], &work); + g(&["commit", "-qm", "feat"], &work); + g(&["checkout", "-q", &main], &work); + if conflict { + std::fs::write(work.join("base.txt"), b"main\n").unwrap(); + g(&["add", "."], &work); + g(&["commit", "-qm", "main"], &work); + } + + let bare = td.path().join("bare.git"); + g( + &[ + "clone", + "--bare", + "-q", + work.to_str().unwrap(), + bare.to_str().unwrap(), + ], + td.path(), + ); + (td, bare, main) + } + + #[cfg(unix)] + fn rev_parse(repo_path: &Path, spec: &str) -> String { + let out = Command::new("git") + .args(["rev-parse", spec]) + .current_dir(repo_path) + .output() + .unwrap(); + assert!( + out.status.success(), + "git rev-parse {spec}: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + #[cfg(unix)] + fn merge_call_deadline(secs: u64) -> std::time::Instant { + std::time::Instant::now() + std::time::Duration::from_secs(secs) + } + + #[cfg(unix)] + #[test] + fn merge_branch_hung_merge_times_out_without_moving_the_target() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let before = rev_parse(&bare, &format!("refs/heads/{main}")); + let shim = git_shim::create( + "gl-merge-hang-git", + git_shim::Behavior::HangSubcommand("merge"), + ); + let started = std::time::Instant::now(); + let result = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(1), + ); + let elapsed = started.elapsed(); + + assert!( + matches!(&result, Err(super::MergeError::Merge(e)) if e.downcast_ref::().is_some()), + "a hung merge child must be a merge-phase timeout, got {result:?}" + ); + assert!( + elapsed < std::time::Duration::from_secs(6), + "the bounded child must stop long before the shim's 30s hang: {elapsed:?}" + ); + assert_eq!( + rev_parse(&bare, &format!("refs/heads/{main}")), + before, + "a merge killed before it committed must leave the target unmoved" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_commit_then_hang_reports_that_the_merge_may_have_moved() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let before = rev_parse(&bare, &format!("refs/heads/{main}")); + let shim = git_shim::create( + "gl-merge-commit-hang-git", + git_shim::Behavior::CommitThenHang("merge"), + ); + let result = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(1), + ); + + assert!( + matches!(&result, Err(super::MergeError::Merge(e)) if e.downcast_ref::().is_some()), + "a merge killed after committing must be a merge-phase timeout, got {result:?}" + ); + assert!( + shim.parent().unwrap().join("committed").exists(), + "the shim must prove the merge committed before it hung" + ); + assert_ne!( + rev_parse(&bare, &format!("refs/heads/{main}")), + before, + "the target must have moved, or the reconcile case this feeds would be vacuous" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_hung_premerge_child_is_before_merge_and_never_merges() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let before = rev_parse(&bare, &format!("refs/heads/{main}")); + let shim = git_shim::create( + "gl-merge-worktree-hang-git", + git_shim::Behavior::HangSubcommand("worktree"), + ); + let started = std::time::Instant::now(); + let result = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(1), + ); + let elapsed = started.elapsed(); + + assert!( + matches!(&result, Err(super::MergeError::BeforeMerge(e)) if e.downcast_ref::().is_some()), + "a hung pre-merge child must be a before-merge timeout, got {result:?}" + ); + assert!( + elapsed < std::time::Duration::from_secs(9), + "the pre-merge children must be bounded, got {elapsed:?}" + ); + assert_eq!( + rev_parse(&bare, &format!("refs/heads/{main}")), + before, + "the merge must not run after a pre-merge timeout" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_expired_deadline_spawns_no_git_child() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let log = _td.path().join("subcommands.log"); + let shim = git_shim::create( + "gl-merge-expired-git", + git_shim::Behavior::LogSubcommands(&log), + ); + let result = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + std::time::Instant::now(), + ); + + assert!( + matches!(&result, Err(super::MergeError::BeforeMerge(e)) if e.downcast_ref::().is_some()), + "an expired deadline must refuse before the first spawn, got {result:?}" + ); + let spawned = std::fs::read_to_string(&log).unwrap_or_default(); + assert!( + spawned.is_empty(), + "an expired deadline must spawn no child, spawned: {spawned:?}" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_slow_but_completing_merge_keeps_identity_and_parents() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let shim = git_shim::create("gl-merge-delay-git", git_shim::Behavior::Delay(1500)); + let author = "did:key:zMergeIdentity"; + let merged = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + author, + "identity title", + merge_call_deadline(15), + ) + .expect("a merge whose children complete inside the deadline must succeed"); + + let parents = Command::new("git") + .args([ + "rev-list", + "--parents", + "-n", + "1", + &format!("refs/heads/{main}"), + ]) + .current_dir(&bare) + .output() + .unwrap(); + assert!(parents.status.success()); + assert_eq!( + String::from_utf8_lossy(&parents.stdout) + .split_whitespace() + .count(), + 3, + "the new tip must be a merge commit with two parents" + ); + assert_eq!(rev_parse(&bare, &format!("refs/heads/{main}")), merged); + let identity = Command::new("git") + .args(["log", "-1", "--format=%an%n%ae%n%cn%n%ce", &merged]) + .current_dir(&bare) + .output() + .unwrap(); + assert!(identity.status.success()); + let identity_text = String::from_utf8_lossy(&identity.stdout); + let lines: Vec<_> = identity_text.lines().collect(); + assert_eq!( + lines, + vec![ + author, + &format!("{author}@gitlawb"), + author, + &format!("{author}@gitlawb") + ], + "the merge commit must use the requested author and committer identity" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_conflict_stays_a_plain_merge_failure_and_does_not_move_target() { + let (_td, bare, main) = bare_merge_fixture(true); + let before = rev_parse(&bare, &format!("refs/heads/{main}")); + let result = merge_branch( + "git", + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(10), + ); + + assert!( + matches!(&result, Err(super::MergeError::Merge(e)) if e.downcast_ref::().is_none()), + "a conflict must stay a non-timeout merge failure, got {result:?}" + ); + assert_eq!( + rev_parse(&bare, &format!("refs/heads/{main}")), + before, + "a conflicting merge must leave the target unmoved" + ); + assert!( + !bare.join("_merge_worktree").exists(), + "the worktree must be removed after a merge conflict" + ); + } + + #[cfg(unix)] + #[test] + fn update_ref_at_deadline_passes_the_old_value_as_a_cas_guard() { + let tmp = tempfile::tempdir().unwrap(); + let log = tmp.path().join("args.log"); + let script = tmp.path().join("git"); + std::fs::write( + &script, + format!( + "#!/bin/sh\nprintf '%s\\n' \"$*\" > '{}'\nexit 0\n", + log.display() + ), + ) + .unwrap(); + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap(); + + super::update_ref_at_deadline( + script.to_str().unwrap(), + tmp.path(), + "refs/heads/main", + "newtip", + "oldtip", + std::time::Instant::now() + std::time::Duration::from_secs(5), + ) + .expect("the fake update-ref succeeds"); + assert_eq!( + std::fs::read_to_string(&log).unwrap().trim(), + "update-ref refs/heads/main newtip oldtip", + "the rewind must compare the observed tip before replacing it" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_uses_the_configured_git_binary_for_every_child() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let log = _td.path().join("subcommands.log"); + let shim = git_shim::create("gl-merge-log-git", git_shim::Behavior::LogSubcommands(&log)); + merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(15), + ) + .expect("the forwarding shim must complete the merge"); + + let logged_text = std::fs::read_to_string(&log).expect("the shim must log every child"); + let logged: Vec<_> = logged_text.lines().collect(); + assert_eq!( + logged, + vec![ + "check-ref-format", + "check-ref-format", + "worktree", + "show-ref", + "worktree", + "symbolic-ref", + "merge", + "worktree", + "rev-parse" + ], + "every merge child, including validation and both cleanups, must use the configured git binary" + ); + } + + #[cfg(unix)] + #[test] + fn merge_branch_after_a_killed_merge_heals_the_worktree_on_the_next_call() { + use crate::test_support::git_shim; + + let (_td, bare, main) = bare_merge_fixture(false); + let shim = git_shim::create( + "gl-merge-heal-hang-git", + git_shim::Behavior::HangSubcommand("merge"), + ); + let first = merge_branch( + shim.to_str().unwrap(), + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(1), + ); + assert!(first.is_err(), "the first merge must time out"); + drop(shim); + + merge_branch( + "git", + &bare, + &main, + "feature", + "did:key:zMergeTest", + "t", + merge_call_deadline(10), + ) + .expect("the next merge must heal a leftover worktree registration"); + } + #[test] fn validate_git_ref_accepts_normal_branch_names() { for good in [ @@ -4348,8 +4910,16 @@ mod tests { .unwrap(); let before = String::from_utf8_lossy(&before.stdout).trim().to_string(); - let merged = merge_branch(&bare, &main, "feature", "did:key:zTest", "t") - .expect("a stale worktree registration must not wedge the merge endpoint"); + let merged = merge_branch( + "git", + &bare, + &main, + "feature", + "did:key:zTest", + "t", + std::time::Instant::now() + std::time::Duration::from_secs(10), + ) + .expect("a stale worktree registration must not wedge the merge endpoint"); let after = Command::new("git") .args(["rev-parse", &format!("refs/heads/{main}")]) @@ -4425,8 +4995,16 @@ mod tests { .unwrap(); let before = String::from_utf8_lossy(&before.stdout).trim().to_string(); - let merged = merge_branch(&bare, &main, "feature", "did:key:zTest", "t") - .expect("a locked leftover worktree must not wedge the merge endpoint"); + let merged = merge_branch( + "git", + &bare, + &main, + "feature", + "did:key:zTest", + "t", + std::time::Instant::now() + std::time::Duration::from_secs(10), + ) + .expect("a locked leftover worktree must not wedge the merge endpoint"); let after = Command::new("git") .args(["rev-parse", &format!("refs/heads/{main}")]) @@ -4508,8 +5086,16 @@ mod tests { .unwrap(); let before = String::from_utf8_lossy(&before.stdout).trim().to_string(); - let merged = merge_branch(&bare, &main, "feature", "did:key:zTest", "t") - .expect("an unregistered leftover directory must not wedge the merge endpoint"); + let merged = merge_branch( + "git", + &bare, + &main, + "feature", + "did:key:zTest", + "t", + std::time::Instant::now() + std::time::Duration::from_secs(10), + ) + .expect("an unregistered leftover directory must not wedge the merge endpoint"); let after = Command::new("git") .args(["rev-parse", &format!("refs/heads/{main}")]) diff --git a/crates/twigpine-node/src/git/visibility_pack.rs b/crates/twigpine-node/src/git/visibility_pack.rs index d59dff8cb..e22917632 100644 --- a/crates/twigpine-node/src/git/visibility_pack.rs +++ b/crates/twigpine-node/src/git/visibility_pack.rs @@ -53,6 +53,7 @@ fn git_child_command( repo_path: &Path, isolated_https: bool, isolated_config: &[(&str, &str)], + env: &[(&str, &str)], ) -> std::process::Command { let mut command = std::process::Command::new(git_bin); command @@ -87,6 +88,9 @@ fn git_child_command( } } } + for (key, value) in env { + command.env(key, value); + } command } @@ -128,6 +132,7 @@ fn child_terminated_without_reaping(pid: i32) -> bool { } #[cfg(unix)] +#[allow(clippy::too_many_arguments)] fn run_bounded_git_raw_impl( git_bin: &str, args: &[&str], @@ -136,6 +141,7 @@ fn run_bounded_git_raw_impl( deadline: Instant, isolated_https: bool, isolated_config: &[(&str, &str)], + env: &[(&str, &str)], ) -> Result<(std::process::ExitStatus, Vec, Vec)> { let mut out = Vec::new(); let (status, err, _stopped) = run_bounded_git_sink_impl( @@ -146,6 +152,7 @@ fn run_bounded_git_raw_impl( deadline, isolated_https, isolated_config, + env, &mut |chunk| { out.extend_from_slice(chunk); true @@ -168,6 +175,7 @@ fn run_bounded_git_sink_impl( deadline: Instant, isolated_https: bool, isolated_config: &[(&str, &str)], + env: &[(&str, &str)], on_chunk: &mut dyn FnMut(&[u8]) -> bool, ) -> Result<(std::process::ExitStatus, Vec, bool)> { use std::io::{Read, Write}; @@ -175,7 +183,14 @@ fn run_bounded_git_sink_impl( use std::sync::mpsc::RecvTimeoutError; let label = args.first().copied().unwrap_or("git"); - let mut command = git_child_command(git_bin, args, repo_path, isolated_https, isolated_config); + let mut command = git_child_command( + git_bin, + args, + repo_path, + isolated_https, + isolated_config, + env, + ); let mut child = command .process_group(0) .spawn() @@ -314,7 +329,39 @@ pub(crate) fn run_bounded_git_raw( stdin_bytes: &[u8], deadline: Instant, ) -> Result<(std::process::ExitStatus, Vec, Vec)> { - run_bounded_git_raw_impl(git_bin, args, repo_path, stdin_bytes, deadline, false, &[]) + run_bounded_git_raw_impl( + git_bin, + args, + repo_path, + stdin_bytes, + deadline, + false, + &[], + &[], + ) +} + +/// Bounded git with caller-supplied environment entries, otherwise exactly +/// [`run_bounded_git_raw`]. The entries overlay the inherited environment, so +/// caller-supplied keys win over ambient values. +pub(crate) fn run_bounded_git_raw_with_env( + git_bin: &str, + args: &[&str], + repo_path: &Path, + stdin_bytes: &[u8], + deadline: Instant, + env: &[(&str, &str)], +) -> Result<(std::process::ExitStatus, Vec, Vec)> { + run_bounded_git_raw_impl( + git_bin, + args, + repo_path, + stdin_bytes, + deadline, + false, + &[], + env, + ) } /// Bounded git whose stdout is handed to `on_chunk` as it arrives instead of @@ -340,6 +387,7 @@ pub(crate) fn run_bounded_git_streaming( deadline, false, &[], + &[], on_chunk, ) } @@ -370,7 +418,16 @@ pub(crate) fn run_bounded_git_raw_isolated_https( stdin_bytes: &[u8], deadline: Instant, ) -> Result<(std::process::ExitStatus, Vec, Vec)> { - run_bounded_git_raw_impl(git_bin, args, repo_path, stdin_bytes, deadline, true, &[]) + run_bounded_git_raw_impl( + git_bin, + args, + repo_path, + stdin_bytes, + deadline, + true, + &[], + &[], + ) } /// Isolated HTTPS runner with command-scope Git configuration supplied as @@ -392,6 +449,7 @@ pub(crate) fn run_bounded_git_raw_isolated_https_with_config( deadline, true, config, + &[], ) } @@ -428,6 +486,7 @@ pub(crate) fn run_bounded_git( /// the Unix version's signature and result semantics so every caller compiles on all /// targets (#174). #[cfg(not(unix))] +#[allow(clippy::too_many_arguments)] fn run_bounded_git_raw_impl( git_bin: &str, args: &[&str], @@ -436,14 +495,22 @@ fn run_bounded_git_raw_impl( deadline: Instant, isolated_https: bool, isolated_config: &[(&str, &str)], + env: &[(&str, &str)], ) -> Result<(std::process::ExitStatus, Vec, Vec)> { use std::io::{Read, Write}; use std::sync::mpsc::RecvTimeoutError; let label = args.first().copied().unwrap_or("git"); - let mut child = git_child_command(git_bin, args, repo_path, isolated_https, isolated_config) - .spawn() - .with_context(|| format!("failed to spawn git {label}"))?; + let mut child = git_child_command( + git_bin, + args, + repo_path, + isolated_https, + isolated_config, + env, + ) + .spawn() + .with_context(|| format!("failed to spawn git {label}"))?; let mut stdin = child.stdin.take(); let input = stdin_bytes.to_vec(); @@ -3194,6 +3261,64 @@ mod tests { ); } + #[cfg(unix)] + #[test] + fn run_bounded_git_raw_with_env_overlays_only_the_supplied_environment() { + let tmp = TempDir::new().unwrap(); + let body = "#!/bin/sh\nprintf '%s' \"${TWIGPINE_ENV_PROBE:-}\"\n"; + let git_bin = write_fake_git(tmp.path(), body); + let deadline = std::time::Instant::now() + SH_STARTUP_HEADROOM; + + let (status, out, _) = + run_bounded_git_raw(&git_bin, &["rev-parse"], tmp.path(), b"", deadline) + .expect("plain bounded child"); + assert!(status.success()); + assert!( + out.is_empty(), + "the plain runner must not inject the probe variable" + ); + + let (status, out, _) = run_bounded_git_raw_with_env( + &git_bin, + &["rev-parse"], + tmp.path(), + b"", + deadline, + &[("TWIGPINE_ENV_PROBE", "present")], + ) + .expect("env-carrying bounded child"); + assert!(status.success()); + assert_eq!(out, b"present"); + } + + #[test] + fn run_bounded_git_raw_with_env_supplies_git_commit_identity() { + let tmp = TempDir::new().unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + let (status, out, err) = run_bounded_git_raw_with_env( + "git", + &["var", "GIT_AUTHOR_IDENT"], + tmp.path(), + b"", + deadline, + &[ + ("GIT_AUTHOR_NAME", "Merge Author"), + ("GIT_AUTHOR_EMAIL", "merge@example.com"), + ], + ) + .expect("git var runs"); + assert!( + status.success(), + "git var failed: {}", + String::from_utf8_lossy(&err) + ); + let ident = String::from_utf8_lossy(&out); + assert!( + ident.starts_with("Merge Author "), + "the child must see the supplied identity, got {ident:?}" + ); + } + /// #174 (F1 status-gate, vetted by execution): a child that exits SUCCESSFULLY is /// never reported as a timeout even when the watchdog fires, so a walk finishing /// right at its deadline is not a spurious 504. The fake only exits when signalled diff --git a/crates/twigpine-node/src/test_git_shim.rs b/crates/twigpine-node/src/test_git_shim.rs index e088bc2aa..38b048246 100644 --- a/crates/twigpine-node/src/test_git_shim.rs +++ b/crates/twigpine-node/src/test_git_shim.rs @@ -12,7 +12,11 @@ pub(crate) enum Behavior<'a> { Hang, HangOid(&'a str), HangRepo(&'a str), + HangSubcommand(&'a str), + CommitThenHang(&'a str), + CommitThenHangThenStall(&'a str, &'a str), LogTypes(&'a Path), + LogSubcommands(&'a Path), FailAfterUpdateRef, /// Like `FailAfterUpdateRef`, and a ref delete never returns. StallRefDelete, @@ -71,7 +75,13 @@ pub(crate) fn create(name: &str, behavior: Behavior<'_>) -> GitShim { Behavior::Hang => "hang\n".to_owned(), Behavior::HangOid(oid) => format!("hang-oid\n{oid}"), Behavior::HangRepo(repo) => format!("hang-repo\n{repo}"), + Behavior::HangSubcommand(subcommand) => format!("hang-subcommand\n{subcommand}"), + Behavior::CommitThenHang(subcommand) => format!("commit-then-hang\n{subcommand}"), + Behavior::CommitThenHangThenStall(commit, stall) => { + format!("commit-then-hang-then-stall\n{commit}\n{stall}") + } Behavior::LogTypes(path) => format!("log-types\n{}", path.display()), + Behavior::LogSubcommands(path) => format!("log-subcommands\n{}", path.display()), Behavior::FailAfterUpdateRef => "fail-after-update-ref\n".to_owned(), Behavior::StallRefDelete => "stall-ref-delete\n".to_owned(), }; diff --git a/crates/twigpine-node/tests/fixtures/git_shim.rs b/crates/twigpine-node/tests/fixtures/git_shim.rs index 2a1272e23..ca5baedff 100644 --- a/crates/twigpine-node/tests/fixtures/git_shim.rs +++ b/crates/twigpine-node/tests/fixtures/git_shim.rs @@ -2,11 +2,31 @@ use std::io::{Read, Write}; use std::process::{Command, Stdio}; use std::time::Duration; +fn first_subcommand(args: &[std::ffi::OsString]) -> Option { + let mut skip_value = false; + for arg in args { + if skip_value { + skip_value = false; + continue; + } + if arg == "-c" { + skip_value = true; + continue; + } + return Some(arg.to_string_lossy().into_owned()); + } + None +} + fn main() -> std::io::Result<()> { let executable = std::env::current_exe()?; let config = std::fs::read_to_string(executable.parent().unwrap().join("config"))?; - let (mode, parameter) = config.split_once('\n').unwrap_or((&config, "")); + let mut lines = config.lines(); + let mode = lines.next().unwrap_or(""); + let parameter = lines.next().unwrap_or(""); + let second_parameter = lines.next().unwrap_or(""); let args: Vec<_> = std::env::args_os().skip(1).collect(); + let subcommand = first_subcommand(&args); if mode == "delay" { std::thread::sleep(Duration::from_millis(parameter.parse().unwrap())); } @@ -21,6 +41,8 @@ fn main() -> std::io::Result<()> { let cwd = std::env::current_dir()?; let hang = mode == "hang" || (mode == "hang-repo" && cwd.file_name().is_some_and(|name| name == parameter)) + || (mode == "hang-subcommand" && subcommand.as_deref() == Some(parameter)) + || (mode == "commit-then-hang-then-stall" && subcommand.as_deref() == Some(second_parameter)) || (mode == "stall-ref-delete" && args.first().is_some_and(|arg| arg == "update-ref") && args.get(1).is_some_and(|arg| arg == "-d")) @@ -45,6 +67,13 @@ fn main() -> std::io::Result<()> { cwd.file_name().unwrap().to_string_lossy() )?; } + if mode == "log-subcommands" { + let mut log = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(parameter)?; + writeln!(log, "{}", subcommand.as_deref().unwrap_or(""))?; + } let mut child = Command::new("git") .args(&args) .stdin(if input.is_some() { @@ -59,6 +88,13 @@ fn main() -> std::io::Result<()> { child.stdin.take().unwrap().write_all(&bytes)?; } let code = child.wait()?.code().unwrap_or(1); + let commit_then_hang = (mode == "commit-then-hang" && subcommand.as_deref() == Some(parameter)) + || (mode == "commit-then-hang-then-stall" && subcommand.as_deref() == Some(parameter)); + if commit_then_hang && code == 0 { + std::fs::write(executable.parent().unwrap().join("committed"), b"1")?; + std::thread::sleep(Duration::from_secs(30)); + std::process::exit(1); + } // A ref write that commits and then reports failure, the state a runner // that kills a child at its deadline cannot tell from a clean failure. let committed_then_failed = (mode == "fail-after-update-ref" || mode == "stall-ref-delete")