From bbdf697a3c669bffe7c4bebce7f4a0ea18b5908b Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Wed, 5 Aug 2026 13:25:36 +0200 Subject: [PATCH] fix(bkp): stop rsync from keeping superseded files as ~ twins rsync -b turns a deletion into a rename, so a file the source dropped between two writes of the same generation survives as name~ beside the real one and is restored into live data. baudolo 3.4.1 fixes the copy that caused the elasticsearch restore failure; this is the sweep over the sibling call sites here. svc-bkp-remote-2-local is the live one: the rsync command is assembled once and re-executed up to twelve times against the same destination, which is created with exist_ok before the loop starts. A retry after a partial transfer is structurally the same second write as baudolo's hot/cold pair, only triggered by --timeout instead of a container stop. That path pulls other hosts' backups, and retries are its normal case rather than an exception. svc-bkp-local-2-device cannot fire today - it writes one pass into a directory named after the current second - but mkdir(exist_ok=True) makes a re-entry the same two-write case, so the flag goes rather than the argument for keeping it. The integration test mirrors the production command and follows. The lint is what makes this complete: it scans every tracked .py/.sh/.j2/.yml for a backup flag near an rsync token, and it found the integration test that the manual sweep had missed. It excludes exactly one file, its own, because the rule has to name the token it forbids; the sibling guard for || true avoids the same problem only by scanning .sh alone. Verified: make quality green across all four targets, the ssh-wrapper integration test passes with real rsync, and test-lint goes 307 -> 308 with the new guard collected. Co-Authored-By: Claude Opus 5 (1M context) --- roles/svc-bkp-local-2-device/files/script.py | 2 +- .../files/pull_specific_host.py | 2 +- .../test_ssh_wrapper_rsync_e2e.py | 2 +- .../filesystem/test_no_rsync_backup_flag.py | 143 ++++++++++++++++++ 4 files changed, 146 insertions(+), 3 deletions(-) create mode 100644 tests/lint/filesystem/test_no_rsync_backup_flag.py diff --git a/roles/svc-bkp-local-2-device/files/script.py b/roles/svc-bkp-local-2-device/files/script.py index 8b6b17bc7e..8f82112091 100755 --- a/roles/svc-bkp-local-2-device/files/script.py +++ b/roles/svc-bkp-local-2-device/files/script.py @@ -51,7 +51,7 @@ def main(): try: rsync_command = [ "rsync", - "-abP", + "-aP", "--numeric-ids", "--delete", "--delete-excluded", diff --git a/roles/svc-bkp-remote-2-local/files/pull_specific_host.py b/roles/svc-bkp-remote-2-local/files/pull_specific_host.py index eb3927ce06..3c57de188f 100755 --- a/roles/svc-bkp-remote-2-local/files/pull_specific_host.py +++ b/roles/svc-bkp-remote-2-local/files/pull_specific_host.py @@ -120,7 +120,7 @@ def pull_backups(hostname: str, backups_dir: str) -> None: Path(local_backup_destination_path).mkdir(parents=True, exist_ok=True) rsync_command = ( - f"rsync -ab --partial --info=stats2 " + f"rsync -a --partial --info=stats2 " f"--numeric-ids --delete --delete-excluded --timeout=300 " f'-e "ssh {SSH_OPTS}" ' f'--rsync-path="sudo rsync" ' diff --git a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py index 9787fe69b7..f7269a5a3c 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/test_ssh_wrapper_rsync_e2e.py @@ -108,7 +108,7 @@ class TestSshWrapperRsyncE2E(unittest.TestCase): result = subprocess.run( [ "rsync", - "-abP", + "-aP", "--numeric-ids", "--delete", "--delete-excluded", diff --git a/tests/lint/filesystem/test_no_rsync_backup_flag.py b/tests/lint/filesystem/test_no_rsync_backup_flag.py new file mode 100644 index 0000000000..a2b47e659f --- /dev/null +++ b/tests/lint/filesystem/test_no_rsync_backup_flag.py @@ -0,0 +1,143 @@ +"""Lint guard: rsync invocations MUST NOT carry ``-b`` / ``--backup``. + +Every backup path here writes a generation more than once: baudolo copies +each volume hot and again after stopping the container, and +``pull_specific_host.py`` retries the same command into the same +destination. ``--backup`` turns that second write into a rename, so a file +the source deleted or replaced survives as ``name~`` beside the real one and +is restored into live data. + +Lucene resolves its current commit by parsing *every* file starting with +``segments`` as a radix-36 generation, so one ``segments_3~`` is enough to +make a shard unopenable. ``--link-dest`` already provides the incrementals. + +Suppress on a per-line basis with a same-line ``# nocheck: rsync-backup -- +`` marker. +""" + +from __future__ import annotations + +import re +import subprocess +import unittest +from dataclasses import dataclass +from pathlib import Path + +from utils.cache.files import read_text + +from . import PROJECT_ROOT + +_SCANNED_SUFFIXES = (".py", ".sh", ".j2", ".yml", ".yaml") +_SELF_REL = ( + Path(__file__).resolve().relative_to(Path(PROJECT_ROOT).resolve()).as_posix() +) +_LONG_RE = re.compile(r"(? list[str]: + out = subprocess.check_output( + ["git", "-c", "safe.directory=*", "-C", str(PROJECT_ROOT), "ls-files"], + text=True, + ) + return [line for line in out.splitlines() if line] + + +def _offending_flag(line: str) -> str | None: + """Name the backup flag on a line, or None when it carries none. + + Args: + line: one source line already known to mention rsync. + """ + if _LONG_RE.search(line): + return "--backup" + for token in re.findall(r"(? list[Violation]: + rel = path.relative_to(PROJECT_ROOT).as_posix() + try: + text = read_text(str(path)) + except (OSError, UnicodeDecodeError) as exc: + return [Violation(rel, 0, str(exc))] + + violations: list[Violation] = [] + rsync_window = 0 + for idx, raw in enumerate(text.splitlines(), 1): + if _RSYNC_RE.search(raw): + rsync_window = 8 + elif rsync_window: + rsync_window -= 1 + else: + continue + if _NOCHECK_RE.search(raw): + continue + flag = _offending_flag(raw) + if flag: + violations.append( + Violation( + rel, + idx, + f"`{flag}` keeps a `name~` twin of every file a later pass " + "replaces or deletes; drop it and rely on --link-dest, or " + "suppress with `# nocheck: rsync-backup -- `", + ) + ) + return violations + + +def _scan_targets() -> list[Path]: + return [ + PROJECT_ROOT / rel + for rel in _git_ls_files() + if rel.endswith(_SCANNED_SUFFIXES) and rel != _SELF_REL + ] + + +class TestNoRsyncBackupFlag(unittest.TestCase): + def test_no_rsync_call_keeps_backup_twins(self) -> None: + targets = _scan_targets() + self.assertTrue(targets, "no files found to scan") + all_violations: list[Violation] = [] + for path in targets: + all_violations.extend(_scan_file(path)) + if all_violations: + grouped: dict[str, list[Violation]] = {} + for v in all_violations: + grouped.setdefault(v.file, []).append(v) + lines = [ + ( + f"rsync --backup in {len(all_violations)} place(s) across " + f"{len(grouped)} file(s):" + ), + "", + ( + "A backup generation is written more than once (hot pass " + "then cold pass, or a retry into the same destination). " + "`--backup` preserves the superseded file as `name~`, " + "which restores into live data and breaks any format that " + "enumerates its own directory." + ), + "", + "Offenders:", + ] + for f, vs in sorted(grouped.items()): + lines.append(f" {f}:") + lines.extend(f" line {v.line_no}: {v.detail}" for v in vs) + self.fail("\n".join(lines)) + + +if __name__ == "__main__": + unittest.main()