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): retry-after on the push-advert 429, and create_repo locks …
…on the app pool (#196)

Two review follow-ups:

- The unauthenticated info/refs?service=git-receive-pack limiter still
  returned a bare 429 with no Retry-After while the other limiters
  advertise the window-derived delay; it now uses check_retry and the
  shared too_many_requests helper. Removed the orphaned
  AppError::TooManyRequests variant and gated the now-test-only check().

- create_repo's transient serialization lock drew from the write
  lock_pool, so a burst that pins lock_pool starved repo creation.
  Postgres advisory locks are database-global, so create now takes its
  lock from the app pool (via lock_repo_blocking_on) and still
  serializes against a purge holding the same key from lock_pool.
  • Loading branch information
beardthelion committed Jul 20, 2026
commit 7dc7be2ecdf1f945fc723789abdb40cd4b13d0c9
165 changes: 160 additions & 5 deletions crates/gitlawb-node/src/api/repos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,16 @@ pub async fn create_repo(
// explicitly on the success path, and its guard's Drop frees the lock on every
// error path below. Bounded-wait (no object-store I/O), so the uncontended hot
// path returns on the first attempt. (KTD6, R6.)
//
// Take this transient lock on the APP pool, not the write lock_pool. lock_pool
// is sized for long-held receive-pack write guards; a push burst that pins it
// would otherwise starve create's acquire (-> 500). The advisory lock is
// DB-global, so locking from the app pool still serializes against a same-key
// purge holding the lock from lock_pool. (INV-15 sibling: don't couple a cheap
// path to the expensive path's capacity.)
let repo_lock = state
.repo_store
.lock_repo_blocking(&owner_did, &req.name)
.lock_repo_blocking_on(state.db.pool(), &owner_did, &req.name)
.await
.map_err(|e| AppError::Git(e.to_string()))?
.ok_or_else(|| {
Expand Down Expand Up @@ -579,11 +586,12 @@ pub async fn git_info_refs(
// trusted-proxy policy as the POST middleware (shared buckets).
if service == "git-receive-pack" {
if let Some(key) = crate::rate_limit::client_key(&headers, peer, state.push_limiter_trust) {
if !state.push_rate_limiter.check(&key).await {
// Use check_retry (like U5's other 429 sites) so the rejection carries a
// window-derived Retry-After, built via the shared 429 response helper
// that the per-IP middleware also uses.
if let Some(retry_after) = state.push_rate_limiter.check_retry(&key).await {
tracing::warn!(repo = %name, key = %key, "receive-pack advertisement rate limited");
return Err(AppError::TooManyRequests(
"push rate limit exceeded — try again later".into(),
));
return Ok(crate::rate_limit::too_many_requests(retry_after));
}
}
}
Expand Down Expand Up @@ -2678,6 +2686,60 @@ mod tests {
);
}

/// The receive-pack advertisement 429 must carry a window-derived Retry-After,
/// consistent with the other push 429 sites (U5). Before the fix this site
/// returned a bare 429 with no Retry-After header at all — a client had nothing
/// to back off on. A freshly-filled bucket's oldest
/// entry is ~now, so the advertised delay must be close to the whole window
/// (100s), never missing and never the old constant 60.
#[sqlx::test]
async fn receive_pack_advertisement_429_carries_window_derived_retry_after(pool: sqlx::PgPool) {
use axum::body::Body;
use axum::extract::ConnectInfo;
use axum::http::{Method, Request, StatusCode};
use std::net::SocketAddr;
use std::time::Duration;
use tower::ServiceExt;

let mut state = crate::test_support::test_state(pool).await;
// Budget 1, 100s window, keyed on the socket peer (no trusted proxy).
state.push_rate_limiter = crate::rate_limit::RateLimiter::new(1, Duration::from_secs(100));
state.push_limiter_trust = crate::rate_limit::TrustedProxy::None;
state
.db
.upsert_mirror_repo("z6advretry", "adv", "/tmp/advretry", None, false)
.await
.unwrap();

let peer: SocketAddr = "203.0.113.56:6000".parse().unwrap();
// Fill the single-request budget so the handler's own check rejects.
assert!(state.push_rate_limiter.check(&peer.ip().to_string()).await);

let router = crate::server::build_router(state);
let mut req = Request::builder()
.method(Method::GET)
.uri("/z6advretry/adv/info/refs?service=git-receive-pack")
.body(Body::empty())
.unwrap();
req.extensions_mut().insert(ConnectInfo(peer));

let resp = router.oneshot(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
let retry: u64 = resp
.headers()
.get("retry-after")
.expect("advertisement 429 must carry a retry-after header")
.to_str()
.unwrap()
.parse()
.expect("retry-after must be an integer number of seconds");
assert!(
(95..=100).contains(&retry),
"freshly-filled bucket must advertise ~window (95..=100s), got {retry} \
(missing header or constant-60 bug otherwise)"
);
}

// 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
Expand Down Expand Up @@ -3837,4 +3899,97 @@ mod tests {
"on-disk dir present after an uncontended create"
);
}

// create_repo's transient serialization lock must NOT draw from the write
// lock_pool. lock_pool is sized for LONG-HELD receive-pack write guards; a
// concurrent-push burst that pins every lock_pool connection would otherwise
// starve legitimate repo creation (create's acquire times out -> 500). The fix
// takes create's transient lock on the APP pool instead, which the write burst
// never touches. RED on base (create locks on lock_pool): with the lock_pool
// saturated by held write guards, create errors. GREEN after (create locks on
// the app pool): create still succeeds.
#[sqlx::test]
async fn create_repo_survives_a_saturated_lock_pool(
pool_opts: sqlx::postgres::PgPoolOptions,
connect_opts: sqlx::postgres::PgConnectOptions,
) {
use axum::extract::State;
use axum::Extension;
use std::time::Duration;

// App pool: serves state.db AND (after the fix) create's transient lock.
let app_pool = pool_opts
.max_connections(5)
.connect_with(connect_opts.clone())
.await
.unwrap();
let mut state = crate::test_support::test_state(app_pool.clone()).await;

// A SEPARATE, small write lock pool that fails fast on exhaustion, so a
// create wired to it errors quickly rather than blocking the whole test.
const N: u32 = 2;
let lock_pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(N)
.acquire_timeout(Duration::from_secs(2))
.min_connections(0)
.idle_timeout(None)
.max_lifetime(None)
.test_before_acquire(false)
.connect_with(connect_opts.clone())
.await
.unwrap();
let repos_dir = tempfile::TempDir::new().unwrap();
state.repo_store = crate::git::repo_store::RepoStore::for_testing(
repos_dir.path().to_path_buf(),
lock_pool.clone(),
);

// Saturate the lock pool with N held write guards on distinct repos — the
// 32-writer burst, scaled down. Each guard pins one lock_pool connection.
let mut guards = Vec::new();
for i in 0..N {
let owner = format!("did:key:z6MkSaturateLock{i}AAAAAAAAAAAAAAAAAAAAAA");
guards.push(
state
.repo_store
.acquire_write(&owner, "held")
.await
.unwrap(),
);
}
// The lock pool is exhausted, so the create assertion below is load-bearing
// (not vacuously green because the pool happened to be idle).
assert!(
lock_pool.acquire().await.is_err(),
"the lock pool must be exhausted by N held write guards"
);

// create for an UNCONTENDED key. Its advisory lock is free (the write
// guards hold different keys), so the only thing that can stop it is the
// saturated lock_pool — which it must not touch.
let owner = "did:key:z6MkCreateAppPoolCCCCCCCCCCCCCCCCCCCCCCCC";
let name = "created";
let created = super::create_repo(
State(state.clone()),
Extension(crate::auth::AuthenticatedDid(owner.to_string())),
axum::http::HeaderMap::new(),
Json(CreateRepoRequest {
name: name.to_string(),
description: None,
is_public: true,
default_branch: "main".to_string(),
}),
)
.await
.expect("create must survive a saturated lock pool by locking on the app pool");
assert_eq!(created.0, StatusCode::CREATED);
assert!(
state.db.get_repo(owner, name).await.unwrap().is_some(),
"row present after a create under a saturated lock pool"
);

for g in guards {
g.release(true).await;
}
}
}
13 changes: 7 additions & 6 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -247,12 +247,13 @@ pub struct Db {
}

impl Db {
/// Access the underlying Postgres connection pool. Test-only: production DB
/// access goes through `Db`'s methods, and the advisory-lock subsystem now
/// uses its own pool (`connect_lock_pool`), so nothing outside tests reaches
/// for the raw app pool.
#[cfg(test)]
pub fn pool(&self) -> &PgPool {
/// Access the underlying Postgres connection pool. Most DB access goes through
/// `Db`'s methods; the write advisory-lock subsystem uses its own pool
/// (`connect_lock_pool`). `create_repo` is the one production caller: its
/// transient serialization lock is taken on THIS app pool rather than the
/// write lock pool, so a write burst that pins the lock pool cannot starve
/// repo creation.
pub(crate) fn pool(&self) -> &PgPool {
&self.pool
}

Expand Down
6 changes: 0 additions & 6 deletions crates/gitlawb-node/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,6 @@ pub enum AppError {
#[error("invalid request: {0}")]
BadRequest(String),

#[error("too many requests: {0}")]
TooManyRequests(String),

#[error("incomplete: {0}")]
Incomplete(String),

Expand Down Expand Up @@ -132,9 +129,6 @@ impl IntoResponse for AppError {
// IcaptchaProofRequired is handled above (it carries extra headers/fields).
AppError::IcaptchaProofRequired { .. } => unreachable!("handled before this match"),
AppError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "bad_request", msg.clone()),
AppError::TooManyRequests(msg) => {
(StatusCode::TOO_MANY_REQUESTS, "rate_limited", msg.clone())
}
AppError::Incomplete(msg) => {
(StatusCode::UNPROCESSABLE_ENTITY, "incomplete", msg.clone())
}
Expand Down
40 changes: 34 additions & 6 deletions crates/gitlawb-node/src/git/repo_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,14 +292,25 @@ impl RepoStore {
&self,
owner_did: &str,
repo_name: &str,
) -> Result<Option<RepoLockGuard>> {
self.try_lock_repo_on(&self.lock_pool, owner_did, repo_name)
.await
}

/// [`try_lock_repo`](Self::try_lock_repo) against a caller-chosen pool. The
/// Postgres advisory lock is DATABASE-global, so the lock still mutually
/// excludes holders of the same key from any other pool — only the connection
/// the guard pins comes from `pool`. `create_repo` uses this with the app pool
/// so its transient lock never draws from the write `lock_pool`.
async fn try_lock_repo_on(
&self,
pool: &PgPool,
owner_did: &str,
repo_name: &str,
) -> Result<Option<RepoLockGuard>> {
let (owner_slug, _local) = self.local_path(owner_did, repo_name)?;
let lock_key = advisory_lock_key(&owner_slug, repo_name);
let mut conn = self
.lock_pool
.acquire()
.await
.context("acquiring lock connection")?;
let mut conn = pool.acquire().await.context("acquiring lock connection")?;
let row: (bool,) = sqlx::query_as("SELECT pg_try_advisory_lock($1)")
.bind(lock_key)
.fetch_one(&mut *conn)
Expand Down Expand Up @@ -431,9 +442,26 @@ impl RepoStore {
&self,
owner_did: &str,
repo_name: &str,
) -> Result<Option<RepoLockGuard>> {
self.lock_repo_blocking_on(&self.lock_pool, owner_did, repo_name)
.await
}

/// [`lock_repo_blocking`](Self::lock_repo_blocking) against a caller-chosen
/// pool. `create_repo` passes the app pool so its transient serialization lock
/// (check-exists -> init -> insert) does not draw a connection from the write
/// `lock_pool` — a receive-pack burst that pins every lock-pool connection
/// must not starve repo creation. The advisory lock is DB-global, so this
/// still serializes create against a same-key purge that holds the lock from
/// the lock pool.
pub async fn lock_repo_blocking_on(
&self,
pool: &PgPool,
owner_did: &str,
repo_name: &str,
) -> Result<Option<RepoLockGuard>> {
for attempt in 0..30 {
if let Some(g) = self.try_lock_repo(owner_did, repo_name).await? {
if let Some(g) = self.try_lock_repo_on(pool, owner_did, repo_name).await? {
return Ok(Some(g));
}
if attempt < 29 {
Expand Down
4 changes: 3 additions & 1 deletion crates/gitlawb-node/src/rate_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,9 @@ impl RateLimiter {

/// Returns `true` if the request is allowed. Thin wrapper over
/// [`check_retry`](Self::check_retry) for callers that only need the
/// allow/deny decision, not the rejection's Retry-After delay.
/// allow/deny decision, not the rejection's Retry-After delay. Test-only now:
/// production 429 sites use `check_retry` so they can advertise Retry-After.
#[cfg(test)]
pub(crate) async fn check(&self, key: &str) -> bool {
self.check_retry(key).await.is_none()
}
Expand Down