Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions src/specify_cli/shared_infra.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,12 +243,20 @@ def _validate_safe_shared_directory(project_path: Path, directory: Path) -> None


@contextlib.contextmanager
def _exclusive_project_lock(project_root: Path, lock_name: str, *, context: str):
def _exclusive_project_lock(
project_root: Path,
lock_name: str,
*,
context: str,
blocking: bool = True,
):
"""Hold an exclusive inter-process lock on ``.specify/<lock_name>``.
Callers use one lock file per mutable project resource so that its
directory and registry changes are serialized across processes. Every
failure to acquire the lock is raised as ``OSError``.
failure to acquire the lock is raised as ``OSError``. ``blocking`` waits
for the current holder; ``blocking=False`` raises immediately instead.
Releasing the lock closes its descriptor and does not delete the file.
"""
project_root = Path(project_root)
lock_dir = project_root / ".specify"
Expand Down Expand Up @@ -286,11 +294,27 @@ def _exclusive_project_lock(project_root: Path, lock_name: str, *, context: str)
except OSError as exc:
if exc.errno not in (errno.EACCES, errno.EDEADLK):
raise
if not blocking:
raise OSError(
f"Exclusive {context} lock is already held"
) from exc
time.sleep(0.05)
else:
import errno
import fcntl

fcntl.flock(fd, fcntl.LOCK_EX)
operation = fcntl.LOCK_EX
if not blocking:
operation |= fcntl.LOCK_NB
try:
fcntl.flock(fd, operation)
except OSError as exc:
busy = exc.errno in (errno.EAGAIN, errno.EWOULDBLOCK)
if not blocking and busy:
raise OSError(
f"Exclusive {context} lock is already held"
) from exc
raise
yield
finally:
os.close(fd)
Expand Down
165 changes: 88 additions & 77 deletions src/specify_cli/workflows/command_resume.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def workflow_resume(
"""Resume a paused or failed workflow run."""
from ..integrations.installer import IntegrationInstallError
from ._execution import CheckpointError
from .engine import RunState, WorkflowEngine
from .engine import RunState, WorkflowEngine, _resume_run_lock

project_root = cli._require_specify_project(load_integrations=False)
cli._load_project_workflow_plugins_or_exit(
Expand Down Expand Up @@ -50,94 +50,105 @@ def workflow_resume(
inputs = cli._parse_input_values(input_values, json_output=json_output)
err = cli._error_console(json_output)

# Pre-load the persisted run state so a run started from an installed
# workflow that has since been disabled cannot resume unchecked --
# engine.resume() replays the run directly from disk with no registry
# awareness at all, which would otherwise bypass the same disabled
# guard `workflow run` enforces. Runs without installed_workflow_id
# (a direct/non-installed source, or a run persisted before this field
# existed) are unaffected and resume exactly as before.
try:
pre_state = RunState.load(run_id, project_root)
except FileNotFoundError:
err.print(f"[red]Error:[/red] Run not found: {run_id}")
raise cli.typer.Exit(1)
except ValueError as exc:
err.print(f"[red]Error:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
except OSError as exc:
err.print(f"[red]Resume failed:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)

if pre_state.installed_workflow_id is not None:
def _resume_under_lock() -> None:
# Pre-load the persisted run state so a run started from an installed
# workflow that has since been disabled cannot resume unchecked --
# engine.resume() replays the run directly from disk with no registry
# awareness at all, which would otherwise bypass the same disabled
# guard `workflow run` enforces. Runs without installed_workflow_id
# (a direct/non-installed source, or a run persisted before this field
# existed) are unaffected and resume exactly as before.
try:
owner_root = resume_state._resolve_run_owner_root(
pre_state.installed_registry_root, project_root
)
pre_state = RunState.load(run_id, project_root)
except FileNotFoundError:
err.print(f"[red]Error:[/red] Run not found: {run_id}")
raise cli.typer.Exit(1)
except ValueError as exc:
err.print(f"[red]Error:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
cli._require_enabled_workflow(owner_root, pre_state.installed_workflow_id, err)
elif not pre_state.installed_origin_tracked:
if cli._require_enabled_workflow(project_root, pre_state.workflow_id, err):
pre_state.installed_workflow_id = pre_state.workflow_id
pre_state.installed_origin_tracked = True
try:
pre_state.save()
except (OSError, CheckpointError) as exc:
except OSError as exc:
err.print(f"[red]Resume failed:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)

try:
with cli._stdout_to_stderr_when(json_output):
state = engine.resume(run_id, inputs or None)
except FileNotFoundError as exc:
if engine._execution_state.get() is not None:
if pre_state.installed_workflow_id is not None:
try:
owner_root = resume_state._resolve_run_owner_root(
pre_state.installed_registry_root, project_root
)
except ValueError as exc:
err.print(f"[red]Error:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
cli._require_enabled_workflow(owner_root, pre_state.installed_workflow_id, err)
elif not pre_state.installed_origin_tracked:
if cli._require_enabled_workflow(project_root, pre_state.workflow_id, err):
pre_state.installed_workflow_id = pre_state.workflow_id
pre_state.installed_origin_tracked = True
try:
pre_state.save()
except (OSError, CheckpointError) as exc:
err.print(f"[red]Resume failed:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)

try:
with cli._stdout_to_stderr_when(json_output):
state = engine.resume(run_id, inputs or None)
except FileNotFoundError as exc:
if engine._execution_state.get() is not None:
cli._fail_workflow_execution(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
cli._fail_integration_load(
FileNotFoundError(f"Run not found: {run_id}"), json_output=json_output, run_id=run_id,
)
except IntegrationInstallError as exc:
execution_state = engine._execution_state.get()
if execution_state is None:
cli._fail_integration_load(exc, json_output=json_output, run_id=run_id)
cli._fail_workflow_execution(
exc, json_output=json_output, state=execution_state, resume=True,
)
except OSError as exc:
cli._fail_workflow_execution(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
cli._fail_integration_load(
FileNotFoundError(f"Run not found: {run_id}"), json_output=json_output, run_id=run_id,
)
except IntegrationInstallError as exc:
execution_state = engine._execution_state.get()
if execution_state is None:
cli._fail_integration_load(exc, json_output=json_output, run_id=run_id)
cli._fail_workflow_execution(
exc, json_output=json_output, state=execution_state, resume=True,
)
except OSError as exc:
cli._fail_workflow_execution(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
except ValueError as exc:
cli._fail_recorded_run(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
err.print(f"[red]Error:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
except Exception as exc:
cli._fail_recorded_run(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
err.print(f"[red]Resume failed:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)

if json_output:
cli._emit_workflow_json(cli._workflow_run_payload(state))
raise cli.typer.Exit(cli._run_outcome_exit_code(state.status.value))

status_colors = {
"completed": "green",
"paused": "yellow",
"failed": "red",
"aborted": "red",
}
color = status_colors.get(state.status.value, "white")
cli.console.print(f"\n[{color}]Status: {state.status.value}[/{color}]")

err_msg = cli._failed_step_error(state)
if err_msg:
cli.console.print(f"[red]Error:[/red] {cli._escape_markup(err_msg)}")

raise cli.typer.Exit(cli._run_outcome_exit_code(state.status.value))

try:
with _resume_run_lock(project_root, run_id):
_resume_under_lock()
except ValueError as exc:
cli._fail_recorded_run(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
err.print(f"[red]Error:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
except Exception as exc:
cli._fail_recorded_run(
exc, json_output=json_output, state=engine._execution_state.get(), resume=True,
)
except OSError as exc:
err.print(f"[red]Resume failed:[/red] {cli._escape_markup(str(exc))}")
raise cli.typer.Exit(1)
Comment on lines +152 to 154

if json_output:
cli._emit_workflow_json(cli._workflow_run_payload(state))
raise cli.typer.Exit(cli._run_outcome_exit_code(state.status.value))

status_colors = {
"completed": "green",
"paused": "yellow",
"failed": "red",
"aborted": "red",
}
color = status_colors.get(state.status.value, "white")
cli.console.print(f"\n[{color}]Status: {state.status.value}[/{color}]")

err_msg = cli._failed_step_error(state)
if err_msg:
cli.console.print(f"[red]Error:[/red] {cli._escape_markup(err_msg)}")

raise cli.typer.Exit(cli._run_outcome_exit_code(state.status.value))
47 changes: 47 additions & 0 deletions src/specify_cli/workflows/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

from __future__ import annotations

import contextlib
import json
import os
import re
Expand Down Expand Up @@ -1052,6 +1053,44 @@ def append_log(self, entry: dict[str, Any]) -> None:
f.write(json.dumps(entry, ensure_ascii=False) + "\n")


_resume_run_owners: ContextVar[tuple[str, ...]] = ContextVar(
"specify_resume_run_owners",
default=(),
)


@contextlib.contextmanager
def _resume_run_lock(project_root: Path, run_id: str):
"""Own one workflow run across processes for the duration of resume.
The lock is acquired before the caller loads or writes that run and is
released on every exit. The owning thread may re-enter, so the CLI can
hold the lock across its legacy checkpoint and ``WorkflowEngine.resume``.
A different process or thread is rejected immediately. The lock file stays
at ``.specify/workflow-run-<run_id>.lock`` and is not removed.
"""
from ..shared_infra import _exclusive_project_lock, _shared_relative_path

RunState._validate_run_id(run_id)
root = Path(project_root).resolve()
lock_name = f"workflow-run-{run_id}.lock"
relative = _shared_relative_path(root, root / ".specify" / lock_name)
if relative.parts != (".specify", lock_name):
raise ValueError(f"Workflow run lock escapes project root: {relative}")
key = os.path.normcase(str(root)) + "\n" + run_id
if key in _resume_run_owners.get():
yield
return
Comment on lines +1081 to +1083
with _exclusive_project_lock(
root, lock_name, context="workflow run", blocking=False
):
token = _resume_run_owners.set(_resume_run_owners.get() + (key,))
try:
yield
finally:
_resume_run_owners.reset(token)


# -- Workflow Engine ------------------------------------------------------


Expand Down Expand Up @@ -1255,6 +1294,14 @@ def resume(
workflow inputs. Keys not supplied keep their persisted values; an
empty/``None`` ``inputs`` leaves the run's inputs unchanged.
"""
with _resume_run_lock(self.project_root, run_id):
return self._resume_owned(run_id, inputs)

def _resume_owned(
self,
run_id: str,
inputs: dict[str, Any] | None,
) -> RunState:
self._execution_state.set(None)
Comment on lines +1297 to 1305
self._load_integrations()
state = RunState.load(run_id, self.project_root)
Expand Down
35 changes: 35 additions & 0 deletions tests/test_shared_infra_lock.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import os
import threading
import time

import pytest

Expand All @@ -20,6 +21,40 @@ def _symlink_or_skip(link, target, *, target_is_directory=False):
pytest.skip(f"symlinks are unavailable: {exc}")


def test_nonblocking_lock_rejects_immediately_and_keeps_the_file(tmp_path):
started = threading.Event()
release = threading.Event()
errors: list[BaseException] = []

def _hold():
try:
with _exclusive_project_lock(tmp_path, LOCK_NAME, context="test"):
started.set()
if not release.wait(10):
raise AssertionError("holder was not released")
except BaseException as exc: # noqa: BLE001 - surfaced below
errors.append(exc)

holder = threading.Thread(target=_hold, name="lock-holder", daemon=True)
holder.start()
assert started.wait(10)
started_at = time.monotonic()
with pytest.raises(OSError, match="already held"):
with _exclusive_project_lock(
tmp_path, LOCK_NAME, context="test", blocking=False
):
pass
assert time.monotonic() - started_at < 0.5
release.set()
holder.join(10)
assert not errors
assert (tmp_path / ".specify" / LOCK_NAME).is_file()
with _exclusive_project_lock(
tmp_path, LOCK_NAME, context="test", blocking=False
):
pass


def test_lock_creates_lock_file_under_specify(tmp_path):
with _exclusive_project_lock(tmp_path, LOCK_NAME, context="test"):
assert (tmp_path / ".specify" / LOCK_NAME).is_file()
Expand Down
Loading