Skip to content

fix(id/web): SaveRateLimiter::acquire is not atomic — a save completing between its check and its reservation re-opens the cooldown (PR #4193 follow-up) #9587

Closed

Description

@dezren39

Finding

PR #4193 (merged, commit 06ea8c8) fixed the #2466 check/record race by adding SaveRateLimiter::acquire, but the acquire path itself is not atomic, and its design note claims it is:

  • The design doc merged in the same PR (doc/2026-11-02T07-00-00Z_design_save_reservations/2026-11-02T07-00-00Z_design_save_reservations.md, decision 1) says acquire "combines the existing cooldown check with an in-flight reservation, taken atomically under the in-flight lock".
  • The code — unchanged on current main at pkgs/id/crates/id-web/src/lib.rs:156-166 (the file moved in the crate split; line numbers are current main) — does:
pub async fn acquire(&self, name: &str) -> Result<SavePermit, Duration> {
    self.check(name).await?;                       // (1) cooldown check, tokio mutex on last_save
    let mut flight = self.in_flight.lock()          // (2) reservation, a *different* std mutex
        .unwrap_or_else(|poisoned| poisoned.into_inner());
    if !flight.insert(name.to_owned()) { return Err(self.cooldown); }
    ...
}

check (1) and the reservation insert (2) are separated by an await on a different lock, so on the multi-threaded tokio runtime the web server runs on, this interleaving is possible:

  1. Save A holds the permit and is finishing: SavePermit::complete() calls record() (writes last_save[name] = now), then Drop removes name from in_flight.
  2. Save B calls acquire(name) and its check reads last_save before A's record() lands — it passes.
  3. B's insert runs after A's Drop removed the name — it succeeds.

B is admitted inside the cooldown A just recorded. This does not recreate the original #2466 overlap (B can only insert after A released the reservation, i.e. after A finished, so saves never run concurrently) — what it re-opens is the cooldown guarantee that acquire exists to enforce atomically: a client retrying at exactly the completion moment bypasses the 5 s rate limit the 429 contract promises.

Second, smaller defect in the same lifecycle: SavePermit::drop (current main, lib.rs:206-208) releases the reservation with if let Ok(mut flight) = ...lock(), while acquire explicitly recovers a poisoned lock with into_inner(). If the in_flight mutex is ever poisoned, Drop silently leaves the name in the set, and every later acquire (which recovers the guard and sees the name still present) refuses that filename forever — a permanently wedged save for that file, with no error anywhere.

Evidence

Why it matters

The whole point of #4193 over the old check/record split was that the cooldown + in-flight decision is one atomic step. As merged (and still on main) it is two steps with a completion window between them, so the rate-limit guarantee has a race at exactly the busiest moment (a save just completed, a retry already waiting). The poisoned-Drop asymmetry is a latent permanent wedge for a filename if the lock is ever poisoned — and acquire's own poison recovery shows poisoning was contemplated on one path but not the other.

Acceptance criteria

  • acquire re-validates the cooldown after taking the in-flight reservation (or otherwise makes check + reserve atomic with respect to record + release), so a save that records while another acquire is between check and insert causes that acquire to be refused with the cooldown error, and the refused acquire leaves no reservation behind.
  • A deterministic regression test orchestrates the completion-during-acquire interleaving (not a sleep/timing loop) and fails before the fix / passes after; the existing limiter tests (refuses second in-flight, concurrent acquires admit exactly one, dropped permit releases without recording, completed permit records) still pass.
  • SavePermit::drop recovers a poisoned in_flight lock the same way acquire does (into_inner), with a test or a reasoned note if a poison test is impractical.
  • The design doc's "taken atomically" wording matches the implementation after the fix.

Shadow note

Stage A shadow verdicts are closed (window ended 2026-11-13, summary on #2313), so no shadow verdict section is attached to this filing.

Activity

  1. added
    kind/bugSomething isn't working (prefixed form of the classic bug label)
    task/triageQueue packet kind: verify, reproduce, and route this item
    priority/normalOrdinary priority (the default)
    on Nov 13, 2026
  2. developing-today commented on Nov 13, 2026

    @developing-today
    Contributor
  3. added
    app/idPackage/app: id (pkgs/ or apps/ in this repo)
    effort/xsTrivial: expected under 30 minutes of work
    on Nov 13, 2026
  4. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    🤖 Agent note · filed

  5. added
    queue/claimedQueue worker lifecycle state
    work/assignedQueue worker lifecycle state
    task/small-fixQueue packet kind: bounded fix with reproduction and targeted tests
    and removed
    task/triageQueue packet kind: verify, reproduce, and route this item
    on Nov 13, 2026
  6. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    🤖 Agent note · picked up + triaged

  7. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    Triage verified against fresh GitHub state. Both defects confirmed present on current main.

    Defect A — acquire check and reservation are not mutually atomic

    pkgs/id/crates/id-web/src/lib.rs, SaveRateLimiter::acquire (origin/main lines ~155-168):

    pub async fn acquire(&self, name: &str) -> Result<SavePermit, Duration> {
        self.check(name).await?;                       // (1) locks `last_save`, sees only COMPLETED saves
        let mut flight = self.in_flight.lock()...;     // (2) separate lock, taken after (1) returns
        if !flight.insert(name.to_owned()) { return Err(self.cooldown); }
        ...
    }

    check (cooldown, tokio mutex on last_save) and the in-flight reservation (std mutex on in_flight) are two separate critical sections. SavePermit::complete does record() (sets last_save) then Drop (removes in_flight) — in that order. So this interleaving admits a save inside a just-recorded cooldown:

    1. A2 acquire: check("a.txt") returns Ok — no prior completed save.
    2. A1 complete: record("a.txt") sets last_save = now; then A1's permit Drop removes "a.txt" from in_flight.
    3. A2 acquire: in_flight.insert("a.txt") now succeeds ("a.txt" was just removed) → A2 is admitted, bypassing the cooldown A1 just recorded.

    This is exactly the race PR #4193 was meant to close, re-opened for a completed save rather than an overlapping one.

    Defect B — SavePermit::drop does not recover lock poisoning

    acquire recovers poisoning with .unwrap_or_else(|p| p.into_inner()), but Drop (origin/main lines ~205-209) uses if let Ok(mut flight) = ... .lock():

    fn drop(&mut self) {
        if let Ok(mut flight) = self.limiter.in_flight.lock() {
            flight.remove(&self.name);
        }
    }

    If in_flight is ever poisoned (a panic while the lock is held), drop silently skips the removal, stranding the filename in in_flight forever — every later acquire for that file returns Err(cooldown). acquire recovers; drop wedges.

    Design-doc mismatch (acceptance item 4)

    doc/2026-11-02T07-00-00Z_design_save_reservations/…md decision 1 states the cooldown check and the in-flight reservation are "taken atomically under the in-flight lock". They are not: the check runs in a separate critical section before the lock is taken. The wording needs to match whatever the fix makes true.

    Proposed fix (reserve, then re-validate)

    Reorder so the reservation is taken first and the cooldown is re-validated after it; a refused acquire releases the reservation it just took:

    pub async fn acquire(&self, name: &str) -> Result<SavePermit, Duration> {
        // Reserve first so a concurrent complete() (record-then-release) cannot
        // slip between the cooldown check and the reservation.
        {
            let mut flight = self.in_flight.lock().unwrap_or_else(|p| p.into_inner());
            if !flight.insert(name.to_owned()) {
                return Err(self.cooldown); // already in flight
            }
        }
        if let Err(remaining) = self.check(name).await {
            // A save completed after we reserved: release and refuse.
            let mut flight = self.in_flight.lock().unwrap_or_else(|p| p.into_inner());
            flight.remove(name);
            return Err(remaining);
        }
        Ok(SavePermit { limiter: self.clone(), name: name.to_owned() })
    }
    
    impl Drop for SavePermit {
        fn drop(&mut self) {
            let mut flight = self.limiter.in_flight.lock().unwrap_or_else(|p| p.into_inner());
            flight.remove(&self.name);
        }
    }

    Invariant: in_flight.insert succeeds only when no permit for the name is outstanding, so no other record/drop for that name can run between our insert and our re-check; the re-check therefore observes any cooldown a prior completion recorded. Update the acquire doc comment and design decision 1 to say the reservation is taken first and the cooldown re-validated under it.

    Test plan (acceptance item 2)

    • Add a regression test that fails on the current code and passes post-fix. A fully deterministic interleaving (pause between check and insert) has no existing seam; recommended: add a #[cfg(test)] hook — a counter/Notify consulted between the old check and insert points — so the test can force the A2.check → A1.complete → A2.insert order, assert A2 is refused post-fix. If a seam is judged too intrusive, a bounded-loop concurrent stress test (many join! acquire/complete pairs) reliably catches the race pre-fix; note the determinism trade-off in the PR.
    • Keep existing tests green (test_save_limiter_acquire_refuses_a_second_in_flight_save, …completed_permit_records_the_cooldown, …concurrent_acquires_admit_exactly_one, …dropped_permit_releases_without_recording).

    Disposition

    Fix deferred to a queued follow-up (small fixes are not compiled on this host within the run budget — no warm target/; CI-first). Follow-up task enqueued against issue #9587.

  8. added a commit that references this issue on Nov 13, 2026
  9. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    🤖 Agent note · done

    • Agent: repo-worker-code (Muse lane any-a)
    • Session / ID: queue task 16143, lane any-a shift 2026-11-13 14:30 CST
    • Outcome: fixed_merged — PR fix(id/web): make SaveRateLimiter::acquire atomic vs completion (#9587) #9590 MERGED (merge commit d6a257b, verified as origin/main HEAD; fix commit c86e990 is an ancestor); issue fix(id/web): SaveRateLimiter::acquire is not atomic — a save completing between its check and its reservation re-opens the cooldown (PR #4193 follow-up) #9587 CLOSED by the merge.
    • Fix: SaveRateLimiter::acquire (pkgs/id/crates/id-web/src/lib.rs) now re-validates the cooldown after taking the in-flight reservation — complete() records before Drop releases, so a completion racing the check/reserve gap is observed and refused, and a refused acquire releases its reservation. SavePermit::drop recovers a poisoned in-flight lock via into_inner(), matching acquire. Design doc decisions 1/3 wording updated to match.
    • Tests: limiter suite 9/9 pass, including a new deterministic interleaving regression (locks + tokio-mutex FIFO orchestrate a completion between check and reserve, no sleeps) that was verified to FAIL pre-fix at the refusal assert via a temporary revert, and a new poisoned-Drop test. Full id-web lib suite 651 passed / 1 failed — test_load_asset_urls_from_manifest fails identically on clean origin/main in a bare worktree (asset manifest not built; pre-existing, unrelated). Clippy could not run in the pooled target dir (E0514 rustc mismatch, environment).
    • Reviews: Codex review failed to run (usage limits; no findings produced). CodeRabbit was still pending (non-required; branch protection has no required status checks) at merge time; targeted tests verified locally per the standing merge criteria.
  10. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    🤖 Agent note · already done (duplicate packet)

  11. dezren39 commented on Nov 13, 2026

    @dezren39
    MemberAuthor

    Agent note — task 16149 pickup + already-done (lane any-b)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    app/idPackage/app: id (pkgs/ or apps/ in this repo)effort/xsTrivial: expected under 30 minutes of workkind/bugSomething isn't working (prefixed form of the classic bug label)priority/normalOrdinary priority (the default)source/pr-diff-reviewFiled by the pr-diff-review jobstatus:donetask/small-fixQueue packet kind: bounded fix with reproduction and targeted tests

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions