Skip to content
Merged
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): serialize repo purge cascade with mirror ingest via adviso…
…ry lock

delete_repo_by_id ran a point-in-time sibling check then cascaded slug-scoped
deletes; upsert_mirror_repo (peer sync) did not serialize against that window,
so a colliding mirror could land mid-purge and get half-wiped. Both now take a
transaction-scoped pg_advisory_xact_lock keyed on the normalized slug. (F1, #196)
  • Loading branch information
beardthelion committed Jul 22, 2026
commit 556aa31e2c39340da4a4fc9d5d674509cc0010c9
187 changes: 182 additions & 5 deletions crates/gitlawb-node/src/db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,23 @@ fn owner_key_case_sql(col: &str) -> String {
)
}

/// Take a transaction-scoped Postgres advisory lock keyed on the normalized repo
/// slug (`normalize_owner_key(owner)/name`). `delete_repo_by_id`'s purge cascade and
/// `upsert_mirror_repo`'s ingest both take this lock on the identical slug string, so
/// a peer-sync mirror insert cannot interleave between the purge's point-in-time
/// sibling check and its slug-scoped deletes (which would half-wipe a live mirror's
/// child rows / bounty). `hashtextextended($1, 0)` folds the slug to the `bigint` the
/// lock API needs; both call sites hash the identical string, so their keys agree.
/// XACT-scoped, so it auto-releases on commit/rollback with no unlock bookkeeping
/// (mirrors the session-scoped `pg_advisory_lock` migration guard, but self-releasing).
async fn lock_repo_slug(conn: &mut sqlx::PgConnection, slug: &str) -> Result<()> {
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))")
.bind(slug)
.execute(conn)
.await?;
Ok(())
}

