-
Notifications
You must be signed in to change notification settings - Fork 0
fix(lock): kernel-mediated byte lock with fail-safe cleanup and classified contention #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
3ae4ccd
fix(lock): replace stale-file sweep with kernel-mediated byte lock
justkidding2047 201cd3f
test(lock): deterministic cross-process race and leak regression cove…
justkidding2047 5ebf973
chore(tests): drop unused imports and locals flagged by ruff
justkidding2047 bf6e6e9
chore(lint): pin ruff's rule selection, not its version
justkidding2047 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| """Subprocess contender used by RepositoryLock concurrency tests. | ||
|
|
||
| Driven by a JSON config file so the parent test can orchestrate real | ||
| cross-process contention deterministically: | ||
|
|
||
| python _lock_child.py <config.json> | ||
|
|
||
| Config keys: | ||
| repo, operation, wait_seconds -- lock identity and wait budget | ||
| signaldir -- directory for markers/outcomes | ||
| id -- this child's marker suffix ("0"/"1") | ||
|
|
||
| Optional deterministic seams (inert unless the implementation calls the | ||
| patched functions during acquisition): | ||
| barrier_pid_exists -- synchronize BOTH children at the stale-pid | ||
| observation point before psutil.pid_exists returns | ||
| wait_peer_created_then_unlink -- before unlinking the lock path, block | ||
| until the peer reports holding the lock (forces | ||
| the stale-sweep to run against a *live* lock) | ||
|
|
||
| Outcome protocol: writes ``outcome-<id>.json`` ({acquired, error}); when | ||
| acquired, also writes ``holding-<id>`` and keeps the lock until a | ||
| ``release-<id>`` file appears (polling with hard caps so nothing hangs). | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import os | ||
| import sys | ||
| import time | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| def _await_file(path: Path, timeout: float = 15.0) -> bool: | ||
| deadline = time.monotonic() + timeout | ||
| while time.monotonic() < deadline: | ||
| if path.exists(): | ||
| return True | ||
| time.sleep(0.02) | ||
| return False | ||
|
|
||
|
|
||
| def _patch_pid_exists_barrier(signaldir: Path, child_id: str, peer_id: str) -> None: | ||
| """Both children meet here before agreeing the pid is dead.""" | ||
| import psutil | ||
|
|
||
| mine = signaldir / f"saw-stale-{child_id}" | ||
| peers = signaldir / f"saw-stale-{peer_id}" | ||
|
|
||
| def synchronized(pid: int) -> bool: | ||
| mine.write_text(str(pid), encoding="ascii") | ||
| if not _await_file(peers): | ||
| raise RuntimeError("pid_exists barrier timed out") | ||
| return False # both contenders agree: stale | ||
|
|
||
| psutil.pid_exists = synchronized | ||
|
|
||
|
|
||
| def _patch_unlink_waits_for_peer(signaldir: Path, child_id: str, peer_id: str, lock_path: Path) -> None: | ||
| """Force the stale-sweep unlink to run after the peer recreated the lock.""" | ||
| real_unlink = os.unlink | ||
|
|
||
| def ordered_unlink(path, *args, **kwargs): | ||
| try: | ||
| if Path(path).resolve() == lock_path.resolve(): | ||
| if not _await_file(signaldir / f"holding-{peer_id}"): | ||
| raise RuntimeError("peer-created barrier timed out") | ||
| except OSError: | ||
| pass # not the lock path, or already gone: behave like unlink | ||
| return real_unlink(path, *args, **kwargs) | ||
|
|
||
| os.unlink = ordered_unlink | ||
|
|
||
|
|
||
| def main() -> int: | ||
| config = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) | ||
| signaldir = Path(config["signaldir"]) | ||
| child_id = str(config["id"]) | ||
| peer_id = str(config["peer"]) | ||
| outcome_path = signaldir / f"outcome-{child_id}.json" | ||
|
|
||
| from worker_bridge.workspace import RepositoryLock | ||
|
|
||
| lock = RepositoryLock( | ||
| config["repo"], operation=config["operation"], wait_seconds=config["wait_seconds"] | ||
| ) | ||
|
|
||
| if config.get("barrier_pid_exists"): | ||
| _patch_pid_exists_barrier(signaldir, child_id, peer_id) | ||
| if config.get("wait_peer_created_then_unlink"): | ||
| _patch_unlink_waits_for_peer(signaldir, child_id, peer_id, lock._path) | ||
|
|
||
| try: | ||
| with lock: | ||
| (signaldir / f"holding-{child_id}").write_text("", encoding="ascii") | ||
| outcome_path.write_text( | ||
| json.dumps({"id": child_id, "acquired": True, "error": None}), encoding="utf-8" | ||
| ) | ||
| _await_file(signaldir / f"release-{child_id}", timeout=30.0) | ||
| return 0 | ||
| except Exception as exc: # noqa: BLE001 - report every failure shape to the parent | ||
| outcome_path.write_text( | ||
| json.dumps({"id": child_id, "acquired": False, "error": f"{type(exc).__name__}: {exc}"}), | ||
| encoding="utf-8", | ||
| ) | ||
| return 1 | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| raise SystemExit(main()) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| """Shared helpers for cross-process RepositoryLock tests. | ||
|
|
||
| Spawns real contender subprocesses (``_lock_child.py``) coordinated through | ||
| marker files, so mutual exclusion is tested against actual OS-level | ||
| processes rather than simulated lock-file contents. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import subprocess | ||
| import sys | ||
| import time | ||
| from pathlib import Path | ||
|
|
||
| CHILD = Path(__file__).parent / "_lock_child.py" | ||
|
|
||
|
|
||
| def child_config(tmp: Path, *, repo: Path, operation: str, wait_seconds: float, | ||
| id: str, peer: str, **overrides) -> Path: # noqa: A002 - test fixture ids | ||
| config = { | ||
| "repo": str(repo), | ||
| "operation": operation, | ||
| "wait_seconds": wait_seconds, | ||
| "signaldir": str(tmp / "signals"), | ||
| "id": id, | ||
| "peer": peer, | ||
| } | ||
| config.update(overrides) | ||
| (tmp / "signals").mkdir(parents=True, exist_ok=True) | ||
| path = tmp / f"config-{id}.json" | ||
| path.write_text(json.dumps(config), encoding="utf-8") | ||
| return path | ||
|
|
||
|
|
||
| def spawn(config: Path) -> subprocess.Popen: | ||
| return subprocess.Popen( | ||
| [sys.executable, str(CHILD), str(config)], | ||
| stdout=subprocess.PIPE, | ||
| stderr=subprocess.PIPE, | ||
| text=True, | ||
| ) | ||
|
|
||
|
|
||
| def await_file(path: Path, timeout: float = 30.0) -> str: | ||
| deadline = time.monotonic() + timeout | ||
| while time.monotonic() < deadline: | ||
| if path.exists(): | ||
| return path.read_text(encoding="utf-8") | ||
| time.sleep(0.02) | ||
| raise AssertionError(f"timed out waiting for {path.name}") | ||
|
|
||
|
|
||
| def outcome(tmp: Path, child_id: str) -> dict: | ||
| return json.loads(await_file(tmp / "signals" / f"outcome-{child_id}.json")) | ||
|
|
||
|
|
||
| def release_and_join(tmp: Path, children: list[subprocess.Popen]) -> None: | ||
| for child_id in ("0", "1"): | ||
| (tmp / "signals" / f"release-{child_id}").write_text("", encoding="ascii") | ||
| for proc in children: | ||
| proc.wait(timeout=30) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Lock scheme breaks mixed upgrades
Medium Severity
The new kernel byte lock still uses the same per-key
.lockpath as the oldO_EXCLscheme. An upgraded process canopenthat file and takeflock/msvcrt.lockingwhile a pre-upgrade holder only owns the path via exclusive create and an open fd, so both can enter the critical section during a rolling upgrade.Additional Locations (2)
src/worker_bridge/workspace.py#L170-L188src/worker_bridge/workspace.py#L259-L261Reviewed by Cursor Bugbot for commit bf6e6e9. Configure here.