Skip to content
Merged
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
7 changes: 7 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ _Notes on upcoming releases will be added here_

### Fixes

#### Retain recovery records under load after timeout or Ctrl-C (#616)

{ref}`cli-sync` and {ref}`cli-worktree-sync` now allow five seconds (up from
one second) for post-timeout and post-interrupt recovery inspection and skip
loading CLI subcommand modules inside worker inspection processes, preventing
busy hosts from dropping retained `dirty: preserve` recovery tokens.

#### Exclude archived GitLab subgroups and drop emptied workspace roots (#579)

{ref}`cli-import-gitlab` now excludes projects belonging to archived groups,
Expand Down
2 changes: 1 addition & 1 deletion docs/cli/sync.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ status `130`) so shell chains (`vcspull sync --all && next-cmd`) halt cleanly.

A stopped update can leave partially changed files; its `update_state` remains
`unknown` unless the worker returned a complete native result. Retained
preservation material is inspected with a one-second deadline and stays
preservation material is inspected with a five-second deadline and stays
available until released through libvcs.

### Debug logs and verbosity
Expand Down
20 changes: 12 additions & 8 deletions src/vcspull/_internal/sync_process.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@

from vcspull._internal.sync import sync_result_data

_INSPECTION_TIMEOUT_SECONDS = 5.0


@dataclasses.dataclass(slots=True)
class SyncOutcome:
Expand Down Expand Up @@ -417,7 +419,7 @@ def run_sync_process(
)
inspection = _exchange(
{"repo": dict(repo), "operation": "inspect"},
timeout=1.0,
timeout=_INSPECTION_TIMEOUT_SECONDS,
progress_callback=lambda *args: None,
is_human=False,
)
Expand Down Expand Up @@ -495,10 +497,6 @@ def emit(self, record: logging.LogRecord) -> None:
request = json.load(sys.stdin)
sync_failure_type: type[SyncFailedError] | None = None
try:
from vcspull.cli.sync import SyncFailedError, guess_vcs, update_repo

sync_failure_type = SyncFailedError

if request["operation"] == "worktree":
from vcspull._internal.worktree_sync import (
WorktreeAction,
Expand Down Expand Up @@ -536,11 +534,13 @@ def emit(self, record: logging.LogRecord) -> None:
return
if request["operation"] == "inspect":
from vcspull._internal.sync import create_sync_project
from vcspull.validator import match_vcs_url

repo = request["repo"]
vcs = repo.get("vcs") or guess_vcs(
repo.get("url", repo.get("pip_url", ""))
)
vcs = repo.get("vcs")
if vcs is None:
matches = match_vcs_url(repo.get("url", repo.get("pip_url", "")))
vcs = matches[0] if len(matches) == 1 else None
if vcs is None:
recoveries: tuple[SyncResult, ...] = ()
else:
Expand All @@ -553,6 +553,10 @@ def emit(self, record: logging.LogRecord) -> None:
}
)
return

from vcspull.cli.sync import SyncFailedError, update_repo

