Files
codeberg-to-gitea-migrator/audit/2026-08-11/optimization-report.md
T
AlexKucera 137734673d
CI / test (push) Canceled after 0s
perf(migrator): parallelize and harden migration
The migrator was fully synchronous — every HTTP round-trip and git
op serialized over one blocking client, and a stalled git push could
hang it forever. Overlap the independent phases and bound the slow /
memory-heavy paths.

- clients: ApiClient is now thread-safe (per-thread httpx.Client) so
  labels, milestones, Pass-B comments, and release assets overlap via
  parallel(); --concurrency sizes it (default 8). Pass A issue/PR
  creation stays serial — entities are created in source-number order
  so the number map resolves forward cross-references.
- releases: stream assets through a spooled temp file instead of
  buffering each whole into memory; upload them concurrently.
- reliability: per-op --git-timeout (was unbounded hangs), a circuit
  breaker that aborts on a degraded target, jittered retry backoff,
  and a bulk timeout for large asset transfers.
- round-trips: set an issue's milestone in the create body; batch the
  deleted-branch PR-head git push and refs/pull/* pruning.
- fix: raw_get_stream 4xx/5xx raised AttributeError (resp.read().text
  on bytes) instead of ApiError — now decodes. Wrap mirror git ops in
  try/finally so tokenized remote URLs are scrubbed even on timeout.
- refactor: drop the typer dependency — the CLI is now stdlib argparse
  (same subcommands, flags, and env vars); remove dead code surfaced by
  a whole-repo audit (has_lfs, name_map, unused owner_repo param,
  stored-but-unread _base_url).
- ci: enable the uv download cache.

Tests cover parallel ordering, the circuit breaker, and the streamed
4xx path. CHANGELOG updated; the runtime dependency is now just httpx.
2026-08-11 13:36:11 +02:00

49 KiB
Raw Blame History

Code Optimization Audit Report

Project: codeberg-to-gitea-migrator Date: 2026-08-11 Auditor: Claude — code-optimizer skill Framework: 13-domain performance audit (parallel agents) Scope: src/codeberg_to_gitea_migrator/ (8 modules: cli.py, clients.py, issues.py, migrate.py, mirror.py, refs.py, releases.py, __init__.py), pyproject.toml, .gitea/workflows/ci.yml, tests/. Technology Stack: Python 3.11+ CLI migrator — httpx>=0.27 (sync httpx.Client), typer>=0.12. No database, no frontend UI, no Docker.


Executive Summary

The migrator is a small, well-structured codebase that is correct and clean on the dimensions Python projects usually fail (dependencies, data structures, algorithmic complexity, logging, regex safety). The performance posture is dominated by one architectural fact: the entire HTTP layer is synchronous. A repository migration is overwhelmingly I/O-bound — labels, milestones, issues, PRs, comments, releases, and binary assets are each their own round-trip, and every one of them is serialized over a single blocking httpx.Client with zero async/await/asyncio anywhere in the codebase. On a tracker with hundreds of issues × dozens of comments plus binary releases, wall-time equals the raw sum of thousands of sequential network waits.

Three concrete amplifiers stack on top of that: release assets are downloaded whole into memory then re-uploaded one at a time (memory spike + serial transfer), the comment-upload loop is a nested sequential POST (the single hottest serialization), and every milestone is set via a redundant follow-up PATCH instead of in the create body. A separate reliability gap — git subprocess calls have no timeout — can hang an unattended cutover indefinitely.

None of this is a bug; the data structures, retry logic (exponential backoff), connection reuse (one pooled client), and logging (lazy %s everywhere) are all done right. The wins are architectural (async + streaming + bounded concurrency) and a handful of surgical fixes.

Overall Risk Score: 94 (Critical Risk)

Severity Count
Critical 0
High 6
Medium 9
Low 8
Info 3
Total 26

Top 3 highest-impact fixes

  1. Move the HTTP client to httpx.AsyncClient and overlap independent writes with bounded concurrency — the dominant lever; migration wall-time moves from ≈ Σ(round-trips) toward ≈ max(batch) within each phase. Commonly 5–10× faster on issue/comment-heavy repos. (clients.py, issues.py, migrate.py)
  2. Stream release assets and upload them concurrently — raw_get buffers each binary into RAM; streaming bounds peak memory to a fixed buffer (~1 MiB vs. hundreds of MB) and bounded gather removes the serial download→upload wait. (clients.py:98-101, releases.py:57-63)
  3. Add a timeout to git subprocess calls — clone --mirror / fetch / push --mirror currently block forever on a stalled TCP connection. Converts an indefinite production hang into a bounded, diagnosable GitError. (mirror.py:70-73)

Findings

Database & Queries

The project has no DB/ORM layer — it is a pure REST-API migrator. The Database-domain analogs are the redundant-round-trip and N+1 patterns in the per-item migration loops.

Medium Milestone set via redundant follow-up PATCH instead of in the create body

  • File: src/codeberg_to_gitea_migrator/issues.py
  • Line(s): 150-178
  • Pattern: Redundant round-trip (ORM .create() then .update() analog) — two requests per item where one suffices
  • Current code:
    created = tgt.post(
        _path(owner, repo, "/issues"),
        body={"title": item["title"], "body": item.get("body") or ""},
    )
    ...
    new_number = created["number"]
    ms = item.get("milestone")
    if ms and ms.get("id") in milestone_map:
        tgt.patch(
            _path(owner, repo, f"/issues/{new_number}"),
            body={"milestone": milestone_map[ms["id"]]},
        )
    
  • Why it's slow: Gitea/Forgejo CreateIssueOption accepts milestone directly in the create body. Setting it via a separate PATCH doubles the round-trips for every milestoned item, each a full WAN hop over the blocking client. Cost scales linearly with the count of milestoned items.
  • Optimal fix:
    body = {"title": item["title"], "body": item.get("body") or ""}
    ms = item.get("milestone")
    if ms and ms.get("id") in milestone_map:
        body["milestone"] = milestone_map[ms["id"]]
    created = tgt.post(_path(owner, repo, "/issues"), body=body)
    # drop the follow-up milestone PATCH entirely
    
    (Labels and state=closed legitimately need separate endpoints — Gitea doesn't accept them on create — so those calls are inherent, not redundant.)
  • Estimated impact: Eliminates one round-trip per milestoned item; roughly halves per-item wall time for those items over slow links.

Medium Per-issue paginated comment fetch inside the migration loop (N+1)

  • File: src/codeberg_to_gitea_migrator/issues.py
  • Line(s): 224-235
  • Pattern: N+1 query — one (paginated) read per parent item inside a loop
  • Current code:
    for item, new_number in created:
        ...
        for comment in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments")):
            tgt.post(_path(owner, repo, f"/issues/{new_number}/comments"), ...)
    
  • Why it's slow: For M issues this is M fresh paginated GETs plus one POST per comment, all sequential through the blocking client. Latency of the comment pass scales O(M) and dominates runtime on large repos.
  • Optimal fix: The per-issue fetch shape is largely inherent — Gitea exposes comments only per-issue (no bulk endpoint). The amplifier is the sequential blocking execution, so the real fix is in the Concurrency domain: stream comments for independent issues concurrently. Keep this as the query-shape note and apply the parallelization described under Concurrency & Async.
  • Estimated impact: Concurrency change cuts comment-pass wall time by the concurrency factor; query count itself is bounded by the Gitea API.

Notes (no separate findings): pagination is correctly bounded (clients.paged() terminates on len(batch) < limit); get_all() materializes to a list, which matters only for large sets (see Memory & Resources).


Memory & Resources

Medium Release assets fully buffered in memory (no streaming)

  • File: src/codeberg_to_gitea_migrator/releases.py (root cause at clients.py:98-101)
  • Line(s): releases.py:57-63; clients.py:98-101
  • Pattern: Large allocations — whole-body resp.content read; binary download loaded entirely into memory instead of streamed
  • Current code:
    # clients.py — raw_get returns the FULL response body as bytes
    def raw_get(self, path: str, **params: Any) -> bytes:
        resp = self.request("GET", path, params=_clean(params))
        return resp.content   # entire asset buffered in RAM
    
    # releases.py — each asset downloaded whole, then re-uploaded
    for asset in rel.get("assets", []) or []:
        data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
        tgt.post_multipart(..., files={"attachment": (asset["name"], data)})  # held in memory twice
    
  • Why it's slow: raw_get reads the entire binary asset into a bytes object (httpx .content decodes eagerly); post_multipart keeps it alive while uploading. Peak memory ≈ the size of the largest single asset (briefly duplicated during multipart encoding). A release with a few hundred-MB binary caps the migrator's usable asset size at available RAM.
  • Optimal fix:
    # clients.py — stream the download into a spooled temp file; return a handle
    def raw_get_stream(self, path: str, **params: Any):
        tmp = tempfile.SpooledTemporaryFile(max_size=1 << 20)  # 1 MiB in-RAM threshold
        with self._client.stream("GET", path, params=_clean(params), follow_redirects=True) as resp:
            if resp.status_code >= 400:
                raise ApiError(resp.status_code, str(resp.url), resp.read().text)
            for chunk in resp.iter_bytes():
                tmp.write(chunk)
        tmp.seek(0)
        return tmp
    
    # releases.py — upload straight from the file handle (httpx streams file objs)
    with src.raw_get_stream(...) as data:
        tgt.post_multipart(..., files={"attachment": (asset["name"], data)}, name=asset["name"])
    
  • Estimated impact: Bounds peak memory to ~1 MiB per asset regardless of size. A 500 MB asset drops peak RSS from ~500 MB+ to a few MB; large-binary repos stop risking OOM/swap.

Low Entire issues/PR collection materialized and held across a two-pass migration

  • File: src/codeberg_to_gitea_migrator/issues.py (root cause at clients.py:117-118)
  • Line(s): issues.py:95-105, 192-235; clients.py:117-118
  • Pattern: Unbounded result set — get_all eagerly builds a full list; _collect keeps all issues and PRs in memory for sorting and a two-pass rewrite
  • Current code:
    # clients.py
    def get_all(self, path: str, **params: Any) -> list[Any]:
        return list(self.paged(path, **params))   # entire dataset in RAM
    
  • Why it's slow: Every issue/PR object (full body markdown + metadata) is loaded once and retained for the whole migration so the ref-rewrite pass can map #old → #new. The paged generator's memory benefit is discarded by list(...). Bounded footprint, not a leak; matters mainly for repos with many thousands of issues.
  • Optimal fix: Single-pass migration — create each entity and immediately write its rewritten title/body in the same loop, dropping the source dict after (requires migrating milestones/labels first, already done). Eliminates the held created list and lets each source item be GC'd.
  • Estimated impact: Roughly halves peak memory for the issues/PRs phase on large repos.

Algorithmic Complexity

No issues found. Checked: O(n²) nested loops / array-as-lookup (the only nested loop is the issue→comment fetch at issues.py:224-235, which is the N+1 network pattern reported under Database/Concurrency, not a data-structure issue); sorted(...)[0] sort-for-extremum (0 matches — the two .sort() calls produce fully ordered output and are load-bearing for correctness); redundant computation in loops (3 regexes all compiled once at module scope, callbacks do O(1) dict lookups); inefficient data structures (every keyed lookup is a dict).


Concurrency & Async

High Foundational HTTP layer is fully synchronous — entire I/O-bound migration serialized

  • File: src/codeberg_to_gitea_migrator/clients.py
  • Line(s): 45, 60, 72, 80
  • Pattern: Blocking synchronous I/O / missing parallelization
  • Current code:
    self._client = httpx.Client(base_url=self.api_root, headers={"Authorization": f"token {token}"})
    ...
    resp = self._client.request(method, path, **kwargs)
    
  • Why it's slow: A migration is overwhelmingly I/O-bound. With a sync client and no async/gather anywhere (0 matches for await/asyncio/AsyncClient), total wall-time ≈ Σ of every round-trip, serialized. For hundreds of issues × dozens of comments plus binary assets, that is thousands of sequential network waits.
  • Optimal fix: Move to httpx.AsyncClient, make the verb methods coroutines, and drive independent groups through a bounded gather that respects the forge's rate limit:
    SEM = asyncio.Semaphore(8)  # ponytail: fixed cap, tune to source/target rate limit
    
    async def get(self, path, **params):
        async with SEM:
            resp = await self._client.request("GET", path, params=_clean(params))
        ...
    
    # independent, unordered group → gather (no shared mutation)
    results = await asyncio.gather(*[tgt.post(...) for x in batch])
    
    Keep ordering only where dependencies exist (labels/milestones before issues; release before its assets).
  • Estimated impact: Migration wall-time divided roughly by the concurrency cap on parallelizable groups — commonly 5–10× faster on issue/comment-heavy repos.

High Nested sequential comment-upload loop (the hottest serialization)

  • File: src/codeberg_to_gitea_migrator/issues.py
  • Line(s): 231-235
  • Pattern: Sequential HTTP-in-loop
  • Current code:
    for comment in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments")):
        tgt.post(_path(owner, repo, f"/issues/{new_number}/comments"),
                 body={"body": ref(comment.get("body"))})
    
  • Why it's slow: Nested loop — each issue is iterated, and within it every comment is POSTed one at a time. Comments are mutually independent (across and within issues), yet every POST blocks. On a busy tracker this is the single largest contributor to migration time.
  • Optimal fix: Collect all (new_number, comment) pairs, then upload with a bounded gather:
    comments = [(nnum, ref(c.get("body")))
                for item, nnum in created
                for c in src.get_all(_path(owner, repo, f"/issues/{item['number']}/comments"))]
    await asyncio.gather(*[
        tgt.post(_path(owner, repo, f"/issues/{n}/comments"), body={"body": body})
        for n, body in comments
    ])
    
  • Estimated impact: Removes the dominant serialization; comments upload in min(N, cap) waves instead of one-by-one.

High Sequential release-asset download + upload

  • File: src/codeberg_to_gitea_migrator/releases.py
  • Line(s): 57-63
  • Pattern: Sequential HTTP-in-loop (download then upload, per asset)
  • Current code:
    for asset in rel.get("assets", []) or []:
        data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
        tgt.post_multipart(..., name=asset["name"])
    
  • Why it's slow: Each asset is fetched in full, then uploaded in full, before the next starts. Assets within and across releases are independent; this pipeline is ideal for concurrency. Binary-heavy releases dominate runtime here.
  • Optimal fix: Upload assets with a bounded gather (download can stream in parallel with other assets' uploads):
    async def _one(asset):
        data = await src.raw_get_stream(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
        await tgt.post_multipart(..., name=asset["name"])
    await asyncio.gather(*[_one(a) for a in rel.get("assets", []) or []])
    
  • Estimated impact: Large for binary release sets — throughput scales with the cap up to local bandwidth limits. (Pairs with the streaming fix in Memory & Resources.)

Medium Sequential label / milestone creation

  • File: src/codeberg_to_gitea_migrator/issues.py
  • Line(s): 60-73, 80-91
  • Pattern: Sequential HTTP-in-loop
  • Why it's slow: Labels/milestones are mutually independent (only issues depend on them), yet created one-by-one. id_map/name_map are built via shared mutation today, which is safe only because it's single-threaded.
  • Optimal fix: Gather the POSTs and build the maps from returned results (no shared mutation):
    created = await asyncio.gather(*[tgt.post(.../labels, body=b) for label, b in jobs])
    id_map = {lab["id"]: c["id"] for lab, c in zip(labels, created)}
    
  • Estimated impact: Modest (counts are usually tens), but removes one serial stage.

Medium Sequential pagination could read total page count and fan out

  • File: src/codeberg_to_gitea_migrator/clients.py
  • Line(s): 108-115
  • Pattern: Sequential while True paging
  • Current code:
    while True:
        batch = self.get(path, page=page, limit=limit, **params) or []
        ...
        yield from batch
        if len(batch) < limit:
            return
        page += 1
    
  • Why it's slow: Every page waits on the previous. Forgejo/Gitea list endpoints return X-Total-Count / X-Page-Count, so after page 1 the remaining pages are known and independent.
  • Optimal fix: Fetch page 1, read X-Total-Count to compute page count, then gather pages 2..N; yield in order. (Requires get to expose response headers — currently it returns parsed JSON only.)
  • Estimated impact: Helps repos with thousands of items (many pages); negligible for small lists.

Low Sequential per-ref git subprocess spawns

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 99-100 (also 201)
  • Pattern: Subprocess-in-loop
  • Current code:
    for ref in listing.split():
        _run(["git", "--git-dir", str(bare), "update-ref", "-d", ref])
    
  • Why it's slow: One git process per PR ref to delete. Local git is fast, so the cost is process-spawn overhead, fully serialized.
  • Optimal fix: Delete all refs in a single process via update-ref --stdin:
    stdin = "".join(f"delete {r}\n" for r in listing.split()).encode()
    _run(["git", "--git-dir", str(bare), "update-ref", "--stdin"], input=stdin)
    
  • Estimated impact: Small (local ops), but turns N process spawns into one.

Bundle & Dependencies

No issues found. Checked: wildcard imports (import *), declared-vs-used dependency cross-reference (pyproject.toml vs third-party imports in src/), duplicate/competing libraries, dev/test dependencies leaking into src/, large/inlined assets, dynamic-import opportunities. Runtime deps (httpx, typer) are both used and minimal; dev deps (pytest, ruff) correctly isolated to tests/CI. Every other import is stdlib. The bundle/dependency reference patterns are largely JS/TS-oriented (lodash/moment/tree-shaking) and don't apply to a stdlib-heavy Python CLI.


Dead Code & Redundancy

Low Duplicate _path() helper defined byte-identically in two modules

  • File: src/codeberg_to_gitea_migrator/issues.py, src/codeberg_to_gitea_migrator/releases.py
  • Line(s): issues.py:49-50, releases.py:19-20
  • Pattern: Duplicate logic — identical function copy-pasted across modules
  • Current code:
    # issues.py:49 AND releases.py:19 — identical in both files
    def _path(owner: str, repo: str, suffix: str = "") -> str:
        return f"/repos/{owner}/{repo}{suffix}"
    
  • Why it's slow: No runtime cost — pure maintainability redundancy. The two copies can drift; releases.py already imports from .issues, so the local copy is gratuitous.
  • Optimal fix:
    # releases.py — import instead of redefine
    from .issues import RefCtx, _path
    
    (Or move _path to clients.py and import from there in both.)
  • Estimated impact: Zero runtime effect; removes one DRY violation and drift risk.

Low Duplicated subprocess + error-raising block in _run / _run_capture

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 70-91
  • Pattern: Duplicate logic — identical 8-line subprocess.run + GitError construction in two near-identical helpers
  • Current code:
    def _run(cmd, cwd=None) -> None:
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
        if proc.returncode != 0:
            raise GitError(f"git failed ({proc.returncode}): ... \n{_redact(proc.stderr.strip())}")
    
    def _run_capture(cmd, cwd=None) -> str:
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)  # identical
        if proc.returncode != 0:
            raise GitError(...)                                               # identical
        return proc.stdout
    
  • Why it's slow: No runtime cost — duplication is maintainability risk; an error-handling/redaction fix must be applied in two places. The only real difference is _run_capture returns proc.stdout.
  • Optimal fix: Collapse _run into a thin wrapper over _run_capture:
    def _run_capture(cmd, cwd=None) -> str:
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
        if proc.returncode != 0:
            raise GitError(...)
        return proc.stdout
    
    def _run(cmd, cwd=None) -> None:
        _run_capture(cmd, cwd)
    
  • Estimated impact: Zero runtime effect; removes ~8 lines of divergence-prone error handling.

Checked and clean: commented-out code (0), deprecated/legacy markers (0), dead branches (0), unreachable code (none), unused imports (every import used), unused functions (all 38 module-level defs/classes reachable — confirmed via the GitNexus call graph), no wildcard imports.


I/O & Network

High Release assets downloaded + uploaded one-at-a-time, fully buffered

  • File: src/codeberg_to_gitea_migrator/releases.py
  • Line(s): 57-63
  • Pattern: Missing batching / sequential requests in a loop; missing streaming for binary downloads
  • Current code:
    for asset in rel.get("assets", []) or []:
        data = src.raw_get(_path(owner, repo, f"/releases/{rel['id']}/assets/{asset['id']}"))
        tgt.post_multipart(..., files={"attachment": (asset["name"], data)}, name=asset["name"])
    
  • Why it's slow: Each asset is two blocking round trips (download then upload) strictly in series, and raw_get buffers the whole file into bytes before the upload can start. With N assets across M releases you pay 2·N·M sequential RTTs plus full in-memory copies of each file.
  • Optimal fix: Stream the download into the upload so each asset never sits fully in memory, and run independent assets concurrently with bounded parallelism:
    # clients.py — streaming raw getter
    def raw_get_stream(self, path, **params):
        with self._client.stream("GET", path.lstrip("/"), params=_clean(params)) as r:
            r.raise_for_status()
            yield from r.iter_bytes()   # hand chunks straight to the upload
    
    # releases.py — pipeline download→upload, no full buffer, then bounded-gather across assets
    
  • Estimated impact: Memory drops from O(max asset size) to a fixed buffer; transfer time goes from Σ(2·RTT per asset) toward max(batch) — multiple-fold faster for releases with many assets. (Same root cause as the Memory & Resources streaming finding.)

High Entire migration is synchronous; every independent API write serializes

  • File: src/codeberg_to_gitea_migrator/migrate.py, src/codeberg_to_gitea_migrator/issues.py
  • Line(s): migrate.py:160-169 (orchestration); issues.py:60-90, 195-235 (loops)
  • Pattern: Sequential requests that should be parallel; blocking I/O where independent operations are issued one at a time
  • Current code:
    for label in src.get_all(_path(owner, repo, "/labels")):
        ...
        created = tgt.post(_path(owner, repo, "/labels"), body=body)   # one at a time
    
    Backed by a single blocking httpx.Client (clients.py:45) with time.sleep retries (clients.py:69).
  • Why it's slow: Migration wall-time equals the sum of every HTTP round trip. Independent writes (all labels, all milestones, Pass-B comment batches across different issues) could overlap but don't.
  • Optimal fix: Move to httpx.AsyncClient (already a declared dependency) and overlap independent writes with bounded concurrency, throttled to the target's rate limit (the existing 429 backoff already detects throttling). Ordering-sensitive work (issue number mapping) stays serial.
  • Estimated impact: Large repos move from wall-time ≈ Σ(RTT) toward ≈ max(batch) within each phase — several-fold faster. (Canonical framing of the Concurrency & Async foundational finding.)

Medium Binary release assets fully buffered into memory instead of streamed

  • File: src/codeberg_to_gitea_migrator/clients.py
  • Line(s): 98-101
  • Pattern: Missing streaming — entire response buffered
  • Current code:
    def raw_get(self, path: str, **params: Any) -> bytes:
        resp = self.request("GET", path, params=_clean(params))
        return resp.content
    
  • Why it's slow: resp.content loads the entire asset at once. This caps usable asset size at available RAM and prevents download/upload pipelining. Same root cause as the asset-loop finding, at the transport layer.
  • Optimal fix: Streaming variant feeding chunks to the upload (see Memory & Resources / the High asset finding above).
  • Estimated impact: Fixed low memory regardless of asset size; unblocks the pipeline fix. No speed change on its own but removes the size ceiling.

Medium One git push subprocess per PR-head branch instead of a single batched push

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 201-211
  • Pattern: Sequential I/O in a loop; N process spawns + N network connections where one suffices
  • Current code:
    for pr_number, sha in pull_heads.items():
        _run(["git", "--git-dir", str(bare), "push", tgt, f"{sha}:refs/heads/_pr/{pr_number}"])
    
  • Why it's slow: Each iteration spawns a git process, opens a fresh network connection to the target, performs the auth handshake, and pushes a single ref. Repos with many deleted-branch PRs pay N launches and N connections serially.
  • Optimal fix: git push accepts many refspecs in one invocation:
    if pull_heads:
        refspecs = [f"{sha}:refs/heads/_pr/{n}" for n, sha in pull_heads.items()]
        _run(["git", "--git-dir", str(bare), "push", tgt, *refspecs])
    
  • Estimated impact: N process spawns + N connections → 1; meaningful for repos with many historical deleted-branch PRs.

Positive (no action needed): connection reuse is handled well — one httpx.Client per forge held open for the whole migration via a context manager (migrate.py:135-138), so HTTP keep-alive is reused. Retry logic uses exponential backoff (clients.py:64-69: 0.5 * 2**attempt on 429/5xx), so the "retry without backoff" anti-pattern does not apply.


Rendering & UI

No issues found. Not applicable — this is a CLI application with no rendering or UI layer. (Domain excluded from the dispatch: no frontend surface exists to scan.)


Data Structures

No issues found. Checked: linear-search APIs (.find/.index/.count/list in [ membership → 0 matches; all membership tests are dict-key O(1)), wrong container choices (NumberMap + every map is a dict → O(1) add/get/has/in), deep-copy/clone (deepcopy/import copy/pickle/JSON round-trip → 0), serialization in loops (no json.* in src → 0), array-as-queue (.pop(0)/.insert(0) → 0), regex-in-loop (3 compiles all module-scope, none in loops), object creation in loops (body dicts built once per item). The any_mismatch O(n) scan is confined to __repr__/test. Data-structure selection is appropriate throughout.


Error & Resilience

High Git subprocess calls have no timeout — a stalled clone/push hangs the migration indefinitely

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 70-73 (_run); callers clone --mirror (185), fetch (183), push --mirror (196)
  • Pattern: Missing timeouts — network call without timeout
  • Current code:
    def _run(cmd: list[str], cwd: Path | None = None) -> None:
        proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)  # no timeout=
        if proc.returncode != 0:
            raise GitError(...)
    
  • Why it's slow/fails: subprocess.run has no timeout=, so every network-bound git op can block forever on a stalled TCP connection. The API client carries a 30s timeout, but the git layer — which does the bulk of byte transfer — has none. A hung git push to a degraded target leaves the migration frozen with no progress, error, or recovery short of a manual Ctrl-C; for an unattended cutover that is a production hang.
  • Optimal fix:
    def _run(cmd, cwd=None, timeout: float = 600):
        try:
            proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True, timeout=timeout)
        except subprocess.TimeoutExpired as exc:
            raise GitError(f"git timed out after {timeout}s: {_redact(' '.join(cmd))}") from exc
        if proc.returncode != 0:
            raise GitError(...)
    
    Generous per-op ceiling (e.g. 600s, overridable via --git-timeout).
  • Estimated impact: Converts an indefinite hang into a bounded, diagnosable failure; the run reports which git op stalled.

Medium No fail-fast / circuit breaker — a degraded target forge turns the run into hours of retry churn

  • File: src/codeberg_to_gitea_migrator/clients.py (retry loop) + src/codeberg_to_gitea_migrator/issues.py:199-201
  • Line(s): clients.py:58-70; issues.py:199-201
  • Pattern: No circuit breaker — retry loop without a global failure threshold
  • Current code:
    # clients.py — every call retries independently
    for attempt in range(self.max_retries + 1):
        ... time.sleep(0.5 * (2**attempt))
    # issues.py — a failed item is logged and skipped, then the next starts fresh
    except ApiError as exc:
        log.warning("skipped %s #%s ...", ...)
        continue
    
  • Why it's slow: If the target degrades (persistent 5xx), the retry contract is per call: each of thousands of items waits ~7.5s across 4 attempts, fails, then the next item repeats the full budget. No shared consecutive-failure counter to abort early, so a sustained outage makes the migration crawl for hours producing only skipped items.
  • Optimal fix: Add a consecutive-failure threshold in ApiClient that raises MigrationError once N calls exhaust their retries, resetting on a real write success.
  • Estimated impact: A degraded-target run aborts in seconds (≈N×7.5s) instead of grinding through every remaining item.

Medium Single 30s timeout applied to large binary asset uploads/downloads

  • File: src/codeberg_to_gitea_migrator/clients.py
  • Line(s): 38 (default timeout=30.0), used by raw_get (98-101) and post_multipart (94-96)
  • Pattern: Under-tuned timeout — httpx.Client(timeout=30.0) sets connect=read=write=pool all to 30s
  • Current code:
    timeout: float = 30.0,
    ...
    self._client = httpx.Client(base_url=self.api_root, ..., timeout=timeout, follow_redirects=True)
    
  • Why it's slow: A single value applied to read and write. A multi-hundred-MB release asset over a slow link easily exceeds a 30s window → ReadTimeout/WriteTimeout → caught by the retry loop → the partially-uploaded asset is re-sent from scratch, repeatedly. The timeout that protects metadata calls is too tight for bulk transfers.
  • Optimal fix: Give asset transfers a larger, write-aware timeout via httpx.Timeout, keeping metadata calls snappy:
    from httpx import Timeout
    def raw_get(self, path, **params):
        resp = self.request("GET", path, params=_clean(params),
                            timeout=Timeout(connect=10.0, read=600.0, write=600.0, pool=10.0))
        return resp.content
    
  • Estimated impact: Large-binary repos stop timing out mid-transfer and stop triggering wasteful full re-uploads.

Low Retry backoff has no jitter — deterministic against a shared rate limit

  • File: src/codeberg_to_gitea_migrator/clients.py
  • Line(s): 69
  • Pattern: Missing jitter on retry
  • Current code:
    time.sleep(0.5 * (2**attempt))   # 0.5, 1, 2, 4 … deterministic
    
  • Why it's slow: Fully deterministic. Negligible for one instance, but several migrations (or the migrator + other clients) hitting the same forge retry on the exact same clock → synchronized retry storms that prolong the 429.
  • Optimal fix: Add bounded (full) jitter: time.sleep((0.5 * (2**attempt)) * (0.5 + random.random())).
  • Estimated impact: Low for one run; meaningful when multiple clients share a forge's rate limit.

Low Malformed PR refs skipped silently — could lose a PR head with no trace

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 124-127
  • Pattern: Swallowed error — catch-and-continue with no logging
  • Current code:
    try:
        number = int(ref.split("/")[2])
    except (IndexError, ValueError):
        continue          # no log
    
  • Why it's slow: Unparseable refs are dropped with zero visibility. If a deleted-branch PR's head lives in such a ref, its reconstruction is silently lost with no log line to find it.
  • Optimal fix: log.warning("ignoring unparseable pull ref: %s", _redact(ref)) before continue.
  • Estimated impact: No speed change; restores traceability of skipped refs.

Info Best-effort chmod silently ignored (intentional)

  • File: src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 171-174
  • Pattern: Swallowed error — except OSError: pass
  • Current code:
    try:
        workdir.chmod(0o700)
    except OSError:
        pass
    
  • Why it's noted: Best-effort hardening on a filesystem that may not support mode bits; swallowing is defensible. Flagged only so it is a conscious choice. No fix required.

Checked and clean: no swallowed except blocks (every handler is specific; no bare except: or except Exception: pass); cli.py:80-87 echoes-and-exits on the typed error hierarchy; resource cleanup via context manager (with in migrate.py:135-138); graceful 404 degradation (migrate.py:40-42, releases.py:33-36); max_retries=4 is sane.


Caching & Memoization

Low Redundant per-call string normalization of constant web roots in refs.rewrite

  • File: src/codeberg_to_gitea_migrator/refs.py
  • Line(s): 70-71 (recomputed on every call; called via RefCtx.__call__ at issues.py:41/225-234)
  • Pattern: Constant derived value recomputed per call instead of memoized
  • Current code:
    def rewrite(text, numbers, *, source_web_root, target_web_root, ...):
        ...
        src_root = source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
        tgt_root = target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
    
  • Why it's slow: source_web_root/target_web_root are constant for the whole migration (already normalized once in ApiClient.__init__). The three-call normalization chain runs ~M·(2 + C) times on identical inputs. Small impact (microseconds), but a textbook "recompute a constant N times" pattern.
  • Optimal fix: RefCtx already holds the two roots as immutable fields — precompute normalized forms in __post_init__ and pass them through:
    @dataclass
    class RefCtx:
        numbers: NumberMap
        source_web_root: str
        target_web_root: str
        def __post_init__(self) -> None:
            self._src_root = self.source_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
            self._tgt_root = self.target_web_root.rstrip("/").removesuffix("/api/v1").rstrip("/")
        def __call__(self, text):
            return rewrite(text, self.numbers, src_root=self._src_root, tgt_root=self._tgt_root)
    
  • Estimated impact: Marginal (microseconds); value is clarity and removing N redundant derivations. Listed for completeness.

Checked and clean: @lru_cache/@cache N/A (only one @property, used in __repr__/test — not hot); regex compilation clean (module-scope); no module/instance dict caches (no unbounded-cache risk); no redundant identical API fetches (each entity fetched once; the per-issue comment fetch is the N+1 shape, not a cache miss); HTTP response caching N/A (write-migration client, not a read-heavy server).


Build & Compilation

Low CI dependency cache not enabled — deps reinstalled on every run

  • File: .gitea/workflows/ci.yml
  • Line(s): 14-19
  • Pattern: Missing caching in CI/CD — uv sync without a persisted cache
  • Current code:
    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065  # v5
      with:
        python-version: "3.11"
    - run: python -m pip install uv
    - run: uv sync --frozen --extra dev
    
  • Why it's slow: setup-python@v5 is invoked without a cache input, and no astral-sh/setup-uv/enable-cache step exists, so uv's global download cache is not persisted across runs. Each CI run re-resolves and re-fetches deps cold.
  • Optimal fix:
    - uses: astral-sh/setup-uv@v3   # pin to a SHA per project convention
      with:
        enable-cache: true
        cache-dependency-glob: uv.lock
    
    Or, keeping setup-python, set cache: uv (setup-python@v5 understands uv when uv.lock is present). Stays fully reproducible (--frozen/hash-verified).
  • Estimated impact: Cuts uv sync from a fresh download/install to cache-restore on warm runs — roughly 10–30s saved per CI run; no production effect.

Info Guarded print() in __main__ self-checks — non-actionable, intentional

  • File: src/codeberg_to_gitea_migrator/refs.py, src/codeberg_to_gitea_migrator/mirror.py
  • Line(s): 112, 233
  • Pattern: Development-only code in production — print( matched the debug-logging pattern
  • Current code:
    if __name__ == "__main__":  # self-check — URL auth + redaction, no network
        ...
        print("mirror self-check ok:", url)
    
  • Why it's noted: Not slow — both print calls live behind if __name__ == "__main__": self-check guards and never run during CLI invocation or pytest. Flagged only because the literal pattern matched.
  • Optimal fix: None required (intended self-check convention). Removable without behavior change if zero-noise is desired.
  • Estimated impact: None.

Checked and clean: unoptimized build config (N/A — Python, no bundler), __debug__/python -O flags (no __debug__ usage), heavy/wildcard imports (none), circular imports (none), real I/O in tests (tests use httpx.MockTransport, no network), disabled pytest parallelization (suite is 4 small files — xdist would be YAGNI).


Security-Performance

No issues found. Checked: expensive-crypto-in-hot-paths (bcrypt/hashlib/jwt/hmac/sign/encrypt → 0 matches), ReDoS regex patterns (3 static module-level regexes in refs.py/mirror.py — all linear, no nested quantifiers like (.*)+/(a+)+, no user-input regex compilation), SQL string concatenation (no DB layer → 0), rate-limited web endpoints (no web server — CLI migrator; client-side pacing belongs to Concurrency/I/O), repeated authorization checks in loops (.can/authorize/isAllowed/hasPermission → 0).


Logging & Observability

No issues found. Checked: print() in production paths (2, both in __main__ self-checks — excluded as non-production), f-string/.format()/string-concat in log calls (0 matches — all 12 log sites use lazy %s formatting), logging inside loops (5 per-item INFO logs dominated by HTTP I/O — intended CLI progress, not hot-loop spam), synchronous file logging (none — stderr StreamHandler via basicConfig only), structured-logging gap (N/A for interactive CLI), request/trace IDs (N/A — no web framework). The logging layer follows best practice: module loggers via logging.getLogger(__name__), level gated by --verbose, and consistently lazy %s argument formatting at every call site.


Findings by File

src/codeberg_to_gitea_migrator/clients.py

# Severity Domain Pattern Fix summary Impact
1 High Concurrency Sync HTTP layer httpx.AsyncClient + bounded gather 5–10× faster
2 High I/O All writes serialize AsyncClient + overlap independent writes Several-fold faster
3 Medium I/O raw_get buffers whole body Streaming iter_bytes variant Fixed low memory
4 Medium Error 30s timeout on bulk transfers httpx.Timeout(read=600, write=600) for assets No mid-transfer timeouts
5 Medium Error No circuit breaker Consecutive-failure threshold → abort Seconds vs. hours on outage
6 Medium Concurrency Sequential pagination Read X-Total-Count, fan out pages Helps many-page lists
7 Low Error No jitter on backoff Full-jitter multiplier Avoids retry storms
8 Low Memory get_all materializes to list Streaming paged() where sets are large Bounded memory

src/codeberg_to_gitea_migrator/issues.py

# Severity Domain Pattern Fix summary Impact
1 High Concurrency Nested sequential comment POSTs Collect pairs, bounded gather Removes dominant serialization
2 Medium Database Milestone via redundant PATCH Set milestone in create body −1 RTT per milestoned item
3 Medium Database N+1 per-issue comment fetch Parallelize (no bulk endpoint) Cuts comment-pass wall time
4 Medium Concurrency Sequential label/milestone create Gather POSTs, build maps from results Removes one serial stage
5 Low Memory Full issue/PR set held two-pass Single-pass create+rewrite ~halves peak memory
6 Low Dead Code Duplicate _path helper Import shared _path DRY, no drift

src/codeberg_to_gitea_migrator/releases.py

# Severity Domain Pattern Fix summary Impact
1 High Concurrency / I/O Sequential asset download+upload Bounded gather over assets Multiple-fold faster
2 Low Dead Code Duplicate _path helper Import shared _path DRY, no drift

src/codeberg_to_gitea_migrator/mirror.py

# Severity Domain Pattern Fix summary Impact
1 High Error No git subprocess timeout timeout= + TimeoutExpired → GitError Bounded hang, diagnosable
2 Medium I/O One git push per PR branch Batch refspecs in one push N connections → 1
3 Low Concurrency Per-ref update-ref spawns update-ref --stdin batch N spawns → 1
4 Low Error Malformed PR refs skipped silently log.warning before continue Traceability
5 Low Dead Code Duplicated _run/_run_capture block _run wraps _run_capture −8 lines, no drift
6 Info Error Best-effort chmod swallowed Intentional — no change None

src/codeberg_to_gitea_migrator/migrate.py

# Severity Domain Pattern Fix summary Impact
1 High I/O Entire migration synchronous Async orchestration (see clients.py) Several-fold faster

src/codeberg_to_gitea_migrator/refs.py

# Severity Domain Pattern Fix summary Impact
1 Low Caching Per-call root normalization Precompute in RefCtx.__post_init__ Marginal (microseconds)
2 Info Build Guarded print() self-check Intentional — no change None

.gitea/workflows/ci.yml

# Severity Domain Pattern Fix summary Impact
1 Low Build No uv cache in CI setup-uv enable-cache or cache: uv 10–30s per CI run

Risk Score Breakdown

Scoring: Critical = 10, High = 7, Medium = 4, Low = 2, Info = 0.

Domain Critical High Medium Low Info Points
Database & Queries 0 0 2 0 0 8
Memory & Resources 0 0 1 1 0 6
Algorithmic Complexity 0 0 0 0 0 0
Concurrency & Async 0 3 2 1 0 31
Bundle & Dependencies 0 0 0 0 0 0
Dead Code & Redundancy 0 0 0 2 0 4
I/O & Network 0 2 2 0 0 22
Rendering & UI 0 0 0 0 0 0
Data Structures 0 0 0 0 0 0
Error & Resilience 0 1 2 2 2 19
Caching & Memoization 0 0 0 1 0 2
Build & Compilation 0 0 0 1 1 2
Security-Performance 0 0 0 0 0 0
Logging & Observability 0 0 0 0 0 0
Total 0 6 9 8 3 94

Risk Rating: 0–10 = Low | 11–30 = Moderate | 31–60 = High | 61+ = Critical → Critical (94)

The Critical rating reflects the cumulative cost of fully-serialized I/O at migration scale. There are zero Critical-severity findings and the codebase is clean on 6 of 13 domains; the score is driven by High-severity serialization issues that are concentrated in one architectural change (async).


Improvement Plan

Priority-ordered by impact in this codebase.

  1. [High] Asyncify the HTTP client and overlap independent writes (clients.py, issues.py, migrate.py)

    • Current: fully synchronous httpx.Client; every round-trip serialized.
    • Fix: httpx.AsyncClient + bounded asyncio.gather (cap tuned to the forge rate limit) for labels, milestones, Pass-B comment batches, and release assets. Keep issue-number mapping serial.
    • Impact: wall-time from ≈ Σ(RTT) toward ≈ max(batch) per phase — typically 5–10× faster on issue/comment-heavy repos. This is the single highest-leverage change and resolves the root cause behind four High findings.
  2. [High] Stream release assets + upload concurrently (clients.py:98-101, releases.py:57-63)

    • Current: each asset downloaded whole into RAM, then uploaded one at a time.
    • Fix: streaming raw_get (spooled temp file / iter_bytes) + bounded gather across assets.
    • Impact: peak memory from O(max asset) to ~1 MiB; transfer time multiple-fold faster for binary releases.
  3. [High] Add a timeout to git subprocess calls (mirror.py:70-73)

    • Current: subprocess.run with no timeout= — clone/fetch/push --mirror can hang forever.
    • Fix: timeout= + TimeoutExpired → GitError, overridable via --git-timeout.
    • Impact: converts an indefinite unattended-cutover hang into a bounded, diagnosable failure.
  4. [Medium] Set milestone in the issue create body (issues.py:150-178)

    • Current: create issue, then a follow-up PATCH to set milestone.
    • Fix: include milestone in the POST body; drop the PATCH.
    • Impact: −1 round-trip per milestoned item.
  5. [Medium] Add a circuit breaker for a degraded target (clients.py, issues.py:199-201)

    • Current: per-call retries + per-item skip; a sustained outage grinds for hours.
    • Fix: consecutive-failure threshold that raises MigrationError once N calls exhaust retries.
    • Impact: aborts in seconds instead of churning through every remaining item.
  6. [Medium] Larger, write-aware timeout for bulk transfers (clients.py:38)

    • Current: single 30s timeout on read+write; large assets time out and re-upload repeatedly.
    • Fix: httpx.Timeout(read=600, write=600) on raw_get/post_multipart.
    • Impact: large-binary repos complete instead of fail-or-flail.
  7. [Medium] Batch git operations (mirror.py:99-100, 201-211)

    • Current: one git push per PR-head branch; one update-ref -d per ref.
    • Fix: batch refspecs in a single git push; update-ref --stdin for ref deletion.
    • Impact: N process spawns + N connections → 1.
  8. [Low] Add jitter to retry backoff (clients.py:69)

    • Fix: full-jitter multiplier on the exponential backoff.
    • Impact: avoids synchronized retry storms when multiple clients share a forge rate limit.
  9. [Low] Enable uv cache in CI (.gitea/workflows/ci.yml)

    • Fix: astral-sh/setup-uv enable-cache or setup-python cache: uv.
    • Impact: 10–30s saved per CI run; no production effect.
  10. [Low] DRY helpers (issues.py/releases.py _path; mirror.py _run/_run_capture)

    • Fix: import shared _path; collapse _run into a _run_capture wrapper.
    • Impact: removes ~10 lines of duplication and drift risk; zero runtime effect.
  11. [Low] Log skipped PR refs (mirror.py:124-127) — restore traceability of unparseable refs.

  12. [Low] Precompute normalized web roots (refs.py:70-71) — move constant normalization into RefCtx.__post_init__; marginal.


Methodology

Pattern-based static analysis across 13 performance domains. Each domain was scanned by a specialist sub-agent using anti-anchoring methodology — the agent reads its reference file first, scans the codebase with Grep/Glob for known anti-patterns, and reads only 5–10 lines of context per match to confirm. This avoids accepting existing implementations as "reasonable" by default.

Domains with no applicable surface for this stack were still scanned and reported as "No issues found" (Algorithmic Complexity, Bundle & Dependencies, Data Structures, Rendering & UI, Security-Performance, Logging & Observability). Findings that the same code triggered across multiple domains were cross-referenced rather than duplicated (notably the release-asset loop, reported under Concurrency, I/O, and Memory; and the synchronous-client root cause, reported under Concurrency and I/O).

Execution note: The first parallel batch (13 agents) hit a provider rate-limit; 5 domains were re-run sequentially with acceptance:false so read-only analysis would not be mis-flagged. All 13 domains were ultimately covered.

Limitations: Static analysis only — no profiling, load testing, or runtime measurement. Estimated impacts are qualitative; actual gains depend on repo size, asset sizes, network conditions, and the forge's rate limit. The concurrency estimates in particular assume the chosen cap stays under the target's rate limit (the existing 429 backoff detects throttling). Some issues (e.g. unbounded hang on a stalled git push) are only discoverable under degraded-network conditions.