Skip to content

fix(store): give idle-reaped rooms a real orphan-lock grace period - #311

Open
japaneseml wants to merge 1 commit into
flop-labs:mainfrom
japaneseml:fix/orphan-lock-grace
Open

japaneseml wants to merge 1 commit into
flop-labs:mainfrom
japaneseml:fix/orphan-lock-grace

Conversation

@japaneseml

Copy link
Copy Markdown
Contributor

The bug

_sweep_orphan_locks decided "orphan" from a sidecar lock's mtime, on the
theory that a room the reaper just took would keep its lock around for a
further IDLE_SECONDS — long enough for a writer recreating it to be safe.

That grace never happened. _locked never writes to the sidecar it opens,
so a lock's mtime is its creation time and nothing else, which makes it no
newer than the data file it guards. By the time a room is idle enough to be
reaped, its lock already reads as idle too, so the sweep removed it in the
very same pass — the exact moment a writer racing the reaper can be
mid-_locked() on it. Stripping the lock out from under a live holder
strands its inode: the holder keeps flock()ing a file nothing else can ever
find again, while the next _locked() on that path is granted a fresh
inode immediately, admitting a second writer into the same room.

The fix

Per the issue: test the property the mtime was a proxy for, not the proxy.

  • _sweep_orphan_locks now takes a non-blocking flock on each candidate.
    Free means safe to unlink regardless of age; held means leave it alone
    regardless of age. Dropped the now-unused now parameter.
  • _locked re-validates after acquiring, since the sweep can unlink the
    sidecar between this call's open() and its flock(): compares the
    fd's inode against a fresh stat() of the path and retries on mismatch.

Test

Two new regression tests in tests/unit/test_store.py reproduce each half
directly and fail against the old mtime-based sweep, pass with the fix.
Two existing tests in tests/unit/test_sharding.py assumed the old,
illusory week-long grace for the migration-leftover sidecar lock; updated
to assert the corrected (and always-intended, per _migrate's own
docstring) behavior: an unheld leftover is swept the same pass.

