fix(migrator): retry failed writes serially
CI / test (push) Canceled after 0s

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).
This commit is contained in:
AlexKucera committed 2026-08-13 16:10:10 +02:00
1 parent 8449a2bd81
commit e6fc0c7fb9
4 files changed
+167 -12

No files matched your search

+1 -1
View File
@@ -28,7 +28,7 @@ Console script: `codeberg-to-gitea`.
- `mirror.py` — the git-mirror *procedure*: drives a `GitRunner` (clone/fetch → capture `refs/pull/<n>/head` → prune forge-internal refs → `push --mirror` → recreate deleted-branch PR heads as `refs/heads/_pr/<n>` → 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/<n>` 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/<n>` (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/<n>` (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`.
+66 -11
View File
@@ -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,
)