Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
7af3067
fix(node): close the advisory-lock probe's session if it is dropped m…
beardthelion Jul 29, 2026
edcf0f2
fix(node): add a dedicated, lazily-connected advisory-lock pool
beardthelion Jul 29, 2026
5ce3c7f
fix(node): hold the lock-owning connection in RepoWriteGuard (#279)
beardthelion Jul 29, 2026
c49d3cd
fix(node): free the advisory lock when a write guard dies without rel…
beardthelion Jul 29, 2026
98f2daf
fix(node): read the advisory unlock's result instead of discarding it
beardthelion Jul 29, 2026
9321d3b
fix(node): bound the object-storage transfers that run under the writ…
beardthelion Jul 29, 2026
9da0939
fix(node): authorize before taking the write lock in close_issue
beardthelion Jul 29, 2026
5d254fb
fix(node): address the review findings on the advisory-lock series
beardthelion Jul 30, 2026
d346bde
fix(node): log lock-pool saturation in the request path, not via read…
beardthelion Jul 30, 2026
82143ad
fix(node): refuse a write when object storage is unknowable, and shed…
beardthelion Jul 30, 2026
8cf6b7a
fix(node): re-authorize close_issue under the guard instead of only r…
beardthelion Jul 30, 2026
af5948b
style(node): rustfmt the new contention test
beardthelion Jul 30, 2026
e5558fb
fix(node): shed an unrefreshable write as a retryable 503 with a fixe…
beardthelion Aug 3, 2026
63a9ef8
fix(node): refuse a fresh-copy write when the archive HEAD cannot be …
beardthelion Aug 3, 2026
10230ac
fix(node): log expected transient acquire failures at warn, not error
beardthelion Aug 3, 2026
259d587
fix(node): log the read failure the close_issue pre-check folds into …
beardthelion Aug 3, 2026
999ee72
test(node): poll for the closed session instead of sleeping a fixed 3…
beardthelion Aug 3, 2026
5fdb902
fix(node): raise a failed fresh download with no local copy as RepoUn…
beardthelion Aug 9, 2026
f81ebbe
test(node): assert the second writer sheds as RepoBusy instead of tim…
beardthelion Aug 9, 2026
c4dbd8a
fix(node): read the close_issue author pre-check from a non-mutating …
beardthelion Aug 10, 2026
9f313b9
fix(node): bound every await in the lock-acquire loop by the deadline
beardthelion Aug 10, 2026
60d70c7
test(node): add an S3 mock that really enforces conditional writes
beardthelion Aug 10, 2026
31f90c4
fix(node): stop pretending a held lock fences a late upload
beardthelion Aug 10, 2026
3eabf79
feat(node): let the storage client express and detect a conditional w…
beardthelion Aug 10, 2026
317841e
fix(node): fence the release publish so an abandoned upload cannot win
beardthelion Aug 10, 2026
3d803ff
test(node): drive the abandoned-upload race end to end, and probe the…
beardthelion Aug 10, 2026
2a92a1f
fix(node): reconcile F-series tests and test seams with the rebased g…
beardthelion Aug 18, 2026
9f35dca
fix(node): address the 2026-08-10 review round on the advisory-lock s…
beardthelion Aug 18, 2026
9dd71e9
fix(node): record why the close-issue read gate cannot carry a synced…
beardthelion Aug 18, 2026
4cee7e0
merge origin/main into fix/279-advisory-lock-session-affinity
beardthelion Aug 26, 2026
b35cb31
fix(node): address jatmn review on merged advisory-lock head
beardthelion Aug 26, 2026
3c20148
fix(node): cap close_issue snapshot work on the read pool
beardthelion Aug 26, 2026
7ba0fef
fix(node): mark close_issue mirror visibility gate for push hook
beardthelion Aug 26, 2026
3df71c9
fix: unblock pre-push after main merge
beardthelion Aug 26, 2026
98fe670
fix(node): carry transient acquire failures through every write handler
beardthelion Aug 28, 2026
4f1c1bb
fix(node): drop unused logcap helper after drain_faults seam
beardthelion Aug 28, 2026
4eb0c44
fix(node): route fork disk paths through validated_repo_disk_path
beardthelion Aug 28, 2026
d1ce2e3
fix(node): harden release-upload outcomes and replication tail gating
beardthelion Aug 28, 2026
8e66e77
fix(node): close jatmn round on publish authority and durability gating
beardthelion Aug 29, 2026
1911291
fix(node): harden issue close/create and fork publish paths on #285
beardthelion Aug 29, 2026
5d3a4ea
fix(node): close write-attempt ownership gaps on advisory-lock release
beardthelion Aug 29, 2026
2ad2f12
fix(node): gate replication tail on publish durability and split clos…
beardthelion Aug 29, 2026
487687c
fix(node): add ValidatedRepoDiskPath for CodeQL and reconcile tail du…
beardthelion Aug 29, 2026
9d02139
fix(node): close three jatmn findings on advisory-lock PR
beardthelion Aug 30, 2026
85c6f48
fix(node): verify adversarial findings on advisory-lock PR
beardthelion Aug 30, 2026
5cd6703
fix(node): compensate under the write lock and harden tail durability…
beardthelion Aug 30, 2026
22da2d6
fix(node): refuse stale under-lock refresh and gate tail durability o…
beardthelion Aug 30, 2026
c306933
style(node): rustfmt advisory-lock gap-closure commits
beardthelion Aug 30, 2026
3a82ccb
fix(node): satisfy clippy on stale-local download test path join
beardthelion Aug 30, 2026
c40f299
feat(node): add a publish attempt/stage boundary
kevincodex1 Aug 31, 2026
21646bc
feat(node): stamp uploads with an attempt id and preserve dispatch am…
kevincodex1 Aug 31, 2026
5e548d2
fix(node): key durability, cache validity and fork cleanup on the att…
kevincodex1 Aug 31, 2026
535c5dc
fix(node): settle the cache contract on the abandoned path and the at…
beardthelion Sep 7, 2026
f048a1e
fix(node): settle the abandoned tree at the disconnect, not at reaper…
beardthelion Sep 7, 2026
957d50b
fix(node): let exactly one classifier settle an abandoned tree
beardthelion Sep 7, 2026
892c752
Merge origin/main into fix/279-advisory-lock-session-affinity
beardthelion Nov 4, 2026
28f3fc2
test(node): use the test's own pool now that Db::pool is gone
beardthelion Nov 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(node): close write-attempt ownership gaps on advisory-lock release
Make publish swaps claim-exclusive via CAS, invalidate the local read cache
on definite publish refusals, harden fork create compensation and clone
cleanup, and keep snapshot temp dirs owned through the async handoff.
  • Loading branch information
beardthelion committed Aug 29, 2026
commit 5d3a4ea462631c5b641f5d32faeb3713801965ec
65 changes: 54 additions & 11 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use axum::http::StatusCode;
use axum::response::Response;
use axum::Json;
use bytes::Bytes;
use std::path::PathBuf;
use std::sync::Arc;

use crate::auth::{caller_authorized_to_push, AuthenticatedDid};
Expand Down Expand Up @@ -3121,6 +3122,40 @@ pub async fn list_federated_repos(

// ── Fork ──────────────────────────────────────────────────────────────────

/// Removes a fork's local mirror clone on every exit until disarmed after the
/// database row commits.
struct ForkCloneGuard(Option<PathBuf>);

impl ForkCloneGuard {
fn new(path: PathBuf) -> Self {
Self(Some(path))
}

fn path(&self) -> &std::path::Path {
self.0
.as_deref()
.expect("fork clone guard disarmed while still in use")
}

fn disarm(&mut self) {
self.0 = None;
}
}

impl Drop for ForkCloneGuard {
fn drop(&mut self) {
if let Some(path) = self.0.take() {
if let Err(e) = std::fs::remove_dir_all(&path) {
tracing::warn!(
path = %path.display(),
err = %e,
"failed to remove fork clone during attempt cleanup"
);
}
}
}
}

#[derive(Debug, Deserialize)]
pub struct ForkRepoRequest {
pub name: Option<String>, // defaults to source repo name
Expand Down Expand Up @@ -3216,12 +3251,14 @@ pub async fn fork_repo(
)));
}

let mut clone_guard = ForkCloneGuard::new(disk_path.clone());

// Upload fork to Tigris. Create-only: a refused precondition means an orphan
// archive already sits under this key (a failed create_repo or another
// writer), and proceeding would create a DB record whose archive is shadowed
// by bytes that are not this fork. Refuse rather than accept a fork other
// nodes would fetch as unrelated content. Remove the local mirror clone so
// a refused fork does not leave a bare repo on disk.
// nodes would fetch as unrelated content. The clone guard removes the local
// mirror on every upload failure path.
state
.repo_store
.release_after_write(&forker_did, &fork_name)
Expand All @@ -3234,13 +3271,6 @@ pub async fn fork_repo(
status,
"fork refused: an archive already exists under the fork's key"
);
if let Err(clean) = std::fs::remove_dir_all(&disk_path) {
tracing::warn!(
path = %disk_path.display(),
err = %clean,
"failed to remove fork clone after precondition loss"
);
}
AppError::RepoExists(fork_name.clone())
}
other => AppError::Git(format!("fork upload failed: {other}")),
Expand All @@ -3256,19 +3286,32 @@ pub async fn fork_repo(
default_branch: source.default_branch.clone(),
created_at: now,
updated_at: now,
disk_path: disk_path.to_string_lossy().to_string(),
disk_path: clone_guard.path().to_string_lossy().to_string(),
forked_from: Some(source.id.clone()),
machine_id: state.machine_id.clone(),
};

if let Err(e) = state.db.create_repo(&record).await {
if let Some(committed) = state.db.get_repo(&forker_short, &fork_name).await? {
clone_guard.disarm();
tracing::warn!(
fork = %fork_name,
forker = %forker_did,
"fork create_repo returned an error but the row is present — treating as success"
);
return Ok((StatusCode::CREATED, Json(to_response(&committed, &state, 0))));
}
clone_guard.disarm();
let disk_path_for_compensate = disk_path.clone();
state
.repo_store
.compensate_fork_archive(&forker_did, &fork_name, &disk_path)
.compensate_fork_archive(&forker_did, &fork_name, &disk_path_for_compensate)
.await;
return Err(e.into());
}

clone_guard.disarm();

// Persist the proof so the fork carries it when it propagates to peers.
if let Some(p) = verified_proof {
if let Err(e) = p.record_for_repo(&state.db, &record.id).await {
Expand Down
142 changes: 128 additions & 14 deletions crates/gitlawb-node/src/git/repo_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,10 +255,12 @@ impl RepoStore {
"tigris snapshot download failed during read_snapshot for {owner_slug}/{repo_name}: {e:#}"
))
})?;
return Ok(RepoSnapshot {
path: snapshot.clone(),
owned: true,
});
return match snapshot {
super::tigris::DownloadExtract::Snapshot(dir) => Ok(dir.into_repo_snapshot()),
super::tigris::DownloadExtract::Published(_) => {
unreachable!("snapshot downloads never publish into the live path")
}
};
}
Ok(false) => {}
Err(e) => {
Expand Down Expand Up @@ -588,7 +590,7 @@ impl RepoStore {
//
// Refuse the acquire. Returning here drops the guard, whose Drop
// frees the lock and its pool slot.
refresh_swap_authority.store(false, Ordering::Release);
revoke_swap_authority(&refresh_swap_authority);
//
// `error!`, not the sibling `warn!` above, and that is deliberate.
// The handler layer demotes every `RepoUnavailable` to warn because
Expand Down Expand Up @@ -716,7 +718,9 @@ impl RepoStore {

/// Best-effort cleanup when fork creation published an archive but failed to persist
/// the database row. Removes the object-store key this attempt owns and the local
/// mirror clone so a retry is not blocked by its own orphan.
/// mirror clone so a retry is not blocked by its own orphan. Object-store deletion
/// is retried asynchronously when the first attempt fails so a transient DELETE does
/// not tombstone the fork name.
pub async fn compensate_fork_archive(
&self,
owner_did: &str,
Expand All @@ -725,12 +729,21 @@ impl RepoStore {
) {
if let Some(ref tigris) = self.tigris {
if let Ok((owner_slug, _)) = self.local_path(owner_did, repo_name) {
if let Err(e) = tigris.delete(&owner_slug, repo_name).await {
warn!(
repo = %repo_name,
err = %e,
"failed to delete fork archive during create_repo compensation"
);
match tigris.delete(&owner_slug, repo_name).await {
Ok(()) => {}
Err(e) => {
warn!(
repo = %repo_name,
err = %e,
"failed to delete fork archive during create_repo compensation — scheduling retry"
);
let tigris = tigris.clone();
let slug = owner_slug.clone();
let name = repo_name.to_string();
tokio::spawn(async move {
retry_fork_archive_delete(&tigris, &slug, &name).await;
});
}
}
}
}
Expand All @@ -744,6 +757,38 @@ impl RepoStore {
}
}

async fn retry_fork_archive_delete(tigris: &TigrisClient, owner_slug: &str, repo_name: &str) {
const MAX_ATTEMPTS: u32 = 6;
for attempt in 0..MAX_ATTEMPTS {
match tigris.delete(owner_slug, repo_name).await {
Ok(()) => {
info!(
repo = %repo_name,
attempt,
"fork archive compensation delete succeeded on retry"
);
return;
}
Err(e) if attempt + 1 < MAX_ATTEMPTS => {
warn!(
repo = %repo_name,
attempt,
err = %e,
"fork archive compensation delete failed — retrying"
);
tokio::time::sleep(Duration::from_secs(1u64 << attempt.min(4))).await;
}
Err(e) => {
warn!(
repo = %repo_name,
err = %e,
"fork archive compensation delete failed after all retries — operator cleanup required"
);
}
}
}
}

/// The three-layer validated form of `store::repo_disk_path`, with NO Tigris fetch and
/// no `RepoStore` (#173 round 11, F3). Extracted from `RepoStore::local_path` so a
/// second caller that must not pull a cold repo gets the same barrier instead of the
Expand Down Expand Up @@ -780,6 +825,21 @@ pub(crate) fn validated_repo_disk_path(
Ok(local_path)
}

/// Revoke an in-flight publish swap. Any worker that has not yet claimed the
/// commit token will refuse before touching the live tree.
pub(crate) fn revoke_swap_authority(authority: &AtomicBool) {
authority.store(false, Ordering::Release);
}

/// Claim exclusive rights to perform the destructive publish swap. Revocation and
/// commit are mutually exclusive: only one caller can win the `true -> false`
/// transition, and that caller alone may remove/rename the live directory.
pub(crate) fn try_claim_swap_commit(authority: &AtomicBool) -> bool {
authority
.compare_exchange(true, false, Ordering::AcqRel, Ordering::Acquire)
.is_ok()
}

/// Swap a finished extraction into a validated live repo path. The caller must pass
/// the path returned from [`validated_repo_disk_path`]; this is the CodeQL barrier
/// for `rust/path-injection` on the remove/rename sink.
Expand All @@ -791,7 +851,7 @@ pub(crate) fn swap_extracted_into_validated_repo(
let lock = super::tigris::publish_lock(validated_path);
let _publish = lock.lock().expect("publish lock poisoned");
if let Some(authority) = swap_authority {
if !authority.load(Ordering::Acquire) {
if !try_claim_swap_commit(authority) {
let _ = std::fs::remove_dir_all(tmp_dir);
anyhow::bail!("publish swap revoked after lock ownership ended");
}
Expand All @@ -803,6 +863,29 @@ pub(crate) fn swap_extracted_into_validated_repo(
Ok(())
}

/// Remove a refused write from the unlocked read cache so `acquire` cannot serve
/// a tree that never landed in object storage.
fn invalidate_local_write_cache(local_path: &Path, repo_name: &str, reason: &str) {
if !local_path.exists() {
return;
}
if let Err(e) = std::fs::remove_dir_all(local_path) {
warn!(
repo = %repo_name,
path = %local_path.display(),
err = %e,
reason,
"failed to invalidate local write cache after a refused publish"
);
} else {
debug!(
repo = %repo_name,
reason,
"invalidated local write cache after a refused publish"
);
}
}

/// Strict allowlist validator for `owner_did` and `repo_name`.
///
/// Rejects any character that isn't explicitly safe, plus length and
Expand Down Expand Up @@ -1087,6 +1170,10 @@ impl RepoSnapshot {
pub fn path(&self) -> &Path {
&self.path
}

pub(crate) fn from_owned_path(path: PathBuf) -> Self {
Self { path, owned: true }
}
}

impl Drop for RepoSnapshot {
Expand Down Expand Up @@ -1293,6 +1380,19 @@ impl RepoWriteGuard {
warn!(repo = %self.repo_name, "write failed — skipping tigris upload to avoid propagating an inconsistent repo");
}

if success {
match outcome {
ReleaseOutcome::Fenced | ReleaseOutcome::UploadFailed => {
invalidate_local_write_cache(
&self.local_path,
&self.repo_name,
"definite publish refusal",
);
}
ReleaseOutcome::Released | ReleaseOutcome::UploadUnknowable => {}
}
}

// Release the advisory lock on the SAME session that took it. Unlocking
// through the pool would land on an arbitrary backend, where the call is a
// silent no-op.
Expand Down Expand Up @@ -1349,7 +1449,7 @@ impl RepoWriteGuard {
impl Drop for RepoWriteGuard {
fn drop(&mut self) {
if let Some(authority) = self.refresh_swap_authority.take() {
authority.store(false, Ordering::Release);
revoke_swap_authority(&authority);
}

let Some(mut conn) = self.conn.take() else {
Expand Down Expand Up @@ -1636,6 +1736,15 @@ mod tests {
assert!(ReleaseOutcome::Fenced.into_result().is_err());
}

#[test]
fn swap_commit_token_is_exclusive() {
let authority = Arc::new(AtomicBool::new(true));
assert!(try_claim_swap_commit(&authority));
assert!(!try_claim_swap_commit(&authority));
revoke_swap_authority(&authority);
assert!(!try_claim_swap_commit(&authority));
}

#[test]
fn revoked_publish_swap_cannot_replace_the_live_tree() {
let root = tempfile::TempDir::new().unwrap();
Expand Down Expand Up @@ -5065,12 +5174,17 @@ mod tests {
// ... and the generation the retry HEADs for moves on before its PUT
// can use it, so the second attempt loses too.
mock.roll_generation_after_next_heads(1);
let local_path = guard.local_path.clone();
let outcome = guard.release(true).await;

assert!(
matches!(outcome, ReleaseOutcome::Fenced),
"a publish refused twice must be reported to the caller, got {outcome:?}"
);
assert!(
!local_path.exists(),
"a fenced publish must invalidate the local read cache"
);
let attempts = mock.put_attempts();
assert_eq!(
attempts.len(),
Expand Down
Loading