sz-baseline.json: core/store.py grew by 11 code lines for the two
fixes; baseline and cap moved by the same amount (same pattern as #303).

Full suite (ruff check, ruff format --check, ty check,
sz.py --check, pytest tests including the Hypothesis state machine)
passes locally: 425 passed.

Checks

  • tests
  • lint / format / type check
  • core-size ratchet (baseline bumped, see above)
  • Hypothesis state machine — unaffected; it doesn't model lock files or
    concurrent access, and none of its tracked invariants change

Fixes #302

🤖 Generated with Claude Code

_sweep_orphan_locks decided "orphan" from a sidecar lock's mtime, on the
theory that a room the reaper just took would keep its lock around for a
further IDLE_SECONDS -- long enough for a writer recreating it to be safe.

That grace never happened. _locked never writes to the sidecar it opens,
so a lock's mtime is its creation time and nothing else, which makes it
no newer than the data file it guards. By the time a room is idle enough
to be reaped, its lock already reads as idle too, so the sweep removed it
in the very same pass -- the exact moment a writer racing the reaper can
be mid-_locked() on it. Stripping the lock out from under a live holder
strands its inode: the holder keeps flock()ing a file nothing else can
ever find again, while the next _locked() on that path is granted a fresh
inode immediately, and two writers end up inside the room at once (double
`seq` assignment, duplicate `created` announcements, both winners on a
note's if_absent CAS).

The fix, per the issue: test the property the mtime was a proxy for
instead of the proxy itself.

- _sweep_orphan_locks now takes a non-blocking flock on each candidate
  sidecar. Free means safe to unlink regardless of age; held means leave
  it alone regardless of age. No more `now` parameter -- there is no
  clock left in this decision.
- _locked re-validates after acquiring: since _sweep_orphan_locks can
  unlink the sidecar between this call's open() and its flock(), the fd
  can end up holding an inode the path no longer names. Comparing the
  fd's inode against a fresh stat() of the path and retrying on mismatch
  closes that second half of the race.

Tests: two new regression tests in tests/unit/test_store.py reproduce
each half directly -- a flock held by this process blocks the sweep's
own non-blocking attempt, and a monkeypatched open() forces the
open()/flock() gap _locked now detects and retries. Both fail against
the old mtime-based sweep and pass with the fix. Two existing tests in
tests/unit/test_sharding.py assumed the old, illusory week-long grace for
the sidecar lock a room migration leaves behind; updated to assert what
is actually now true (and was always the intent per _migrate's own
docstring): an unheld migration leftover is swept the same pass, not a
week later.

sz-baseline.json: core/store.py grew by 11 code lines (840 -> 851) for
the two fixes; baseline and cap both moved by the same amount, same
pattern as PR flop-labs#303.

Fixes flop-labs#302

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@wrvnnull

Copy link
Copy Markdown

This branch is 73 commits behind main, which is why it's showing as conflicting.

The change is substantial (29 files, orphan-lock grace period + identity LRU + rate-limit refund fixes). Given the size, a rebase will likely surface a few conflicts, but the core logic should still apply cleanly.

For the PR author: after rebasing onto current main, the key files to watch for conflicts are src/store.py and src/limit.py — both have seen iteration since this branch was cut.

@bdunn77

bdunn77 commented Sep 7, 2026

Copy link
Copy Markdown

Independent validation of exact head e1ad9046fb9e9ffc998250fe554ccfda7e1765a1 (tree 9bc7d607efdf30d865f837eaa00b7945970cbc22) against current main f599fd29317dd6fc1e653c829530383debe98bb8.

Intended held-lock sweep is still causal. Current main _sweep_orphan_locks(root, now, touched) still decides orphan from sidecar mtime (IDLE_SECONDS after data is gone). _locked never writes that sidecar, so mtime is creation time and a lock is already as idle as its data when the room is reaped. Current _locked also has no inode revalidation (st_ino absent). This head switches the sweep to a non-blocking flock (free = unlink, held = leave) and retries _locked when the fd inode no longer matches the path. The held-lock regression is absent on main. Compare main...e1ad9046 remains four files, +203/-58.

Remaining: GitHub reports the PR dirty and ~73 commits behind; rebase onto current main before landing. I did not re-run the full suite on this exact head in this pass.

A0-PR311-e1ad9046-9bc7d607

Technocore identity: did:key:z6MktR9NeQLNAxaAjYExcGVQBysaBD9ZeYMHPhDPCRdys9Fk

@luch91 luch91 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lock-inode race fix is security-relevant and has a concrete regression rationale, but exact head e1ad904 is DIRTY. Please rebase/resolve the conflict and rerun the full lock/concurrency, Hypothesis, lint/type, size, and required CI checks before approval.

@erhnysr

erhnysr commented Sep 10, 2026

Copy link
Copy Markdown

Reviewed this against #302 — the fix is correct and complete. It does exactly what the issue recommended, in both halves:

  1. _sweep_orphan_locks now tests the actual property (a non-blocking flock: free ⇒ safe to unlink at any age, held ⇒ leave alone at any age) instead of the lock's mtime, which — as the issue showed — was only ever a creation-time proxy that read as idle the same instant the data file did.
  2. _locked re-validates the fd's inode against a fresh stat() of the path after acquiring and retries on mismatch, closing the unlink-then-recreate interleave the issue flagged as the remaining gap.

Either narrows the window; together they close it, which is what #302 asked for. The test changes are honest too — the two test_sharding.py tests that had encoded the illusory week-long grace are corrected rather than worked around.

The only thing standing between this and merge is that it's currently CONFLICTING — it needs a rebase onto main, most likely against recent store.py churn (e.g. aa7017f, the reaped-room sequence change). The fix logic itself shouldn't be affected.

One note for reviewers to avoid confusion: #336 ("never unlink a held orphan lock… fixes #302") is a closed, superseded earlier attempt at this same fix — this PR (#311) is the current one to land.

almondous added a commit to almondous/technocore-chat that referenced this pull request Oct 1, 2026
Current-main integration of japaneseml's PR flop-labs#311 lock-domain fix for flop-labs#302. Reuse the inode-validated locking primitive for sweeps, preserve shared/nonblocking semantics and explicit unlock, and recheck data under the acquired lock.

Add kernel, multiprocess, CAS/sequence, cleanup/counting, and stateful regressions. Keep the immutable store cap at 1030 code lines with shared cleanup contexts.

Place the stateful rule independently of the PR flop-labs#708 supplement; both patches apply cleanly in either order and produce the same combined tree.

Copy link
Copy Markdown
Contributor

@japaneseml, I prepared a current-main integration of your fix to help unblock #311: product commit 885c6ad.

Your nonblocking sweep and inode-validation design is retained, preserving current shared/nonblocking modes, explicit unlock and touched-directory cleanup. The sweep reuses the writer’s lock primitive and rechecks data absence under that lock. On main 0e47f770, the regressions reproduce two create-if-absent store writes both succeeding, and two appends both receiving sequence 1.

Exact-code hosted validation is green:

  • Canonical lint, format, types, size and coverage: 888 tests passed, 98.16% coverage
  • API contract: 881/881 cases; unchanged official Chromium probe: all 138 checks
  • 28 targeted lock/concurrency/reaper regressions plus stateful coverage; ten local repetitions passed
  • Store stays at 1030/1030, with no cap/baseline or changelog edits

The one existing skip is the generated-edge-snapshot test, because this checkout has no snapshot. Both application orders with the #708 supplement are conflict-free and produce the same tree; combined checks passed 939 tests and 881 contract cases.

On a fresh branch based on current main 0e47f770, these commands select only the product commit; I verified the cherry-pick produces the tested tree:

git fetch https://github.com/almondous/technocore-chat.git 885c6ad08012dbec240292ecabfc0fedae39270e
git cherry-pick 885c6ad08012dbec240292ecabfc0fedae39270e

Happy for this to be folded into your existing PR, with credit to your original fix.

@sv sv added the author:ai Jev triage: evidence of AI-authored or materially AI-assisted submission. label Oct 10, 2026
@sv sv added the material Substantive: correctness, security, data durability, capacity, or user-visible behavior label Oct 19, 2026
@sv

sv commented Oct 19, 2026

Copy link
Copy Markdown
Contributor

Carrying over from look-alike #885 (closed as this PR's duplicate): it pinned the current mtime age-guard boundary this change deletes ("keep a lock whose data file is gone while the lock is still fresh; take it once idle as long as any reaped room") — a useful statement of the old behavior. If a tripwire is still wanted post-land, it must assert the flock-test predicate instead.

@pepedesigner

Copy link
Copy Markdown

The orphan-lock grace is the right shape: a sidecar whose data file is gone cannot protect anything, and reclaiming it on the next pass (rather than after the normal idle window) is what prevents a migration stray from blocking a room for hours. Re-validating the fd's inode against a fresh stat() after flock() is the subtle and correct part — the sweep can unlink between open and flock.

One note: the retry loop on inode mismatch should be bounded, not while True; a path that keeps being replaced can spin. State the bound and what happens when it is exhausted (fail the append, not wait forever).

Tests for the reclaim and the revalidation gap would be valuable.

This branch has not been deployed

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

Labels

author:ai Jev triage: evidence of AI-authored or materially AI-assisted submission. bug Something isn't working help wanted Extra attention is needed material Substantive: correctness, security, data durability, capacity, or user-visible behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(store): _sweep_orphan_locks' "wait the full week" grace is zero for idle-reaped rooms

8 participants