#[cfg(test)]
mod normalize_owner_key_tests {
use super::normalize_owner_key;
Expand Down Expand Up @@ -1030,6 +1047,14 @@ impl Db {
) -> Result<()> {
let now = Utc::now().to_rfc3339();
let id = format!("{owner_short}/{name}");
// Slug the purge cascade keys on. Take the shared advisory lock on it inside a
// tx so a concurrent `delete_repo_by_id` purge of a colliding row cannot
// interleave its sibling-check-then-cascade around this insert and wipe the
// mirror we are ingesting. Normalize the owner the same way the cascade does so
// both call sites hash the identical slug string.
let slug = format!("{}/{}", normalize_owner_key(owner_short), name);
let mut tx = self.pool.begin().await?;
lock_repo_slug(&mut *tx, &slug).await?;
// `quarantined` is set only on first insert (the admission decision).
// A re-sync (ON CONFLICT) preserves the existing flag — admission runs
// once, and an operator's later release must not be silently reverted.
Expand All @@ -1050,8 +1075,9 @@ impl Db {
.bind(disk_path)
.bind(machine_id)
.bind(quarantined)
.execute(&self.pool)
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}

Expand Down Expand Up @@ -1342,6 +1368,13 @@ impl Db {
};
let slug = format!("{}/{}", normalize_owner_key(&owner_did), name);

// Serialize this purge against a concurrent `upsert_mirror_repo` ingest that
// resolves to the same slug: both take this xact-scoped advisory lock on the
// identical slug string BEFORE the sibling check below, so a peer-sync insert
// cannot land between that point-in-time check and the slug-scoped cascade
// deletes (which would half-wipe the live mirror). Auto-released on commit.
lock_repo_slug(&mut *tx, &slug).await?;

// Grandchildren first: PR reviews/comments key on pr_id, so delete them
// before the parent PRs vanish.
for table in ["pr_reviews", "pr_comments"] {
Expand Down Expand Up @@ -1381,10 +1414,12 @@ impl Db {
// a surviving sibling's records. Gate the slug-scoped deletes on the absence
// of any OTHER repos row resolving to the same slug, using the same
// OWNER_KEY_CASE_SQL the slug was built from so the check is byte-identical to
// the cascade key. (Residual: this is a point-in-time check inside one READ
// COMMITTED tx, not full serialization against a concurrent colliding create;
// see the plan's KTD4. Purge is the sole caller, so the window is
// operator-scoped.)
// the cascade key. The xact advisory lock taken at the top of this tx (and
// matched in `upsert_mirror_repo` on the identical slug) serializes this
// sibling-check-then-cascade against a concurrent peer-sync insert for the same
// slug, so this is no longer a bare point-in-time read a mirror upsert can slip
// past (closing the old KTD4 residual: the concurrent inserter is peer sync,
// not an operator, so the window was never operator-scoped).
let sibling_exists: bool = sqlx::query_scalar(&format!(
"SELECT EXISTS(SELECT 1 FROM repos WHERE id <> $1 AND {key} || '/' || name = $2)",
Comment thread
beardthelion marked this conversation as resolved.
Resolved
key = OWNER_KEY_CASE_SQL
Expand Down Expand Up @@ -3951,6 +3986,148 @@ mod dedup_db_tests {
);
}

/// U1 (F1): the purge cascade must be serialized with mirror ingestion on the
/// shared slug. `delete_repo_by_id` runs a point-in-time sibling check and then,
/// only if no sibling was seen, wipes the slug-scoped child rows / tombstones the
/// bounty. A concurrent `upsert_mirror_repo` that inserts a colliding mirror row
/// AFTER that check but before/around the cascade would leave a half-wipe: the
/// mirror's `repos` row survives while its live child rows / bounty are gone.
///
/// Deterministic race: hold a session advisory lock on the same `hashtextextended`
/// slug key the cascade locks on, so the spawned purge BLOCKS at the top of its tx
/// (before the sibling check). While it is parked, land the mirror's `repos` row
/// (what ingestion writes), then release the lock. With the lock in place the purge
/// resumes, its sibling check now SEES the mirror row, and it skips the cascade —
/// both the mirror row and its child rows survive (GREEN). Remove the
/// `lock_repo_slug` call from `delete_repo_by_id` and the purge no longer blocks: it
/// runs its sibling check before the mirror row exists, cascades, and half-wipes the
/// child rows / bounty while the mirror row (inserted afterwards) survives (RED).
#[sqlx::test]
async fn purge_serializes_with_mirror_ingest_via_advisory_lock(pool: PgPool) {
let db = db(pool).await;
// Purge target: an empty canonical `did:key:` row.
let owner = "did:key:z6MkPurgeRaceMirrorFixtureForLock";
let target = rec(
"rid-purge-race-target",
owner,
"victim",
"empty canonical",
"2026-01-01T00:00:00Z",
"2026-01-01T00:00:00Z",
);
db.create_repo(&target).await.unwrap();

// The mirror's slug-scoped live state, keyed on the shared slug. The mirror's
// `repos` row is deliberately NOT present yet — ingestion lands it mid-race.
let slug = format!(
"{}/victim",
crate::db::normalize_owner_key(owner)
);
sqlx::query(
"INSERT INTO branch_cids (repo, ref_name, sha, cid, node_did, updated_at)
VALUES ($1, 'refs/heads/main', '1', 'cid', 'n', '2026-02-01T00:00:00Z')",
)
.bind(&slug)
.execute(db.pool())
.await
.unwrap();
db.create_bounty(&BountyRecord {
id: "bnt-purge-race".to_string(),
repo_owner: "z6MkPurgeRaceMirrorFixtureForLock".to_string(),
repo_name: "victim".to_string(),
issue_id: None,
title: "mirror bounty".to_string(),
amount: 5_000,
creator_did: "did:key:z6MkCreator".to_string(),
claimant_did: None,
claimant_wallet: None,
pr_id: None,
status: "open".to_string(),
created_at: "2026-02-01T00:00:00Z".to_string(),
claimed_at: None,
submitted_at: None,
completed_at: None,
deadline_secs: 604_800,
tx_hash: None,
})
.await
.unwrap();

// Hold a session-scoped advisory lock on the exact slug key the cascade takes.
// A session lock and the cascade's xact lock share Postgres' advisory lock
// space, so the purge's `pg_advisory_xact_lock` blocks on this until we unlock.
let mut lock_conn = db.pool().acquire().await.unwrap();
sqlx::query("SELECT pg_advisory_lock(hashtextextended($1, 0))")
.bind(&slug)
.execute(&mut *lock_conn)
.await
.unwrap();

// Spawn the purge; with the lock present it parks at the top of its tx.
let pool_for_task = db.pool().clone();
let purge = tokio::spawn(async move {
Db::for_testing(pool_for_task)
.delete_repo_by_id("rid-purge-race-target")
.await
});

// Give the purge time to reach the lock wait (GREEN) or, without the lock, to
// run its whole sibling-check-then-cascade (RED) before the mirror row lands.
tokio::time::sleep(std::time::Duration::from_millis(300)).await;

// Mirror ingestion lands the colliding `repos` row (slug-form id, bare owner) —
// exactly what upsert_mirror_repo writes. Raw insert here so it does not contend
// on the advisory lock the test connection is holding.
sqlx::query(
"INSERT INTO repos (id, name, owner_did, description, is_public, default_branch,
created_at, updated_at, disk_path, machine_id, quarantined)
VALUES ($1, 'victim', 'z6MkPurgeRaceMirrorFixtureForLock', 'mirrored from peer',
true, 'main', '2026-02-01T00:00:00Z', '2026-02-01T00:00:00Z',
'/srv/mirror', NULL, false)",
)
.bind(&slug)
.execute(db.pool())
.await
.unwrap();

// Release the lock so the purge can proceed (and observe the mirror row).
sqlx::query("SELECT pg_advisory_unlock(hashtextextended($1, 0))")
.bind(&slug)
.execute(&mut *lock_conn)
.await
.unwrap();

let removed = purge.await.unwrap().unwrap();
assert_eq!(removed, 1, "the empty canonical target row is purged");

async fn count(db: &Db, sql: &str, arg: &str) -> i64 {
sqlx::query_scalar::<_, i64>(sql)
.bind(arg)
.fetch_one(db.pool())
.await
.unwrap()
}
// No half-wipe: the mirror row AND its slug-scoped state are all present.
assert_eq!(
count(&db, "SELECT COUNT(*) FROM repos WHERE id=$1", &slug).await,
1,
"the mirror repos row survives the purge"
);
assert!(
count(&db, "SELECT COUNT(*) FROM branch_cids WHERE repo=$1", &slug).await > 0,
"mirror branch_cids must survive: the purge serialized behind the ingest and saw the sibling"
);
assert_eq!(
db.get_bounty("bnt-purge-race")
.await
.unwrap()
.unwrap()
.status,
"open",
"the mirror's bounty must stay open, not be tombstoned by the racing purge"
);
}

/// U8 (F): bounties key on (repo_owner, repo_name), not an immutable repo id,
/// and `delete_repo_by_id` deliberately does not delete them (financial record).
/// Without tombstoning, a purged repo's OPEN bounty stays claimable and silently
Expand Down