buildlock.py¶
clew/buildlock.py
A cross-process advisory lock over one target's build.
_os_lock
Iterator[bool | None] clew.buildlock._os_lock(Path output, float wait_seconds)
Take the OS advisory lock for one output, bounded and failing open.
Source · 73 lines
def _os_lock(output: Path, wait_seconds: float) -> Iterator[bool | None]:
"""YIELDS A BOOLEAN RATHER THAN RAISING, so the caller decides what a contended target means.
The MCP server re-checks freshness and skips; the CLI builds regardless. Neither can be
blocked by this.
`False` means "another process is building, or locking is unavailable here" — never "give up".
A caller that treats False as a failure would reintroduce the hang this design avoids.
THE WAIT EXISTS TO EARN A SKIP, and that is its only purpose. If the other builder finishes
inside the bound, this process re-checks and finds the index current, which is the whole win.
If it does not, this process builds too — wasteful, and still correct, because staging paths
are per-process and the swap is atomic.
@brief Acquire the cross-process build lock if possible.
@return Yields whether the lock is held.
@version 1
"""
try:
import fcntl
except ImportError: # pragma: no cover - Windows
## No advisory locking here. Proceed unlocked: a duplicate build is the cost, and it is
## the same cost this module exists to reduce rather than to guarantee away.
logger.debug("build lock: fcntl unavailable — proceeding without a cross-process lock")
yield None
return
path = lock_path(output)
fd = None
try:
path.parent.mkdir(parents=True, exist_ok=True)
fd = os.open(str(path), os.O_CREAT | os.O_WRONLY, 0o644)
except OSError as exc:
## An unwritable state directory is a real deployment, and it must not stop a build.
logger.debug("build lock: cannot open %s (%s) — proceeding unlocked", path, exc)
if fd is not None:
os.close(fd)
yield False
return
held = False
try:
deadline = time.monotonic() + max(0.0, wait_seconds)
while True:
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
held = True
break
except OSError:
## Held by another process. Wait for it, so this process can skip rather than
## duplicate — but only up to the bound.
if time.monotonic() >= deadline:
logger.warning(
"build lock: another process has been building %s for over %.0f s — "
"building anyway rather than waiting longer, WITHOUT the shared index "
"cache and in a private scratch directory (slower, and safe).",
output.name,
wait_seconds,
)
break
time.sleep(_POLL_SECONDS)
yield held
finally:
## The kernel would release on close regardless; unlocking explicitly makes the intent
## legible and releases a fraction earlier.
if held:
try:
fcntl.flock(fd, fcntl.LOCK_UN)
except OSError: # pragma: no cover - already gone
pass
try:
os.close(fd)
except OSError: # pragma: no cover
pass1 more lines, not shown
Activity · 31 steps
Flows
build_lock
Iterator[bool | None] clew.buildlock.build_lock(Path output, float wait_seconds=DEFAULT_WAIT_SECONDS)
Hold an exclusive cross-process lock on one target's build, or report not holding it.
Called by _hold, _run_build_walked, _run_pipeline, try_fast_refresh
Tested by 7 tests
test_a_contended_build_gives_up_and_proceeds, test_a_killed_holder_leaves_no_stale_lock, test_a_released_lock_is_taken_again, test_an_uncontended_build_holds_the_lock, test_an_unwritable_location_proceeds_unlocked, test_the_lock_is_reentrant_within_a_process, test_unavailable_locking_yields_none
Calls _os_lock
Source · 15 lines
def build_lock(output: Path, wait_seconds: float = DEFAULT_WAIT_SECONDS) -> Iterator[bool | None]:
"""@brief Re-entrant front of the OS lock. @return Yields True, False or None."""
key = str(output.resolve())
if key in _HELD:
yield True
return
with _os_lock(output, wait_seconds) as held:
if held:
_HELD.add(key)
try:
yield held
finally:
_HELD.discard(key)
Activity · 9 steps
Requirements
Flows
lock_path
Path clew.buildlock.lock_path(Path output)
Path of the lock file guarding one target's build.
Source · 12 lines
def lock_path(output: Path) -> Path:
"""A sibling of the database, so it lands in a directory that already exists before any build
(created by `TargetRegistry.register` or by the pipeline itself) and travels with the target
rather than living in a global namespace someone has to clean up.
@brief Derive the lock path.
@return The lock file path.
@version 1
"""
return output.with_name(output.name + LOCK_SUFFIX)