sync_failure_type = SyncFailedError
execution = update_repo(
request["repo"],
progress_callback=lambda output, timestamp: send(
Expand Down
60 changes: 54 additions & 6 deletions tests/cli/test_sync_sigint.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@
import json
import os
import pathlib
import selectors
import shlex
import signal
import socket
import subprocess
import sys
import time
import typing as t

import pytest
Expand All @@ -22,6 +24,43 @@
from vcspull.types import RepoEntryDict


_HOOK_CONNECT_TIMEOUT_SECONDS = 20.0
_HOOK_CHANNEL_TIMEOUT_SECONDS = 5.0
_CLI_EXIT_TIMEOUT_SECONDS = 15.0


def _accept_hook_connection(
server: socket.socket,
process: subprocess.Popen[bytes],
*,
timeout: float = _HOOK_CONNECT_TIMEOUT_SECONDS,
) -> socket.socket:
"""Accept the hook connection, failing immediately if the CLI exits early."""
deadline = time.monotonic() + timeout
with selectors.DefaultSelector() as selector:
selector.register(server, selectors.EVENT_READ)
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
msg = f"timed out after {timeout:.1f}s waiting for post-checkout hook"
raise TimeoutError(msg)
if selector.select(min(remaining, 0.05)):
connection, _ = server.accept()
connection.settimeout(_HOOK_CHANNEL_TIMEOUT_SECONDS)
return connection
if process.poll() is not None:
if selector.select(0):
connection, _ = server.accept()
connection.settimeout(_HOOK_CHANNEL_TIMEOUT_SECONDS)
return connection
output, error = process.communicate(timeout=1)
pytest.fail(
"CLI exited before post-checkout hook connected "
f"(returncode={process.returncode}, "
f"stdout={output!r}, stderr={error!r})"
)


@pytest.mark.skipif(os.name != "posix", reason="POSIX process-group supervision")
@pytest.mark.parametrize("mode", ["main", "parallel_main", "included", "worktree"])
def test_sync_interrupt_stops_worker(
Expand Down Expand Up @@ -67,7 +106,7 @@ def test_sync_interrupt_stops_worker(
if mode == "included":
arguments.append("--include-worktrees")
else:
arguments = ["worktree", "sync"]
arguments = ["worktree", "sync", "--timeout", "30"]
(checkout.path / "local.txt").write_text("retain this\n")
address = str(tmp_path / "s")
helper = tmp_path / "hook.py"
Expand All @@ -80,7 +119,7 @@ def test_sync_interrupt_stops_worker(
)
hook = git_repo.path / ".git" / "hooks" / "post-checkout"
hook.write_text(
f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(helper))}\n"
f"#!/bin/sh\nexec {shlex.quote(sys.executable)} -S {shlex.quote(str(helper))}\n"
)
hook.chmod(0o700)
config = tmp_path / "repos.json"
Expand All @@ -92,7 +131,6 @@ def test_sync_interrupt_stops_worker(
with socket.socket(socket.AF_UNIX) as server:
server.bind(address)
server.listen()
server.settimeout(3)
process = subprocess.Popen(
[
sys.executable,
Expand All @@ -112,18 +150,28 @@ def test_sync_interrupt_stops_worker(
start_new_session=True,
)
try:
connection, _ = server.accept()
connection = _accept_hook_connection(server, process)
with connection, connection.makefile("rb") as stream:
group = json.loads(stream.readline())["group"]
assert group != process.pid
process.send_signal(signal.SIGINT)
output, error = process.communicate(timeout=3)
output, error = process.communicate(timeout=_CLI_EXIT_TIMEOUT_SECONDS)
assert process.returncode == -signal.SIGINT, (output, error)
if mode == "worktree":
assert b"Interrupted by user." in error
assert connection.recv(1) == b""
events = [json.loads(line) for line in output.splitlines()]
event = next(item for item in events if item.get("status") == "interrupted")
target_reason = "sync" if mode in {"main", "parallel_main"} else "worktree"
event = next(
item
for item in events
if item.get("reason") == target_reason
and (
target_reason == "worktree"
or item.get("name") == git_repo.path.name
)
)
assert event["status"] == "interrupted"
assert event["update_state"] == "unknown"
if mode not in {"main", "parallel_main"}:
assert event["exists"] is None
Expand Down
58 changes: 57 additions & 1 deletion tests/cli/test_sync_watchdog.py
Original file line number Diff line number Diff line change
Expand Up @@ -515,7 +515,7 @@ def test_recovery_inspection_finds_svn_after_source_loss(svn_repo: SvnSync) -> N
"operation": "inspect",
"repo": {"vcs": "svn", "path": str(svn_repo.path), "url": svn_repo.url},
},
timeout=1,
timeout=5,
progress_callback=_noop_progress,
is_human=False,
)
Expand All @@ -526,6 +526,62 @@ def test_recovery_inspection_finds_svn_after_source_loss(svn_repo: SvnSync) -> N
assert not svn_repo.path.exists()


def test_watchdog_inspection_tolerates_slow_worker_startup(
monkeypatch: pytest.MonkeyPatch,
tmp_path: pathlib.Path,
) -> None:
"""Post-failure recovery inspection survives >1s interpreter startup under load."""
from libvcs import RecoveryToken, SyncResult

expected = SyncResult(recovery=RecoveryToken("retained", "git", "/retained/token"))
data = sync_process._result_data(expected)
clock = time.monotonic
offset = 0.0
launches = 0
frame = json.dumps({"event": "result", "ok": True, "recoveries": [data]})
inspect_source = (
"import json, os, sys\n"
"fd = int(sys.argv[1])\n"
"os.set_inheritable(fd, False)\n"
"json.load(sys.stdin)\n"
"with os.fdopen(fd, 'w') as protocol:\n"
f" protocol.write({frame!r} + '\\n')\n"
" protocol.flush()\n"
)

def launch_worker(control_fd: int) -> list[str]:
nonlocal launches, offset
launches += 1
if launches == 1:
return [sys.executable, "-S", "-c", "import os; os._exit(7)"]
# _exchange snapshots its deadline before calling _worker_command.
offset += 1.5
return [sys.executable, "-S", "-u", "-c", inspect_source, str(control_fd)]

monkeypatch.setattr(
sync_process,
"time",
types.SimpleNamespace(monotonic=lambda: clock() + offset),
)
monkeypatch.setattr(sync_process, "_worker_command", launch_worker)

repo: ConfigDict = {
"name": "slow-inspect",
"vcs": "git",
"path": tmp_path,
"url": "git+https://example.com/repo.git",
"workspace_root": str(tmp_path),
}
outcome = _sync_repo_with_watchdog(
repo,
progress_callback=_noop_progress,
timeout=5,
is_human=False,
)
assert outcome.status == "failed"
assert outcome.retained_recoveries == (expected,)


def test_rerun_recipe_emits_one_line_per_workspace(
capsys: pytest.CaptureFixture[str],
tmp_path: pathlib.Path,
Expand Down
2 changes: 1 addition & 1 deletion tests/test_sync.py
Original file line number Diff line number Diff line change
Expand Up @@ -899,7 +899,7 @@ def test_hg_configured_remote_reaches_native_sync(
entry = load_configs([config])[0]
if worker:
outcome = run_sync_process(
entry, progress_callback=lambda *args: None, timeout=5, is_human=False
entry, progress_callback=lambda *args: None, timeout=15, is_human=False
)
assert outcome.status == "synced", outcome.error
else:
Expand Down