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.

clew/buildlock.py:128

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
            pass

1 more lines, not shown

Activity · 31 steps
lines 145–145trylines 146–146import fcntllines 147–147except ImportError: # pragma: no cover - Windowslines 150–150logger.debug("build lock: fcntl unavailable — proceeding without a cross-process lock")lines 151–151yield Nonelines 152–152returnlines 154–154path = lock_path(output)lines 155–155fd = Nonelines 156–156trylines 157–157path.parent.mkdir(parents=True, exist_ok=True)lines 158–158fd = os.open(str(path), os.O_CREAT | os.O_WRONLY, 0o644)lines 159–159except OSError as exclines 161–161logger.debug("build lock: cannot open %s (%s) — proceeding unlocked", path, exc)lines 162–162◇ if fd is not Nonelines 163–163os.close(fd)lines 164–164yield Falselines 165–165returnlines 167–167held = Falselines 168–168trylines 169–169deadline = time.monotonic() + max(0.0, wait_seconds)lines 170–170◇ while Truelines 171–171trylines 172–172fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)lines 173–173held = Truelines 174–174breaklines 175–175except OSErrorlines 178–178◇ if time.monotonic() >= deadlinelines 179–185logger.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, )lines 186–186breaklines 187–187time.sleep(_POLL_SECONDS)lines 188–188yield held

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.

clew/buildlock.py:104

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
lines 106–106key = str(output.resolve())lines 107–107◇ if key in _HELDlines 108–108yield Truelines 109–109returnlines 110–110with _os_lock(output, wait_seconds) as heldlines 111–111◇ if heldlines 112–112_HELD.add(key)lines 113–113trylines 114–114yield held

Requirements

REQ-DDB-INDEX-002

Flows

lock_path

Path clew.buildlock.lock_path(Path output)

Path of the lock file guarding one target's build.

clew/buildlock.py:78

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)

Activity · 1 steps
lines 87–87return output.with_name(output.name + LOCK_SUFFIX)

Flows