Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
75 commits
Select commit Hold shift + click to select a range
34df1fd
feat(node): add per-IP write-surface rate brake and apply to write_ro…
beardthelion Jul 13, 2026
74e05be
feat(node): extend the per-IP write brake to the remaining write sinks
beardthelion Jul 13, 2026
6fded6e
test(node): adversarial TrustedProxy verification through the write b…
beardthelion Jul 13, 2026
e6324d2
feat(node): purge-spam admin subcommand for the empty-burst cleanup
beardthelion Jul 13, 2026
285d7c7
fix(review): make purge-spam empty-check reject git-discovery reads
beardthelion Jul 13, 2026
090019d
fix(review): normalization-consistent purge, brake helper, CLI + cove…
beardthelion Jul 13, 2026
dfd4f6c
test(review): close the reasoned-not-run gaps by execution
beardthelion Jul 13, 2026
0135419
fix(node): reject path-traversal repo names in purge-spam before remo…
beardthelion Jul 15, 2026
a0fcbb0
fix(node): delete child rows transactionally in delete_repo_by_id
beardthelion Jul 15, 2026
fde9cfe
fix(node): reap write_rate_limiter in the periodic cleanup loop
beardthelion Jul 15, 2026
15522d5
fix(node): hold the per-repo advisory lock across purge recheck+delete
beardthelion Jul 15, 2026
1fcca0d
fix(node): count purge-spam disk-removal failures separately from del…
beardthelion Jul 15, 2026
d9eebd2
fix(node): warn on unparseable rate-limit env vars instead of silentl…
beardthelion Jul 15, 2026
6325402
docs(node): document GITLAWB_IPFS_API/TIGRIS_BUCKET/METRICS_ADDR/SHUT…
beardthelion Jul 15, 2026
bfbe502
test(node): exercise the dry-run guard with a real on-disk candidate …
beardthelion Jul 15, 2026
cdb102e
style(node): cargo fmt for the #196 fix set
beardthelion Jul 15, 2026
4df79f2
fix(node): pin the writer's advisory-lock connection in RepoWriteGuard
beardthelion Jul 15, 2026
68c1f5c
refactor(node): introduce ObjectStore trait seam over TigrisClient
beardthelion Jul 15, 2026
3c1ceb8
fix(node): make purge-spam Tigris-authoritative and archive-deleting
beardthelion Jul 15, 2026
cf669bb
fix(review): don't hold/leak the pool connection in acquire_write
beardthelion Jul 15, 2026
dde5ea9
fix(node): make advisory-lock guards drop-safe and reorder acquire_write
beardthelion Jul 16, 2026
b94d440
fix(node): complete a fully-received push after client disconnect
beardthelion Jul 16, 2026
e4c4161
fix(node): serialize archive uploads under the per-repo advisory lock
beardthelion Jul 16, 2026
6ba698c
fix(node): let purge-spam reach repos that exist only as archives
beardthelion Jul 16, 2026
9f7757c
refactor(node): dedup limiter setup + write-brake test driver; fix .e…
beardthelion Jul 16, 2026
2a78524
docs(node): drop the .env.example shutdown-grace entry #196 added (#196)
beardthelion Jul 19, 2026
c4b337b
fix(node): give advisory-lock guards a dedicated pool and bound the r…
beardthelion Jul 19, 2026
4934646
fix(node): advertise a window-derived Retry-After on rate-limit 429s …
beardthelion Jul 19, 2026
0c279c9
fix(node): skip slug-scoped purge cascade when a mirror row shares th…
beardthelion Jul 19, 2026
86a8228
fix(node): fail closed classifying the purge target directory (#196)
beardthelion Jul 20, 2026
bf2a54e
fix(node): run the push completion tail in the disconnect-surviving t…
beardthelion Jul 20, 2026
c24b541
fix(node): tombstone bounties when their repo is purged (#196)
beardthelion Jul 20, 2026
3baa9ed
fix(node): serialize create_repo against the purge advisory lock (#196)
beardthelion Jul 20, 2026
9916bca
test(node): prove purge deletes at MAX_CONNECTIONS=1 with the split p…
beardthelion Jul 20, 2026
8f3d643
fix(node): fail the push when the durable upload times out, don't 200…
beardthelion Jul 20, 2026
d1e596e
fix(node): tombstone bounties under both owner forms on purge (#196)
beardthelion Jul 20, 2026
ce5dcc3
fix(node): fail closed on a symlink at the purge target (#196)
beardthelion Jul 20, 2026
7dc7be2
fix(node): retry-after on the push-advert 429, and create_repo locks …
beardthelion Jul 20, 2026
d2ba14e
fix(node): correct the create-pool and bounty-tombstone remediations …
beardthelion Jul 20, 2026
5a46ef6
fix(node): close the durable-upload data-loss class on every write pa…
beardthelion Jul 20, 2026
2fa9fa3
chore: merge main (iCaptcha PoW + gl retry tests) into feat/write-sin…
beardthelion Jul 21, 2026
16517f8
refactor(node): route the per-DID 429 through the shared too_many_req…
beardthelion Jul 21, 2026
ba572b3
fix(node): init's background upload waits out the creator's advisory …
beardthelion Jul 21, 2026
859240b
fix(node): roll back the local issue ref before unlock when the durab…
beardthelion Jul 21, 2026
c07435d
fix(node): fork publishes only after a durable upload, serialized on …
beardthelion Jul 21, 2026
2ad1c79
fix(node): read-path downloads publish under the purge lock, without …
beardthelion Jul 21, 2026
b2ca5a7
fix(node): bound every under-lock object-store call and dedup the upl…
beardthelion Jul 21, 2026
fa4322c
fix(node): harden the read-path download against cancellation, stale …
beardthelion Jul 21, 2026
c3d6e73
fix(node): keep the fork's unbounded work out of the target-lock span…
beardthelion Jul 21, 2026
03ef9b5
refactor(node): move read-path download coordination into a repo_stor…
beardthelion Jul 21, 2026
4408d27
fix(node): bound acquire_write's download and free the download-map e…
beardthelion Jul 21, 2026
a12f21a
fix(node): roll back the fork mirror and archive on late clone/insert…
beardthelion Jul 21, 2026
556aa31
fix(node): serialize repo purge cascade with mirror ingest via adviso…
beardthelion Jul 22, 2026
1d8c281
fix(node): roll back local ref on failed durable upload (close/merge/…
beardthelion Jul 22, 2026
1d0d3d2
fix(node): tie cancelled cold-download cleanup to blocking extraction
beardthelion Jul 22, 2026
03cd81e
chore(node): fmt + clippy cleanup for the #196 fixes
beardthelion Jul 22, 2026
9152178
fix(node): never let a failed ref snapshot become a delete-all rollba…
beardthelion Jul 22, 2026
296704f
fix(node): slug-lock every peer-ingest writer and drive the real inge…
beardthelion Jul 22, 2026
1e79ae5
fix(node): own cold-download cleanup in a spawned task so handler can…
beardthelion Jul 22, 2026
ce25bba
refactor(node): delegate issue ref helpers to the store ref primitives
beardthelion Jul 22, 2026
4329b2a
Merge origin/main into feat/write-sink-brake-coverage (reintegrate cu…
beardthelion Jul 22, 2026
d755180
fix(node): slug-lock arweave anchor writes; fail closed when the pre-…
beardthelion Jul 22, 2026
e6f4b2f
fix(node): close review residuals: coalesce cold downloads to one in-…
beardthelion Jul 22, 2026
1459cf2
Merge remote-tracking branch 'origin/main' into feat/write-sink-brake…
beardthelion Nov 11, 2026
da876e8
fix(node): re-apply create/fork purge serialization and restore brake…
beardthelion Nov 11, 2026
edfa6bb
fix(node): close review gaps in purge, locks, and fork cleanup
beardthelion Nov 11, 2026
96ed2b2
fix(node): subscriptions-only ws schema and unsettled-work purge guard
beardthelion Nov 11, 2026
082a37f
Merge remote-tracking branch 'origin/main' into feat/write-sink-brake…
beardthelion Nov 11, 2026
e9e86a1
fix(node): wire close_issue rollback, close purge symlink gap, correc…
beardthelion Nov 11, 2026
1187dca
fix(node): close purge/upload lifecycle gaps from review
beardthelion Nov 11, 2026
261f7ab
fix(node): merge rollback, honest create rollback, purge row recheck
beardthelion Nov 12, 2026
662b9a3
fix(node): probe purge slug liveness, gate issue write brake behind t…
beardthelion Nov 12, 2026
43d4f59
fix(node): close-issue rollback uses resolved ref, drop router brake …
beardthelion Nov 12, 2026
4b483a3
fix(node): close_issue spends neither bucket when either cap refuses,…
beardthelion Nov 12, 2026
11cadb9
fix(node): refund the write slot when the close cap refuses, send Ret…
beardthelion Nov 12, 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): complete a fully-received push after client disconnect
git_receive_pack now runs the acquire -> receive-pack -> release core in a
spawned task the handler awaits but whose cancellation it does not propagate.
The pack body is fully buffered before the handler runs, so the task is
self-contained: a client that disconnects mid-apply drops the handler future
without cancelling the task, and the push still applies, uploads, and releases
its lock in order. Drop-safety (the guard's close-on-drop) remains the backstop;
this closes the dominant window where a disconnect both bricked the lock and
abandoned a received push. The post-push bookkeeping tail stays in the
cancellable handler (a disconnect still forgoes it, as today).

Settled OQ1 by execution: a guard abandoned inside a detached task when the
tokio runtime tears down does not panic in Drop (5/5 runs), so detached-task
shutdown tracking stays deferred. Kept the check as a regression guard.

Disconnect regression drives a real push with a sleeping pre-receive hook and
drops the handler mid-hook: RED on the inline handler (the git group is killed,
ref absent), GREEN once detached.
  • Loading branch information
beardthelion committed Jul 16, 2026
commit b94d440e9ec134fea05740b98388da53ba8878f6
211 changes: 196 additions & 15 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -924,24 +924,46 @@ pub async fn git_receive_pack(
}

tracing::debug!(repo = %name, "acquiring write lock");
let guard = state
.repo_store
.acquire_write(&record.owner_did, &record.name)
.await
.map_err(|e| {
tracing::error!(repo = %name, err = %e, "acquire_write failed");
AppError::Git(e.to_string())
})?;
let disk_path = guard.path().to_path_buf();
tracing::debug!(repo = %name, path = %disk_path.display(), "running git receive-pack");
let body_len = body.len();
let git_timeout = std::time::Duration::from_secs(state.config.git_service_timeout_secs);
let receive_result = smart_http::receive_pack(&disk_path, body, git_timeout).await;

// Always release the advisory lock — even on error — to prevent stale locks
// from blocking subsequent pushes. Only upload to Tigris when the push
// succeeded; uploading a half-applied repo would propagate corruption.
guard.release(receive_result.is_ok()).await;
// Detach the acquire → receive-pack → release core from THIS handler future.
// The pack `body` is already fully buffered, so the spawned task is
// self-contained: a client disconnect drops the handler future but does NOT
// cancel the task, so a fully-received push still completes server-side —
// applies the pack, uploads, and releases the lock in order. What a
// disconnect forgoes is the cancellable post-push bookkeeping below, not the
// push itself. (KTD-3, R3.)
let repo_store = state.repo_store.clone();
let owner_did = record.owner_did.clone();
let repo_name = record.name.clone();
let receive_result = tokio::spawn(async move {
let guard = repo_store
.acquire_write(&owner_did, &repo_name)
.await
.map_err(|e| {
tracing::error!(repo = %repo_name, err = %e, "acquire_write failed");
AppError::Git(e.to_string())
})?;
let disk_path = guard.path().to_path_buf();
tracing::debug!(repo = %repo_name, path = %disk_path.display(), "running git receive-pack");
let result = smart_http::receive_pack(&disk_path, body, git_timeout).await;
// Always release the advisory lock — even on error — to prevent stale
// locks from blocking subsequent pushes. Only upload to Tigris when the
// push succeeded; uploading a half-applied repo would propagate corruption.
guard.release(result.is_ok()).await;
Ok::<_, AppError>(result)
})
.await
.map_err(|e| {
tracing::error!(repo = %name, err = %e, "receive-pack task panicked");
AppError::Internal(anyhow::anyhow!("receive-pack task failed: {e}"))
})??;

// Recompute the on-disk path for the post-push tail below — the guard that
// exposed it now lives inside the detached task. Identical to the path
// acquire_write resolved (repos_dir/owner_slug/name.git).
let disk_path = store::repo_disk_path(&state.config.repos_dir, &record.owner_did, &record.name);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

let result = receive_result.map_err(|e| {
let app = git_service_app_error(&e);
Expand Down Expand Up @@ -2579,6 +2601,165 @@ mod tests {
);
}

// U2/R3/AE1: a fully-received push must complete server-side even when the
// client disconnects during the apply. The pack is buffered before the
// handler runs, so the acquire→receive→release core is detached from the
// handler future; dropping that future (the disconnect) must NOT cancel the
// push. A sleeping pre-receive hook creates a deterministic mid-apply window;
// dropping the handler during it kills the git group on the inline (pre-fix)
// code but not on the detached code, so the hook completes and the ref lands
// only after the fix. RED pre-fix (marker + ref absent), GREEN after.
#[sqlx::test]
async fn fully_received_push_completes_after_client_disconnect(pool: sqlx::PgPool) {
use axum::extract::{Path as AxPath, State};
use axum::Extension;
use std::os::unix::fs::PermissionsExt;
use std::process::{Command, Stdio};
use std::time::Duration;

let mut state = crate::test_support::test_state(pool.clone()).await;
let repos_dir = tempfile::TempDir::new().unwrap();
state.repo_store = crate::git::repo_store::RepoStore::for_testing(
repos_dir.path().to_path_buf(),
pool.clone(),
);

let owner = "z6u2pushowner";
let name = "u2push";
let owner_slug = owner.replace([':', '/'], "_");
let bare = repos_dir
.path()
.join(&owner_slug)
.join(format!("{name}.git"));

state
.db
.upsert_mirror_repo(owner, name, &bare.to_string_lossy(), None, false)
.await
.unwrap();

// Helper: run git, asserting success.
fn git(args: &[&str], dir: &std::path::Path) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?} failed: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}

// Build a commit in a scratch working repo.
let work = tempfile::TempDir::new().unwrap();
git(&["init", "-q", "-b", "main", "."], work.path());
git(&["config", "user.email", "t@t"], work.path());
git(&["config", "user.name", "t"], work.path());
std::fs::write(work.path().join("f.txt"), "hi").unwrap();
git(&["add", "f.txt"], work.path());
git(&["commit", "-q", "-m", "c"], work.path());
let oid = git(&["rev-parse", "HEAD"], work.path());

// Server bare repo: has the object (from the clone) but no refs/heads/main,
// so the push is a create satisfiable with an empty pack.
std::fs::create_dir_all(bare.parent().unwrap()).unwrap();
let out = Command::new("git")
.args([
"clone",
"--bare",
"-q",
&work.path().to_string_lossy(),
&bare.to_string_lossy(),
])
.output()
.unwrap();
assert!(
out.status.success(),
"clone --bare failed: {}",
String::from_utf8_lossy(&out.stderr)
);
git(
&[
"-C",
&bare.to_string_lossy(),
"update-ref",
"-d",
"refs/heads/main",
],
work.path(),
);

// Sleeping pre-receive hook — the mid-apply window; writes a marker at the
// end so we can see the git child ran to completion.
let marker = repos_dir.path().join("hook_ran.marker");
let hook = bare.join("hooks").join("pre-receive");
std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
std::fs::write(
&hook,
format!(
"#!/bin/sh\ncat >/dev/null\nsleep 2\necho done > '{}'\nexit 0\n",
marker.display()
),
)
.unwrap();
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();

// Receive-pack POST body: create refs/heads/main -> oid, plus an empty pack.
let zero = "0".repeat(40);
let cmd = format!("{zero} {oid} refs/heads/main\0report-status\n");
let mut body = Vec::new();
let len = cmd.len() + 4;
body.extend_from_slice(format!("{len:04x}").as_bytes());
body.extend_from_slice(cmd.as_bytes());
body.extend_from_slice(b"0000");
let pack = Command::new("git")
.args([
"-C",
&bare.to_string_lossy(),
"pack-objects",
"--stdout",
"-q",
])
.stdin(Stdio::null())
.output()
.unwrap();
assert!(
pack.status.success(),
"pack-objects failed: {}",
String::from_utf8_lossy(&pack.stderr)
);
body.extend_from_slice(&pack.stdout);
let body = Bytes::from(body);

// Drive the handler, then DROP it mid-hook (the "client disconnect").
let handler = super::git_receive_pack(
State(state.clone()),
AxPath((owner.to_string(), format!("{name}.git"))),
Extension(crate::auth::AuthenticatedDid(owner.to_string())),
body,
);
let _ = tokio::time::timeout(Duration::from_millis(800), handler).await;

// Wait past the hook's sleep so a surviving (detached) push can finish.
tokio::time::sleep(Duration::from_millis(3000)).await;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

let ref_present = bare.join("refs/heads/main").exists()
|| std::fs::read_to_string(bare.join("packed-refs"))
.unwrap_or_default()
.contains("refs/heads/main");
assert!(
marker.exists(),
"pre-receive hook must run to completion despite the client disconnect (detached push)"
);
assert!(
ref_present,
"refs/heads/main must be created after a fully-received push despite client disconnect"
);
}

/// Repo creation must be throttled by the per-IP creation limiter BEFORE
/// signature verification — otherwise a DID farm (one throwaway did:key per
/// repo, each carrying a valid but machine-solved iCaptcha proof) walks past
Expand Down
46 changes: 46 additions & 0 deletions crates/gitlawb-node/src/git/repo_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1044,4 +1044,50 @@ mod tests {
guard.release(true).await;
}
}

// OQ1: settle whether a guard abandoned inside a detached task when the
// tokio runtime tears down panics in Drop. `PoolConnection::drop` spawns a
// task (both the close_on_drop path and the normal return path), and
// `rt::spawn` panics via `missing_rt` if no runtime handle is current. U2
// makes receive-pack a detached task that graceful shutdown does not drain,
// so at process exit such a task can be dropped mid-flight holding a guard.
// This drops a real runtime with a parked guard-holding task and asserts the
// process survives (a panic-in-Drop during unwind would abort the binary).
#[test]
fn guard_drop_during_runtime_shutdown_does_not_panic() {
let url = match std::env::var("DATABASE_URL") {
Ok(u) => u,
Err(_) => return, // no DB configured — skip (mirrors sqlx::test gating)
};
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()
.unwrap();
let ready = std::sync::Arc::new(tokio::sync::Notify::new());
let ready2 = ready.clone();
rt.block_on(async move {
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(&url)
.await
.unwrap();
let tmp = tempfile::TempDir::new().unwrap();
let store = RepoStore::new(tmp.path().to_path_buf(), None, pool);
tokio::spawn(async move {
let _guard = store
.acquire_write("did:key:z6MkOQ1ShutdownAAAAAAAAAAAAAAAAAAAAAAAAA", "oq1")
.await
.unwrap();
ready2.notify_one();
// Park forever holding the guard.
std::future::pending::<()>().await;
});
ready.notified().await;
});
// Drop the runtime while the detached task is parked holding the guard:
// the task is cancelled, dropping the guard during runtime teardown. Its
// Drop must not panic. Reaching the end of the test proves it didn't.
drop(rt);
}
}