From e6fc0c7fb906a3efa2fd6969802adce7c273a42b Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Thu, 13 Aug 2026 16:10:10 +0200 Subject: [PATCH] fix(migrator): retry failed writes serially Pass-B writes (issue body rewrite + each comment) ran only at the caller's --concurrency, so a transient target 5xx either aborted the run or silently lost the write. A self-hosted Gitea throws bursts of 500s under concurrent writes, losing comments and leaving bodies with stale cross-refs. Failed writes are now deferred and replayed once serially (concurrency 1) after the concurrent wave -- serial load removes the backpressure causing the 500s, so nearly all recover. Writes still failing serially are logged and skipped; a genuinely-down target still aborts via CircuitOpenError. Adds two phase tests: persistent-fail (no abort) and transient (recover). --- CHANGELOG.md | 1 + src/codeberg_to_gitea_migrator/AGENTS.md | 2 +- src/codeberg_to_gitea_migrator/issues.py | 77 +++++++++++++++--- tests/test_phases.py | 99 ++++++++++++++++++++++++ 4 files changed, 167 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 740399e..f5c530b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ All notable changes to this project will be documented in this file. The format - **client:** add full jitter to the retry backoff and a larger, write-aware timeout (`httpx.Timeout(read=600, write=600)`) for bulk asset transfers so large binaries stop timing out mid-transfer and re-uploading from scratch. - **migrator:** log unparseable pull refs instead of dropping them silently. - **ci:** enable the uv download cache (`setup-python` `cache: uv`) so warm runs skip re-fetching deps; installs stay `--frozen`/hash-verified. +- **migrator:** defer-and-serially-retry Pass-B writes (issue body/title rewrites and each comment) that hit a transient target 5xx. Concurrent writes are what overstress a self-hosted Gitea into bursts of 500s, so a run either aborted or silently lost comments and left issue bodies with stale cross-refs. Failed writes are now deferred during the concurrent pass and replayed once serially (concurrency 1) afterwards — serial load removes the backpressure causing the 500s, so nearly all recover. Writes still failing serially are logged and skipped; a genuinely-down target still aborts via `CircuitOpenError`. ### refactor diff --git a/src/codeberg_to_gitea_migrator/AGENTS.md b/src/codeberg_to_gitea_migrator/AGENTS.md index f02b9f6..9b45cd6 100644 --- a/src/codeberg_to_gitea_migrator/AGENTS.md +++ b/src/codeberg_to_gitea_migrator/AGENTS.md @@ -28,7 +28,7 @@ Console script: `codeberg-to-gitea`. - `mirror.py` — the git-mirror *procedure*: drives a `GitRunner` (clone/fetch → capture `refs/pull//head` → prune forge-internal refs → `push --mirror` → recreate deleted-branch PR heads as `refs/heads/_pr/` → LFS fetch+push). Owns the workdir lifecycle (per-user `0700`); its value is the ordering invariants, which its tests lock. `DEFAULT_GIT_TIMEOUT`/`GitError` are re-exported here so `cli.py`/`migrate.py` import them unchanged. - `refs.py` — reference-namespace knowledge: `pr_head_branch` (the single source of truth for the `_pr/` deleted-branch PR-head branch, shared by the git-mirror and REST layers so they cannot diverge) plus `NumberMap` + `rewrite` (rewrites `#NNN` refs and source issue/PR URLs to the target's fresh number space — source numbers are sparse after deletions). Pure stdlib (`re` only). - `migration.py` — `Migration`: the bound context for one repo's transfer (source + target `ApiClient`, `owner`, `name`, `NumberMap`). Pure context — no I/O, no phase logic; two accessors only (`.path(suffix)` repo-scoped API path, `.rewrite(text)` delegating to the pure refs rewriter via the bound clients' web roots). The four phase functions take this handle instead of the old five loose params; it is also the phase layer's test surface (two mock-transport clients + a number map). -- `issues.py` — labels, milestones, issues + PRs + comments. Each phase is a free function taking the `Migration` handle (`migrate_labels`/`migrate_milestones` return old-id→new-id maps; `migrate_issues_and_prs` mutates `m.numbers`). Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. PR head falls back to `_pr/` (via `refs.pr_head_branch`, shared with the mirror) when the source branch is gone. Pass A (creation) is serial (ordered); labels/milestones and Pass B (ref rewrite + comments) overlap via `parallel`. Issues carry their milestone in the create body; PRs still PATCH it (pull-create has no milestone field). +- `issues.py` — labels, milestones, issues + PRs + comments. Each phase is a free function taking the `Migration` handle (`migrate_labels`/`migrate_milestones` return old-id→new-id maps; `migrate_issues_and_prs` mutates `m.numbers`). Two-pass: create in source-number order (build number map), then rewrite title/body refs + stream comments. Pass-B writes run at the caller's concurrency first; any that hit a transient `ApiError` are deferred and replayed serially (concurrency 1) — serial load removes the burst-of-500s backpressure a self-hosted target throws under concurrent writes — and only writes still failing serially are skipped (`CircuitOpenError` still aborts when the target is down). PR head falls back to `_pr/` (via `refs.pr_head_branch`, shared with the mirror) when the source branch is gone. Pass A (creation) is serial (ordered); labels/milestones and Pass B (ref rewrite + comments) overlap via `parallel`. Issues carry their milestone in the create body; PRs still PATCH it (pull-create has no milestone field). - `releases.py` — `migrate_releases` (takes the `Migration` handle): non-draft releases + asset re-upload. Assets stream through `raw_get_stream` (bounded memory) and upload concurrently within a release. Treats a 404 releases endpoint (feature disabled) as "none". - `migrate.py` — `migrate_repo` orchestrator: creates/validates the target repo, builds one `Migration` once both clients are open, drives the entity phases with it (threading the label/milestone maps between them), returns a report. - `cli.py` — `codeberg-to-gitea migrate` argparse entrypoint (`app()`). Tokens via `CODEBERG_TOKEN` / `GITEA_TOKEN` env or flags. `--repo owner/name` (or bare `name`). `--concurrency` (parallel independent writes, default 8), `--git-timeout` (per-op git timeout, default 1800s); catches `CircuitOpenError`. diff --git a/src/codeberg_to_gitea_migrator/issues.py b/src/codeberg_to_gitea_migrator/issues.py index c3c36ef..8e535c8 100644 --- a/src/codeberg_to_gitea_migrator/issues.py +++ b/src/codeberg_to_gitea_migrator/issues.py @@ -22,6 +22,13 @@ creation, are independent across items and overlap through Known fidelity limits (the public Gitea API stamps these server-side): original author (attributed to the migration token user), original timestamps, and assignees/reactions. + +Pass-B writes (the body rewrite and each comment) run at the caller's concurrency +first; any that hit a transient target ``ApiError`` are deferred and replayed +serially (concurrency 1) afterwards — serial load removes the concurrent-write +backpressure that causes bursts of 500s on a self-hosted target. Writes that +still fail serially are logged and skipped, so a flaky 5xx can't abort the repo +(a genuinely-down target still aborts via ``CircuitOpenError``). """ from __future__ import annotations @@ -203,19 +210,67 @@ def migrate_issues_and_prs( # Pass B: rewrite refs in title+body, then stream comments. Items are # independent of each other (the number map is already complete), so they - # overlap; each item's comments stay sequential to preserve their order. - def pass_b(pair: tuple[dict, int]) -> None: + # overlap at the caller's concurrency; each item's comments stay sequential + # to preserve their order. + # + # Two-tier: a write that hits a transient target error is *deferred*, not + # raised, then replayed serially (concurrency 1) once the concurrent wave is + # done. Concurrent writes are what overstress a self-hosted target and + # surface as bursts of 500s; serial replay recovers nearly all of them. + def pass_b(pair: tuple[dict, int]) -> list[tuple]: item, new_number = pair new_title = m.rewrite(item.get("title")) new_body = m.rewrite(item.get("body")) - m.tgt.patch( - m.path(f"/issues/{new_number}"), - body={"title": new_title, "body": new_body}, - ) - for comment in m.src.get_all(m.path(f"/issues/{item['number']}/comments")): - m.tgt.post( - m.path(f"/issues/{new_number}/comments"), - body={"body": m.rewrite(comment.get("body"))}, + deferred: list[tuple] = [] + try: + m.tgt.patch( + m.path(f"/issues/{new_number}"), + body={"title": new_title, "body": new_body}, ) + except ApiError as exc: + log.info("deferred body rewrite for #%s: %s", new_number, exc.status) + deferred.append(("rewrite", new_number, new_title, new_body)) + for comment in m.src.get_all(m.path(f"/issues/{item['number']}/comments")): + body = m.rewrite(comment.get("body")) + try: + m.tgt.post( + m.path(f"/issues/{new_number}/comments"), + body={"body": body}, + ) + except ApiError as exc: + log.info( + "deferred comment %s on #%s: %s", + comment.get("id"), + new_number, + exc.status, + ) + deferred.append(("comment", new_number, body)) + return deferred - parallel(created, pass_b, workers=concurrency) + deferred = [d for sub in parallel(created, pass_b, workers=concurrency) for d in sub] + + # Serial replay (concurrency 1) of the writes that failed under load. The + # backpressure that caused the 500s is gone; almost everything recovers. + for kind, new_number, *rest in deferred: + try: + if kind == "rewrite": + title, body = rest + m.tgt.patch( + m.path(f"/issues/{new_number}"), + body={"title": title, "body": body}, + ) + log.info("recovered body rewrite for #%s", new_number) + else: # "comment" + (body,) = rest + m.tgt.post( + m.path(f"/issues/{new_number}/comments"), + body={"body": body}, + ) + log.info("recovered comment on #%s", new_number) + except ApiError as exc: + log.warning( + "could not migrate %s for #%s after retry: %s", + kind, + new_number, + exc.status, + ) diff --git a/tests/test_phases.py b/tests/test_phases.py index d09b4d0..8783a79 100644 --- a/tests/test_phases.py +++ b/tests/test_phases.py @@ -347,6 +347,105 @@ def test_migrate_issues_and_prs_attaches_mapped_labels_and_pr_milestone() -> Non assert pr_ms_patches +def test_migrate_issues_and_prs_retries_failed_writes_serially_without_aborting() -> None: + # The target persistently 500s on the body-rewrite PATCH and on the "second" + # comment. Each is deferred in the concurrent pass, retried once serially, + # and — still failing — reported as a warning. The run completes; the other + # comments land; the issue is mapped. Nothing aborts on a per-write ApiError. + src = _src( + { + "/repos/o/r/issues": [{"number": 1, "title": "t", "body": "see #2", "state": "open"}], + "/repos/o/r/pulls": [], + "/repos/o/r/issues/1/comments": [ + {"id": 11, "body": "first"}, + {"id": 12, "body": "second"}, + {"id": 13, "body": "third"}, + ], + } + ) + recorded: list[dict] = [] + + def tgt_h(req: httpx.Request) -> httpx.Response: + method, path = req.method, _wire_path(req) + body = json.loads(req.read() or "null") + recorded.append({"method": method, "path": path, "body": body}) + if method == "POST" and path == "/repos/o/r/issues": + return httpx.Response(201, json={"number": 101}) + if method == "PATCH" and path == "/repos/o/r/issues/101": + return httpx.Response(500, json={"message": "persistent"}) + if method == "POST" and path == "/repos/o/r/issues/101/comments": + if isinstance(body, dict) and body.get("body") == "second": + return httpx.Response(500, json={"message": "persistent"}) + return httpx.Response(201, json={"id": 1}) + return httpx.Response(200, json={}) + + tgt = _client(tgt_h, base="https://git.babylondreams.de") + m = Migration(src, tgt, "o", "r") + + migrate_issues_and_prs(m, {}, {}, concurrency=1) # must not raise + + # "second" attempted twice (concurrent pass + serial retry), still lost; + # "first"/"third" landed once each. + comment_posts = _find(recorded, "POST", "/repos/o/r/issues/101/comments") + assert [c["body"]["body"] for c in comment_posts] == ["first", "second", "third", "second"] + # body rewrite attempted in both passes; persistent 500, never recovered + assert len(_find(recorded, "PATCH", "/repos/o/r/issues/101")) == 2 + assert m.numbers.get(1) == 101 + + +def test_migrate_issues_and_prs_recovers_deferred_writes_on_serial_replay() -> None: + # The target 500s only on the FIRST attempt of the body rewrite and of the + # "second" comment; the serial replay succeeds. Final state: the deferred + # writes are recovered (each attempted twice: fail then ok). + src = _src( + { + "/repos/o/r/issues": [{"number": 1, "title": "t", "body": "see #2", "state": "open"}], + "/repos/o/r/pulls": [], + "/repos/o/r/issues/1/comments": [ + {"id": 11, "body": "first"}, + {"id": 12, "body": "second"}, + ], + } + ) + recorded: list[dict] = [] + seen: dict[str, int] = {"patch": 0, "second": 0} + + def tgt_h(req: httpx.Request) -> httpx.Response: + method, path = req.method, _wire_path(req) + body = json.loads(req.read() or "null") + recorded.append({"method": method, "path": path, "body": body}) + if method == "POST" and path == "/repos/o/r/issues": + return httpx.Response(201, json={"number": 101}) + if method == "PATCH" and path == "/repos/o/r/issues/101": + seen["patch"] += 1 + if seen["patch"] == 1: + return httpx.Response(500, json={"message": "transient"}) + return httpx.Response(200, json={}) + if method == "POST" and path == "/repos/o/r/issues/101/comments": + if isinstance(body, dict) and body.get("body") == "second": + seen["second"] += 1 + if seen["second"] == 1: + return httpx.Response(500, json={"message": "transient"}) + return httpx.Response(201, json={"id": 1}) + return httpx.Response(200, json={}) + + tgt = _client(tgt_h, base="https://git.babylondreams.de") + m = Migration(src, tgt, "o", "r") + + migrate_issues_and_prs(m, {}, {}, concurrency=2) # must not raise + + # body rewrite recovered on the serial replay (attempted twice: fail then ok) + assert len(_find(recorded, "PATCH", "/repos/o/r/issues/101")) == 2 + # "second" recovered: posted twice (fail in pass 1, ok in pass 2) + second_posts = [ + r + for r in _find(recorded, "POST", "/repos/o/r/issues/101/comments") + if r["body"].get("body") == "second" + ] + assert len(second_posts) == 2 + assert m.numbers.get(1) == 101 + + # -- releases (+ assets) ------------------------------------------------ def test_migrate_releases_recreates_rewrites_body_and_reuploads_assets() -> None: src = _src(