3 Commits
Author SHA1 Message Date
AlexKucera 8b19ea502b chore(release): 1.0.0
CI / test (push) Canceled after 0s
Bump version to 1.0.0 across __init__.py, pyproject.toml, and
CITATION.cff (adds date-released); regenerate uv.lock. Promote the
accumulated Unreleased changelog entries to [1.0.0] - 2026-08-13.
2026-08-13 16:23:43 +02:00
AlexKucera e6fc0c7fb9 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).
2026-08-13 16:10:10 +02:00
AlexKucera 8449a2bd81 chore: ignore local .secrets file
Holds live forge API tokens; must never be tracked.
2026-08-13 16:10:10 +02:00
10 changed files with 177 additions and 17 deletions

No files matched your search

+2
View File
@@ -13,3 +13,5 @@ dist/
.pi-subagents/
.claude/
CLAUDE.md
.secrets
+3
View File
@@ -4,6 +4,8 @@ All notable changes to this project will be documented in this file. The format
## [Unreleased]
## [1.0.0] - 2026-08-13
### security
- **migrator:** keep forge API tokens out of error text, the command line, and on-disk git config. Git auth is delivered through a single `git.GitRunner` seam as a non-persisted per-op `http.<host>.extraHeader` (`Authorization: token <T>`), so the token never enters a remote URL or `.git/config`; failures raise a redacted `GitError` (known-secret + `oauth2:` fallback) and the CLI catches it cleanly. The default workdir stays per-user `0700`. Closes the 2026-08-11 audit's HIGH (token in error text) and MEDIUM (token in git config) at one structural root cause.
@@ -23,6 +25,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
+2 -1
View File
@@ -9,7 +9,8 @@ authors:
- given-names: Alexander
family-names: Kucera
email: a.kucera@babylondreams.de
version: 0.1.0
version: 1.0.0
date-released: 2026-08-13
license: GPL-3.0-or-later
repository-code: "https://git.babylondreams.de/AlexKucera/codeberg-to-gitea-migrator.git"
keywords:
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "codeberg-to-gitea-migrator"
version = "0.1.0"
version = "1.0.0"
description = "Migrate repositories (code, issues & PRs, releases & assets, labels & milestones) from Codeberg to a self-hosted Gitea instance."
readme = "README.md"
requires-python = ">=3.11"
+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`.
+1 -1
View File
@@ -1,3 +1,3 @@
"""codeberg-to-gitea-migrator: Codeberg (Forgejo) -> self-hosted Gitea migrator."""
__version__ = "0.1.0"
__version__ = "1.0.0"
+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,
)
+99
View File
@@ -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(
+1 -1
View File
@@ -4,4 +4,4 @@
def test_import():
import codeberg_to_gitea_migrator
assert codeberg_to_gitea_migrator.__version__ == "0.1.0"
assert codeberg_to_gitea_migrator.__version__ == "1.0.0"
Generated
+1 -1
View File
@@ -26,7 +26,7 @@ wheels = [
[[package]]
name = "codeberg-to-gitea-migrator"
version = "0.1.0"
version = "1.0.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },