From e94d5ba8c3d7fc7272f2ba6acc98f2c3ff5c29cb Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 20:47:22 +0000 Subject: [PATCH] fix(backups): openclaw-backup dead links, Turso dump retries, per-db Turso retention openclaw-backup: the state dir holds absolute links into the excluded tmp/ tree (acpx plugin vendor dirs). Once tmp/ was cleaned they dangled, the manifest step opened one and crashed, the archive was built without manifest.json, and verification failed every night from 2026-11-15. The manifest now records symlinks by target and the verifier checks them as links; a manifest or archive-creation failure now fails the run on the spot. export-turso: on 2026-11-17 the server cut the /dump stream (curl 18) on 4 of 42 databases, twice each. Dumps now get 3 retries 30 s apart (TURSO_DUMP_RETRY_DELAY_SECONDS) and databases that still fail get a second pass at the end of the run after a pause (TURSO_DUMP_RETRY_PASS_DELAY_SECONDS, default 60). cold-store prune-backups: the turso folder holds one export per database per night, but retention read it as one series and kept only the newest file per day, so it trashed 37 of the 38 fresh exports on 2026-11-17. Retention for turso now runs per source database. Co-Authored-By: Claude Opus 5.5 --- nixos/home/openclaw-backup.sh | 32 ++++++-- nixos/home/openclaw-backup.test.sh | 45 +++++++++++ pkgs/cold-store-reaper/cold_store.py | 43 +++++++++- .../cold-store-reaper/scripts/export-turso.sh | 78 ++++++++++++++++--- .../tests/test_cold_store.py | 58 ++++++++++++++ .../tests/test_export_turso.py | 49 +++++++++++- 6 files changed, 284 insertions(+), 21 deletions(-) diff --git a/nixos/home/openclaw-backup.sh b/nixos/home/openclaw-backup.sh index 1b75ed947c..ec3d2ef74d 100755 --- a/nixos/home/openclaw-backup.sh +++ b/nixos/home/openclaw-backup.sh @@ -157,16 +157,30 @@ journalctl --user -u "openclaw-gateway.service" --since "$SINCE_STR" --no-pager echo "(journal unavailable for openclaw-gateway)" >"$STAGE/journals/openclaw-gateway.log" # --- manifest --- -python3 - "$STAGE" "$DATE" "$CREATED_AT" <<'PYEOF' +# Symlinks are recorded as links (path + target), never opened: the +# state dir holds absolute links into the excluded tmp/ tree (plugin +# build vendor dirs under acpx/), and once tmp/ is cleaned those links +# dangle. Opening one crashed this step with FileNotFoundError, the +# archive was then built without manifest.json, and every run from +# 2026-11-15 failed verification. tar archives the links as links, so +# the verifier below checks them by target, not by content. The +# `|| fail` makes any other crash here fail the run on the spot +# instead of surfacing later as a missing manifest. +python3 - "$STAGE" "$DATE" "$CREATED_AT" <<'PYEOF' || fail "manifest generation failed" import hashlib, json, os, sys stage, date, created = sys.argv[1], sys.argv[2], sys.argv[3] files = [] -for root, _dirs, names in os.walk(stage): - for n in sorted(names): +for root, dirs, names in os.walk(stage): + # os.walk lists a symlink to a directory under dirs and does not + # descend into it; record it as a link like any other. + for n in sorted(names) + sorted(d for d in dirs if os.path.islink(os.path.join(root, d))): p = os.path.join(root, n) rel = os.path.relpath(p, stage) if rel == "manifest.json": continue + if os.path.islink(p): + files.append({"path": rel, "symlink": os.readlink(p)}) + continue h = hashlib.sha256() with open(p, "rb") as fh: for chunk in iter(lambda: fh.read(1 << 20), b""): @@ -182,8 +196,8 @@ PYEOF # --- tarball (atomic replace) + verify against manifest --- TMPARC="$OUTDIR/.openclaw-$DATE.tar.zst.tmp" -tar -I zstd -cf "$TMPARC" -C "$STAGE" . -mv "$TMPARC" "$ARCHIVE" +tar -I zstd -cf "$TMPARC" -C "$STAGE" . || fail "archive creation failed for $TMPARC" +mv "$TMPARC" "$ARCHIVE" || fail "could not move $TMPARC into place" VDIR="$(mktemp -d)" tar -I zstd -xf "$ARCHIVE" -C "$VDIR" if ! ( @@ -196,7 +210,13 @@ if required not in {f["path"] for f in m["files"]} or not os.path.isfile(require print("MISSING REQUIRED", required); bad += 1 for f in m["files"]: p = f["path"] - if not os.path.isfile(p): + if "symlink" in f: + if not os.path.islink(p): + print("MISSING LINK", p); bad += 1 + elif os.readlink(p) != f["symlink"]: + print("LINK MISMATCH", p); bad += 1 + continue + if os.path.islink(p) or not os.path.isfile(p): print("MISSING", p); bad += 1; continue if hashlib.sha256(open(p, "rb").read()).hexdigest() != f["sha256"] \ or os.path.getsize(p) != f["size"]: diff --git a/nixos/home/openclaw-backup.test.sh b/nixos/home/openclaw-backup.test.sh index f023d804ca..d487123233 100755 --- a/nixos/home/openclaw-backup.test.sh +++ b/nixos/home/openclaw-backup.test.sh @@ -26,6 +26,8 @@ # * happy path — exit 0, verified local archive containing the # staged files (sqlite snapshot included, scratch tree excluded), # both offsite copies in the stub store, marker advances. +# * dangling links — absolute links into the excluded tmp/ tree +# are archived and verified as links; the run succeeds. # * invalid DATE — a nonexistent calendar date and a malformed date # are both rejected non-zero with the value named, nothing # uploaded, marker unchanged. @@ -328,6 +330,49 @@ else fail "happy: marker did not advance on a fully successful run — was $PRESET, now $MARKER_AFTER" fi +# --- dangling symlinks into the excluded tmp/ tree (2026-11-17) ---------------- +# Plugin build vendor dirs keep absolute links into ~/.openclaw/tmp/. +# Once tmp/ is cleaned the links dangle; the manifest step used to open +# them, crash, and leave an archive with no manifest.json (VERIFY +# FAILED every night from 2026-11-15). Links must be archived as links, +# recorded in the manifest by target, and verified, and the run must +# succeed. +setup_home dangling-link +mkdir -p "$RUN_HOME/.openclaw/acpx/vendor/bin" "$RUN_HOME/.openclaw/acpx/libdir" +ln -s "$RUN_HOME/.openclaw/tmp/plugin-captures/gone/bin/codex" \ + "$RUN_HOME/.openclaw/acpx/vendor/bin/codex" +ln -s "$RUN_HOME/.openclaw/tmp/plugin-captures/gone/lib" \ + "$RUN_HOME/.openclaw/acpx/vendor/lib" +ln -s ../libdir "$RUN_HOME/.openclaw/acpx/vendor/live-dir-link" +ln -s ../../session.log "$RUN_HOME/.openclaw/acpx/vendor/live-file-link" +run_backup dangling-link +DL_ARCHIVE="$RUN_HOME/backups/openclaw/$RUN_DATE/openclaw-$RUN_DATE.tar.zst" +if [[ $RC -eq 0 ]] && grep -q "OK openclaw $RUN_DATE backed up to local + R2 + Drive" "$TMP_ROOT/dangling-link.log"; then + ok "dangling-link: run with dangling links into tmp/ succeeded" +else + fail "dangling-link: expected exit 0 and the full OK line, got rc=$RC; log: $(cat "$TMP_ROOT/dangling-link.log")" +fi +if [[ -f $DL_ARCHIVE ]] && + "$REAL_TAR" -I zstd -xOf "$DL_ARCHIVE" ./manifest.json 2>/dev/null | python3 -c ' +import json, sys +m = {f["path"]: f for f in json.load(sys.stdin)["files"]} +want = { + "acpx/vendor/bin/codex": None, + "acpx/vendor/lib": None, + "acpx/vendor/live-dir-link": "../libdir", + "acpx/vendor/live-file-link": "../../session.log", +} +for path, target in want.items(): + f = m.get(path) + assert f is not None and "symlink" in f and "sha256" not in f, path + assert target is None or f["symlink"] == target, path +assert "session.log" in m and "sha256" in m["session.log"] +'; then + ok "dangling-link: manifest records each link by target, files by hash" +else + fail "dangling-link: manifest missing or links not recorded as links; log: $(cat "$TMP_ROOT/dangling-link.log")" +fi + # --- invalid DATE is rejected ------------------------------------------------ setup_home bad-date DATE_ARG="2026-02-30" diff --git a/pkgs/cold-store-reaper/cold_store.py b/pkgs/cold-store-reaper/cold_store.py index 6398ba0e57..1b34dde060 100755 --- a/pkgs/cold-store-reaper/cold_store.py +++ b/pkgs/cold-store-reaper/cold_store.py @@ -64,6 +64,14 @@ # DB-backup class (DESIGN.md section 5): nightly dumps live unbundled under # db-backups//, one subfolder per database. BACKUP_DBS = ("supabase", "turso", "d1") +# Backup families whose folder holds one file per source database per +# run, named --.: retention runs per +# source database (keyed by the name after the stamp), not across the +# family. export-turso.sh files every Turso database into db-backups/ +# turso/ each night; read as one series, "newest per day" kept one +# database's export per night and trashed the rest (2026-11-17: keep +# 20, prune 37 of that night's 38 fresh exports). +PER_SOURCE_RETENTION_DBS = frozenset({"turso"}) # Manifest sync target (DESIGN.md section 3): the hosted copy of this schema lives # in Cloudflare D1. The token comes from the environment only; the account @@ -1504,6 +1512,36 @@ def mark(kept, reason): prune.append({**f, "reasons": ["excess"]}) return keep, prune, unparseable + @classmethod + def _per_source_retention_plan( + cls, db_name: str, files: list[dict] + ) -> tuple[list[dict], list[dict], list[dict]]: + """_retention_plan applied separately to each source database in + a family folder (PER_SOURCE_RETENTION_DBS). The source is the + part of -- after the stamp; every + source keeps its own 30 daily / 12 weekly / 12 monthly set. + Unparseable names are never pruned, only reported.""" + groups: dict[str, list[dict]] = {} + unparseable = [] + for f in files: + m = re.fullmatch(re.escape(db_name) + r"-\d{8}T\d{6}Z-(.+)", f["name"]) + if f["stamp"] is None or not m: + unparseable.append(f) + continue + groups.setdefault(m.group(1), []).append(f) + keep, prune = [], [] + for group in groups.values(): + k, p, _u = cls._retention_plan(group) + keep.extend(k) + prune.extend(p) + + def order(f): + return (f["stamp"], f["name"]) + + keep.sort(key=order, reverse=True) + prune.sort(key=order, reverse=True) + return keep, prune, unparseable + def prune_backups( self, db_name: str | None = None, apply: bool = False ) -> list[dict]: @@ -1526,7 +1564,10 @@ def prune_backups( rows = self.list_backups(db) for r in rows: r["stamp"] = self._parse_backup_stamp(db, r["name"]) - keep, prune, unparseable = self._retention_plan(rows) + if db in PER_SOURCE_RETENTION_DBS: + keep, prune, unparseable = self._per_source_retention_plan(db, rows) + else: + keep, prune, unparseable = self._retention_plan(rows) plans.append( { "db": db, diff --git a/pkgs/cold-store-reaper/scripts/export-turso.sh b/pkgs/cold-store-reaper/scripts/export-turso.sh index 9dcbfc9d3b..e4a5878c74 100755 --- a/pkgs/cold-store-reaper/scripts/export-turso.sh +++ b/pkgs/cold-store-reaper/scripts/export-turso.sh @@ -43,6 +43,20 @@ # 300 s cap; the download also gets one # whole-request retry on transport # failure. Small databases are unaffected. +# TURSO_DUMP_RETRY_DELAY_SECONDS +# optional; curl --retry-delay between the +# 3 retries of one /dump download (default +# 30; must be positive). +# TURSO_DUMP_RETRY_PASS_DELAY_SECONDS +# optional; how long to wait before the +# second pass over databases that failed +# the first pass (default 60; 0 = no +# wait). On 2026-11-17 the +# server closed the stream mid-transfer +# (curl 18) on 4 of 42 databases twice in +# a row while others of the same size +# filed fine, so a later second pass is +# the cheap way past a transient window. # TURSO_API_BASE optional; Platform API base URL # (default https://api.turso.tech). # Test seam, mirrors COLD_STORE_S3_BASE. @@ -91,6 +105,29 @@ case "${DUMP_MAX_TIME}" in exit 1 ;; esac +RETRY_DELAY="${TURSO_DUMP_RETRY_DELAY_SECONDS:-30}" +case "${RETRY_DELAY}" in +*[1-9]*) + [[ ${RETRY_DELAY} != *[!0-9]* ]] || { + echo "turso export: ERROR: TURSO_DUMP_RETRY_DELAY_SECONDS must be a positive integer (got '${RETRY_DELAY}')" >&2 + exit 1 + } + ;; +*) + # Empty, non-numeric or all zeros: curl --retry-delay 0 silently + # switches to its own backoff, so zero would not mean "no delay". + echo "turso export: ERROR: TURSO_DUMP_RETRY_DELAY_SECONDS must be a positive integer (got '${RETRY_DELAY}')" >&2 + exit 1 + ;; +esac +RETRY_PASS_DELAY="${TURSO_DUMP_RETRY_PASS_DELAY_SECONDS:-60}" +case "${RETRY_PASS_DELAY}" in +'' | *[!0-9]*) + echo "turso export: ERROR: TURSO_DUMP_RETRY_PASS_DELAY_SECONDS must be a non-negative integer (got '${RETRY_PASS_DELAY}')" >&2 + exit 1 + ;; +*) ;; +esac API_BASE="${TURSO_API_BASE:-https://api.turso.tech}" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" COLD_STORE="${COLD_STORE_BIN:-${SCRIPT_DIR}/../cold-store}" @@ -199,7 +236,7 @@ PY dump_url="https://${hostname}/dump" fi if ! curl_auth "${jwt}" -fsS --compressed --max-time "${DUMP_MAX_TIME}" \ - --retry 1 --retry-all-errors \ + --retry 3 --retry-delay "${RETRY_DELAY}" --retry-all-errors \ "${dump_url}" -o "${dump_sql}"; then echo "turso export: ERROR: ${name}: dump download failed (${dump_url})" >&2 return 1 @@ -295,17 +332,34 @@ export_one() { return "${rc}" } -FAILURES=0 -for row in "${DB_ROWS[@]}"; do - name="${row%%$'\t'*}" - hostname="${row##*$'\t'}" - # shellcheck disable=SC2310 # by design: export_one guards every - # stage itself and returns 1, so one database's failure is counted - # here instead of aborting the run via set -e. - if ! export_one "${name}" "${hostname}"; then - FAILURES=$((FAILURES + 1)) - fi -done +# One pass over a list of "NameHostname" rows; the rows that +# failed are left in PASS_FAILED for the caller. +run_pass() { + PASS_FAILED=() + local row name hostname + for row in "$@"; do + name="${row%%$'\t'*}" + hostname="${row##*$'\t'}" + # shellcheck disable=SC2310 # by design: export_one guards every + # stage itself and returns 1, so one database's failure is + # recorded here instead of aborting the run via set -e. + if ! export_one "${name}" "${hostname}"; then + PASS_FAILED+=("${row}") + fi + done +} + +run_pass "${DB_ROWS[@]}" +# Second pass: a database whose download was cut off is tried once +# more at the end of the run, after a pause, rather than failing the +# whole step on one transient window (2026-11-17: 4 of 42 failed +# inside a few minutes, all with curl 18). +if [[ ${#PASS_FAILED[@]} -gt 0 ]]; then + echo "turso export: retrying ${#PASS_FAILED[@]} failed database(s) after ${RETRY_PASS_DELAY}s" + sleep "${RETRY_PASS_DELAY}" + run_pass "${PASS_FAILED[@]}" +fi +FAILURES=${#PASS_FAILED[@]} if [[ ${FAILURES} -gt 0 ]]; then echo "turso export: ${FAILURES} of ${#DB_ROWS[@]} database(s) FAILED" >&2 diff --git a/pkgs/cold-store-reaper/tests/test_cold_store.py b/pkgs/cold-store-reaper/tests/test_cold_store.py index ad69fdfc45..133a58f54e 100644 --- a/pkgs/cold-store-reaper/tests/test_cold_store.py +++ b/pkgs/cold-store-reaper/tests/test_cold_store.py @@ -1888,6 +1888,60 @@ def test_prune_long_history_oldest_pruned(self): # the union can never exceed 30 daily + 12 weekly + 12 monthly self.assertLessEqual(len(keep), 30 + 12 + 12) + def _seed_turso_nights(self, nights, databases, end=date(2026, 3, 31)): + folder = self.store.ensure_folders()["db-backups/turso"] + names = [] + for i in range(nights): + d = end - timedelta(days=i) + for j, db in enumerate(databases): + # one export per database per night, minutes apart + name = f"turso-{d:%Y%m%d}T09{j:02d}00Z-{db}.db.gz" + self.seed_drive_file(name, folder, data=b"db") + names.append(name) + return folder, names + + def test_turso_retention_is_per_database_not_per_family(self): + # 2026-11-17: export-turso files every Turso database each + # night; read as one series, "newest per day" kept one export + # per night and trashed the rest. Each database must keep its + # own newest-per-day, so a few nights of exports prune nothing. + databases = ["atlas", "atlas-ask-ledger", "fleet-queue", "voice-line-ledger"] + _folder, names = self._seed_turso_nights(3, databases) + plan = self.store.prune_backups("turso")[0] + self.assertEqual({f["name"] for f in plan["keep"]}, set(names)) + self.assertEqual(plan["prune"], []) + self.assertEqual(plan["unparseable"], []) + + def test_turso_retention_prunes_within_each_database(self): + databases = ["atlas", "fleet-queue"] + folder, _names = self._seed_turso_nights(1, databases) + # an earlier same-day export of atlas is the only excess file + dupe = "turso-20260331T080000Z-atlas.db.gz" + self.seed_drive_file(dupe, folder, data=b"db") + self.seed_drive_file("turso-notes.txt", folder, data=b"?") + plan = self.store.prune_backups("turso", apply=True)[0] + self.assertEqual([f["name"] for f in plan["prune"]], [dupe]) + self.assertEqual( + {f["name"] for f in plan["keep"]}, + { + "turso-20260331T090000Z-atlas.db.gz", + "turso-20260331T090100Z-fleet-queue.db.gz", + }, + ) + self.assertEqual({f["name"] for f in plan["unparseable"]}, {"turso-notes.txt"}) + self.assertEqual(len(self.fake.trashed_calls), 1) + + def test_turso_long_history_is_bounded_per_database(self): + databases = ["atlas", "fleet-queue"] + _folder, _names = self._seed_turso_nights(60, databases) + plan = self.store.prune_backups("turso")[0] + for db in databases: + kept = [f for f in plan["keep"] if f["name"].endswith(f"-{db}.db.gz")] + # 30 daily + the older weekly/monthly keepers, per database + self.assertGreaterEqual(len(kept), 30) + self.assertLessEqual(len(kept), 30 + 12 + 12) + self.assertEqual(len(plan["keep"]) + len(plan["prune"]), 120) + def test_prune_all_dbs_and_unknown_db(self): plans = self.store.prune_backups() self.assertEqual([p["db"] for p in plans], list(cold_store.BACKUP_DBS)) @@ -3320,6 +3374,10 @@ def run_export(self, with_token=True, extra_env=None): "TURSO_API_BASE": self.base, "TURSO_DUMP_BASE": self.base, "COLD_STORE_BIN": str(self.stub), + # keep failing-dump scenarios fast: 1 s between curl + # retries, no pause before the second pass + "TURSO_DUMP_RETRY_DELAY_SECONDS": "1", + "TURSO_DUMP_RETRY_PASS_DELAY_SECONDS": "0", "NO_PROXY": "127.0.0.1,localhost", "no_proxy": "127.0.0.1,localhost", } diff --git a/pkgs/cold-store-reaper/tests/test_export_turso.py b/pkgs/cold-store-reaper/tests/test_export_turso.py index 6cfbce9442..ae5a4c9d61 100644 --- a/pkgs/cold-store-reaper/tests/test_export_turso.py +++ b/pkgs/cold-store-reaper/tests/test_export_turso.py @@ -43,6 +43,18 @@ case "${a}" in http*) url="${a}" ;; esac prev="${a}" done +if [[ "${url}" == */dump ]]; then + # STUB_DUMP_FAIL_FIRST=N: the first N dump downloads fail the way + # the 2026-11-17 run did (server closes the stream mid-transfer). + d=0 + [[ -f "${cap}/dump-count" ]] && d="$(cat "${cap}/dump-count")" + d=$((d + 1)) + echo "${d}" > "${cap}/dump-count" + if [[ "${d}" -le "${STUB_DUMP_FAIL_FIRST:-0}" ]]; then + echo "curl: (18) transfer closed with outstanding read data remaining" >&2 + exit 18 + fi +fi body="" case "${url}" in */auth/tokens) body='{"jwt":"__JWT__"}' ;; @@ -89,6 +101,7 @@ def setUp(self): "TURSO_API_BASE": "http://api.test", "TURSO_DUMP_BASE": "http://dump.test", "COLD_STORE_BIN": str(cold), + "TURSO_DUMP_RETRY_PASS_DELAY_SECONDS": "0", } def tearDown(self): @@ -140,14 +153,46 @@ def dump_argv_lines(self): return lines self.fail("no dump invocation recorded by the stub curl") - def test_dump_uses_default_max_time_and_one_retry(self): + def test_dump_uses_default_max_time_and_three_spaced_retries(self): result = self.run_script() self.assertEqual(result.returncode, 0, result.stderr) lines = self.dump_argv_lines() self.assertEqual(lines[lines.index("--max-time") + 1], "1800") - self.assertEqual(lines[lines.index("--retry") + 1], "1") + self.assertEqual(lines[lines.index("--retry") + 1], "3") + self.assertEqual(lines[lines.index("--retry-delay") + 1], "30") self.assertIn("--retry-all-errors", lines) + def dump_calls(self): + f = self.capture / "dump-count" + return int(f.read_text()) if f.exists() else 0 + + def test_failed_dump_is_retried_in_a_second_pass_and_filed(self): + # 2026-11-17: curl 18 on 4 of 42 databases; a second pass at the + # end of the run must pick them up instead of failing the step. + env = {**self.env, "STUB_DUMP_FAIL_FIRST": "1"} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("dump download failed", result.stderr) + self.assertIn("retrying 1 failed database(s) after 0s", result.stdout) + self.assertIn("all 1 database(s) filed", result.stdout) + self.assertEqual(self.dump_calls(), 2) + self.assertIn("put-backup", (self.capture / "cold-store.log").read_text()) + + def test_database_failing_both_passes_fails_the_run(self): + env = {**self.env, "STUB_DUMP_FAIL_FIRST": "99"} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("1 of 1 database(s) FAILED", result.stderr) + self.assertEqual(self.dump_calls(), 2) + self.assertFalse((self.capture / "cold-store.log").exists()) + + def test_retry_pass_delay_must_be_an_integer(self): + env = {**self.env, "TURSO_DUMP_RETRY_PASS_DELAY_SECONDS": "soon"} + result = self.run_script(env=env) + self.assertEqual(result.returncode, 1, result.stderr) + self.assertIn("must be a non-negative integer", result.stderr) + self.assertEqual(list(self.capture.glob("argv-*.log")), []) + def test_dump_requests_compression(self): # --compressed keeps GB-class dumps under the sandbox proxy's # mid-stream cut: the wire size shrinks several-fold.