Migration: bind the repo-transfer context (slim phase interfaces, retire RefCtx/_path) #2

Closed
opened 2026-08-11 14:35:14 +02:00 by AlexKucera · 1 comment
Owner

Problem Statement

As the maintainer of the Codeberg → Gitea migrator, every entity-migration phase
— labels, milestones, issues+PRs, releases — receives the same five loose
parameters: the source client, the target client, the owner, the repo name, and
(issues/releases) a separate reference-rewrite context. Those five are
conceptually one thing — the repo being transferred — yet they are threaded,
separately, through every phase and every internal helper, and owner/repo
are rebuilt into an API path at ~15 call sites via a shared _path(owner, repo, …). This invites a real drift class of bug (transpose owner and name, or push to
the target while authenticating against the source), and it leaves the entire
entity-migration layer — the two-pass issue/PR creation, the label/milestone id
mapping, the state-setting and best-effort PR-merge, and the release/asset
re-upload — with no test surface at all, because the only way to exercise a
phase today is two real forge clients plus a real repository.

Solution

Introduce a single bound-context type — Migration — that holds exactly the
identity quintet (source client, target client, owner, name, number map) and two
small derived accessors (a repo-scoped path builder and a reference rewriter that
delegates to the existing pure rewriter). The four phase functions stop taking the
quintet and instead take the Migration handle; owner/name are bound once and
can no longer drift; the reference-rewrite context (RefCtx) and the shared
_path helper retire because their reason to exist is absorbed. Migration is
pure context — it holds no phase logic and does no I/O — so the phases stay as
free functions in their per-concern modules (the repo's documented "one module per
concern, no monolith" convention holds). The handle becomes the phase layer's test
surface: construct one from two mock-transport clients and a number map, and the
previously-untested two-pass core, mappings, and merge logic become reachable
without any network.

User Stories

  1. As an operator, I want the migration's observable behaviour and report output
    to be unchanged by this refactor.
  2. As an operator, I want cross-references still rewritten correctly to the
    target number space after the change.
  3. As an operator, I want labels, milestones, issues/PRs, and releases still
    migrated identically.
  4. As a maintainer, I want each phase function to take one bound context instead
    of five loose parameters, so the source/target clients and owner/name cannot
    drift between phases.
  5. As a maintainer, I want owner and name bound once, so a transposition
    (owner↔name) is impossible to express.
  6. As a maintainer, I want the source→target number map bound to the two forges
    it belongs to, rather than threaded as a loose argument beside them.
  7. As a maintainer, I want API-path construction owned in one place, so I stop
    seeing the same _path(owner, repo, …) repeated at ~15 call sites.
  8. As a maintainer, I want reference-rewrite plumbing owned in one place, so the
    two web roots stop being passed around explicitly.
  9. As a maintainer, I want to add a new entity phase without re-threading the
    five context parameters through it.
  10. As a maintainer, I want retiring RefCtx and _path to delete code, not
    leave dead types or helpers behind.
  11. As a maintainer, I want the refactor confined to the entity-migration layer,
    so the REST client internals, the reference rewriter, the git mirror, and the
    CLI are untouched.
  12. As a new contributor, I want the entity phases to read as one-liners driving a
    context, so I can follow the migration flow at a glance.
  13. As a new contributor, I want a single type that documents "this is one repo's
    transfer in progress," so I know where the migration's identity lives.
  14. As a test author, I want to construct a Migration from two mock-transport
    clients and a number map and call a phase, so I can test the two-pass issue
    logic without a real forge.
  15. As a test author, I want the label old-id→new-id mapping reachable through the
    phase interface.
  16. As a test author, I want the milestone id mapping reachable through the phase
    interface.
  17. As a test author, I want the issue/PR two-pass flow (create in source-number
    order, then rewrite references, then stream comments) reachable and
    assertable.
  18. As a test author, I want the deleted-branch PR-head fallback reachable through
    the phase interface.
  19. As a test author, I want the release record and binary-asset re-upload
    reachable through the phase interface.
  20. As a test author, I want the state-setting and best-effort PR-merge logic
    reachable through the phase interface.
  21. As CI, I want the entire entity-migration layer testable without any network,
    so the suite stays fast and hermetic.
  22. As CI, I want phase tests to assert external behaviour — what the target
    client received (paths and bodies) and the resulting number map — never phase
    internals.
  23. As CI, I want phase tests to survive an internal refactor of a phase (they
    describe behaviour, not implementation).
  24. As CI, I want the existing ruff and pytest gates to keep passing.
  25. As a future maintainer, I want Migration to stay pure context with no phase
    logic, so it does not accrete into a god-object.
  26. As a future maintainer, I want a clean seam so a future per-phase input type
    (if cross-phase outputs ever grow beyond two maps) is an additive change, not
    a redesign.

Implementation Decisions

  • New module — the bound context (Migration). A frozen dataclass binding
    exactly the identity quintet: the source client, the target client, owner,
    name, and the NumberMap (the map defaults to empty, since the orchestrator
    always starts a migration with no mappings yet). It carries two derived
    accessors
    : a repo-scoped path builder, and a reference rewriter that delegates
    to the existing pure rewriter (sourcing the web roots from the bound clients).
    It holds no phase logic and performs no I/O; a module-docstring guard states
    that any method doing REST I/O or entity-specific branching belongs in a phase
    module, never here.

  • Phase functions stay free, in their per-concern modules. Each phase's
    signature drops the quintet and takes the Migration handle. The issue phase
    still receives the label and milestone maps it depends on (they are per-phase
    outputs produced by the prior phases, not identity) as positional arguments from
    the orchestrator, and it mutates the handle's number map in place rather than
    returning it (the map already lives on the handle).

  • RefCtx retires. It was exactly the number map plus the two web roots; the
    map is now on Migration and the web roots are on the clients. The existing
    pure reference-rewriting function is unchanged.

  • The shared _path helper retires. Its ~15 call sites across the issue and
    release modules move to the handle's path accessor; with no remaining callers
    the helper is deleted.

  • concurrency stays a per-call keyword argument on the phases. It is
    run-tuning, not identity; the handle binds exactly the quintet.

  • Per-phase outputs are not identity. The label map, the milestone map, and
    the report dict are produced by phases and threaded by the orchestrator; they
    do not live on the handle.

  • Import graph stays acyclic. The new module imports only the REST client and
    the reference types; the phase modules and orchestrator import it, never the
    reverse.

  • Orchestrator. The top-level migration builds the Migration once the two
    clients are open and the target repository is ensured, then drives the entity
    phases with it, threading the label/milestone maps between them as before.

  • Target-repo lifecycle helpers are untouched. They run before the handle
    exists (the repository must be ensured before there is anything to migrate), so
    they keep their current parameters; folding them onto the handle is a separate,
    out-of-scope concern.

    Interface shape (from the design-it-twice prototype — decision-rich parts
    only, not a working demo):

    Migration(src, tgt, owner, name, numbers = <empty>)   # frozen; numbers default-factory
      .path(suffix = "") -> str                           # /repos/{owner}/{name}{suffix}
      .rewrite(text) -> str | None                        # delegates to the pure refs rewriter
    # phases — free functions, per-concern modules:
    migrate_labels(m, *, concurrency)            -> dict[int, int]
    migrate_milestones(m, *, concurrency)        -> dict[int, int]
    migrate_issues_and_prs(m, label_map, ms_map, *, concurrency) -> None   # mutates m.numbers
    migrate_releases(m, *, concurrency)          -> int
    

Testing Decisions

  • One seam. The feature is tested through the Migration interface,
    constructed from two httpx.MockTransport-backed clients plus a NumberMap,
    exercising the phase functions. This is the highest practical seam for the
    entity-migration layer and covers all four phases. The ideal seam count — one —
    is met.
  • Prior art in the repo. test_clients.py injects an httpx.MockTransport
    to test the REST client with no network; the new tests lift that identical
    pattern one layer up — two mock clients fed into a Migration, then call a
    phase.
  • What makes a good test here. Tests assert external behaviour — the paths and
    bodies the target client received, and the resulting number-map state — never
    phase internals. They must survive an internal refactor of a phase; if a test
    has to change when the implementation changes, it is testing past the
    interface.
  • What becomes reachable for the first time. The two-pass issue/PR creation
    (create in source-number order, rewrite references, stream comments), the label
    and milestone id mappings, the state-setting, the best-effort PR-merge, the
    deleted-branch PR-head fallback, and the release-plus-asset re-upload.
  • Replace, don't layer. The retired RefCtx/_path have no direct tests of
    their own to delete; the new phase-interface tests are the surface that
    replaces the absence of coverage.
  • Gates. pytest, ruff check ., and ruff format --check . remain green.

Out of Scope

  • The other architecture-review candidates: the git-op seam (specced separately),
    naming the deleted-branch PR-head contract, and collapsing the target-repo
    lifecycle helpers.
  • Folding concurrency onto Migration — rejected; it is run-tuning, not
    identity, and the handle binds exactly the quintet.
  • Introducing a per-phase input type for the label/milestone maps — scaffolding
    for two dictionaries (YAGNI).
  • Folding the target-repo lifecycle helpers onto the handle — a separate
    candidate; they run before the handle exists.
  • Unifying the REST client and the git-op forge identity into one forge type — a
    speculative cross-candidate move; the two transports stay separate.
  • Any change to the REST-client internals, the pure reference rewriter, the git
    mirror, or the CLI surface.

Further Notes

  • Architecture-review candidate #1 (the second priority, after the git-op seam).
  • The grilling is recorded (what the handle binds, free-functions-take-handle,
    the Migration name, RefCtx retirement, the new module's home, the test seam,
    and the REST-vs-git boundary are all settled). The chosen interface is Design C
    (optimize for the two real callers) from the design-it-twice comparison, with
    one naming tweak: the reference-rewriting accessor is named .rewrite() rather
    than .ref() for clarity.
  • Pairs naturally with the git-op-seam candidate: they are orthogonal — Migration
    is the REST/entity context; the git-op seam is the git-transport context. They
    do not collide.
  • Delivered as a single PR; target Python ≥ 3.11, ruff line-length 100.
  • Implementation note: retiring the shared _path helper requires confirming no
    remaining callers after the issue and release modules switch to the handle's
    path accessor.

[Generated by AI]

## Problem Statement As the maintainer of the Codeberg → Gitea migrator, every entity-migration phase — labels, milestones, issues+PRs, releases — receives the same five loose parameters: the source client, the target client, the owner, the repo name, and (issues/releases) a separate reference-rewrite context. Those five are conceptually one thing — the repo being transferred — yet they are threaded, separately, through every phase and every internal helper, and `owner`/`repo` are rebuilt into an API path at ~15 call sites via a shared `_path(owner, repo, …)`. This invites a real drift class of bug (transpose owner and name, or push to the target while authenticating against the source), and it leaves the entire entity-migration layer — the two-pass issue/PR creation, the label/milestone id mapping, the state-setting and best-effort PR-merge, and the release/asset re-upload — with **no test surface at all**, because the only way to exercise a phase today is two real forge clients plus a real repository. ## Solution Introduce a single bound-context type — **`Migration`** — that holds exactly the identity quintet (source client, target client, owner, name, number map) and two small derived accessors (a repo-scoped path builder and a reference rewriter that delegates to the existing pure rewriter). The four phase functions stop taking the quintet and instead take the `Migration` handle; `owner`/`name` are bound once and can no longer drift; the reference-rewrite context (`RefCtx`) and the shared `_path` helper retire because their reason to exist is absorbed. `Migration` is pure context — it holds no phase logic and does no I/O — so the phases stay as free functions in their per-concern modules (the repo's documented "one module per concern, no monolith" convention holds). The handle becomes the phase layer's test surface: construct one from two mock-transport clients and a number map, and the previously-untested two-pass core, mappings, and merge logic become reachable without any network. ## User Stories 1. As an operator, I want the migration's observable behaviour and report output to be unchanged by this refactor. 2. As an operator, I want cross-references still rewritten correctly to the target number space after the change. 3. As an operator, I want labels, milestones, issues/PRs, and releases still migrated identically. 4. As a maintainer, I want each phase function to take one bound context instead of five loose parameters, so the source/target clients and owner/name cannot drift between phases. 5. As a maintainer, I want owner and name bound once, so a transposition (owner↔name) is impossible to express. 6. As a maintainer, I want the source→target number map bound to the two forges it belongs to, rather than threaded as a loose argument beside them. 7. As a maintainer, I want API-path construction owned in one place, so I stop seeing the same `_path(owner, repo, …)` repeated at ~15 call sites. 8. As a maintainer, I want reference-rewrite plumbing owned in one place, so the two web roots stop being passed around explicitly. 9. As a maintainer, I want to add a new entity phase without re-threading the five context parameters through it. 10. As a maintainer, I want retiring `RefCtx` and `_path` to *delete* code, not leave dead types or helpers behind. 11. As a maintainer, I want the refactor confined to the entity-migration layer, so the REST client internals, the reference rewriter, the git mirror, and the CLI are untouched. 12. As a new contributor, I want the entity phases to read as one-liners driving a context, so I can follow the migration flow at a glance. 13. As a new contributor, I want a single type that documents "this is one repo's transfer in progress," so I know where the migration's identity lives. 14. As a test author, I want to construct a `Migration` from two mock-transport clients and a number map and call a phase, so I can test the two-pass issue logic without a real forge. 15. As a test author, I want the label old-id→new-id mapping reachable through the phase interface. 16. As a test author, I want the milestone id mapping reachable through the phase interface. 17. As a test author, I want the issue/PR two-pass flow (create in source-number order, then rewrite references, then stream comments) reachable and assertable. 18. As a test author, I want the deleted-branch PR-head fallback reachable through the phase interface. 19. As a test author, I want the release record and binary-asset re-upload reachable through the phase interface. 20. As a test author, I want the state-setting and best-effort PR-merge logic reachable through the phase interface. 21. As CI, I want the entire entity-migration layer testable without any network, so the suite stays fast and hermetic. 22. As CI, I want phase tests to assert external behaviour — what the target client received (paths and bodies) and the resulting number map — never phase internals. 23. As CI, I want phase tests to survive an internal refactor of a phase (they describe behaviour, not implementation). 24. As CI, I want the existing ruff and pytest gates to keep passing. 25. As a future maintainer, I want `Migration` to stay pure context with no phase logic, so it does not accrete into a god-object. 26. As a future maintainer, I want a clean seam so a future per-phase input type (if cross-phase outputs ever grow beyond two maps) is an additive change, not a redesign. ## Implementation Decisions - **New module — the bound context (`Migration`).** A frozen dataclass binding exactly the identity quintet: the source client, the target client, `owner`, `name`, and the `NumberMap` (the map defaults to empty, since the orchestrator always starts a migration with no mappings yet). It carries **two derived accessors**: a repo-scoped path builder, and a reference rewriter that delegates to the existing pure rewriter (sourcing the web roots from the bound clients). It holds no phase logic and performs no I/O; a module-docstring guard states that any method doing REST I/O or entity-specific branching belongs in a phase module, never here. - **Phase functions stay free, in their per-concern modules.** Each phase's signature drops the quintet and takes the `Migration` handle. The issue phase still receives the label and milestone maps it depends on (they are per-phase outputs produced by the prior phases, not identity) as positional arguments from the orchestrator, and it mutates the handle's number map in place rather than returning it (the map already lives on the handle). - **`RefCtx` retires.** It was exactly the number map plus the two web roots; the map is now on `Migration` and the web roots are on the clients. The existing pure reference-rewriting function is unchanged. - **The shared `_path` helper retires.** Its ~15 call sites across the issue and release modules move to the handle's path accessor; with no remaining callers the helper is deleted. - **`concurrency` stays a per-call keyword argument on the phases.** It is run-tuning, not identity; the handle binds exactly the quintet. - **Per-phase outputs are not identity.** The label map, the milestone map, and the report dict are produced by phases and threaded by the orchestrator; they do not live on the handle. - **Import graph stays acyclic.** The new module imports only the REST client and the reference types; the phase modules and orchestrator import it, never the reverse. - **Orchestrator.** The top-level migration builds the `Migration` once the two clients are open and the target repository is ensured, then drives the entity phases with it, threading the label/milestone maps between them as before. - **Target-repo lifecycle helpers are untouched.** They run *before* the handle exists (the repository must be ensured before there is anything to migrate), so they keep their current parameters; folding them onto the handle is a separate, out-of-scope concern. *Interface shape (from the design-it-twice prototype — decision-rich parts only, not a working demo):* ``` Migration(src, tgt, owner, name, numbers = <empty>) # frozen; numbers default-factory .path(suffix = "") -> str # /repos/{owner}/{name}{suffix} .rewrite(text) -> str | None # delegates to the pure refs rewriter # phases — free functions, per-concern modules: migrate_labels(m, *, concurrency) -> dict[int, int] migrate_milestones(m, *, concurrency) -> dict[int, int] migrate_issues_and_prs(m, label_map, ms_map, *, concurrency) -> None # mutates m.numbers migrate_releases(m, *, concurrency) -> int ``` ## Testing Decisions - **One seam.** The feature is tested through the `Migration` interface, constructed from two `httpx.MockTransport`-backed clients plus a `NumberMap`, exercising the phase functions. This is the highest practical seam for the entity-migration layer and covers all four phases. The ideal seam count — one — is met. - **Prior art in the repo.** `test_clients.py` injects an `httpx.MockTransport` to test the REST client with no network; the new tests lift that identical pattern one layer up — two mock clients fed into a `Migration`, then call a phase. - **What makes a good test here.** Tests assert external behaviour — the paths and bodies the target client received, and the resulting number-map state — never phase internals. They must survive an internal refactor of a phase; if a test has to change when the implementation changes, it is testing past the interface. - **What becomes reachable for the first time.** The two-pass issue/PR creation (create in source-number order, rewrite references, stream comments), the label and milestone id mappings, the state-setting, the best-effort PR-merge, the deleted-branch PR-head fallback, and the release-plus-asset re-upload. - **Replace, don't layer.** The retired `RefCtx`/`_path` have no direct tests of their own to delete; the new phase-interface tests are the surface that replaces the absence of coverage. - **Gates.** `pytest`, `ruff check .`, and `ruff format --check .` remain green. ## Out of Scope - The other architecture-review candidates: the git-op seam (specced separately), naming the deleted-branch PR-head contract, and collapsing the target-repo lifecycle helpers. - Folding `concurrency` onto `Migration` — rejected; it is run-tuning, not identity, and the handle binds exactly the quintet. - Introducing a per-phase input type for the label/milestone maps — scaffolding for two dictionaries (YAGNI). - Folding the target-repo lifecycle helpers onto the handle — a separate candidate; they run before the handle exists. - Unifying the REST client and the git-op forge identity into one forge type — a speculative cross-candidate move; the two transports stay separate. - Any change to the REST-client internals, the pure reference rewriter, the git mirror, or the CLI surface. ## Further Notes - Architecture-review candidate #1 (the second priority, after the git-op seam). - The grilling is recorded (what the handle binds, free-functions-take-handle, the `Migration` name, `RefCtx` retirement, the new module's home, the test seam, and the REST-vs-git boundary are all settled). The chosen interface is Design C (optimize for the two real callers) from the design-it-twice comparison, with one naming tweak: the reference-rewriting accessor is named `.rewrite()` rather than `.ref()` for clarity. - Pairs naturally with the git-op-seam candidate: they are orthogonal — `Migration` is the REST/entity context; the git-op seam is the git-transport context. They do not collide. - Delivered as a single PR; target Python ≥ 3.11, ruff line-length 100. - Implementation note: retiring the shared `_path` helper requires confirming no remaining callers after the issue and release modules switch to the handle's path accessor. [Generated by AI]
AlexKucera added the ready-for-agentPRD labels 2026-08-11 14:35:14 +02:00
Author
Owner

Absorbs review candidate #4 (target-repo lifecycle helpers)

Architecture-review candidate #4 — "collapse the target-repo lifecycle helpers" — was grilled and resolved to dissolve into this issue, not stand alone. The repetition it nominally fixed (the (tgt, owner, name) threading and the /repos/{owner}/{name} path rebuilt ~5×) is exactly the problem this Migration handle solves. What remains is two residual items this issue should own:

  1. Inline the trivial single-call-site helpers. When rewriting the migrate.py target-repo helpers to take the Migration handle, fold _target_exists and _is_fresh straight into _ensure_target_repo — they are private, called only from _ensure_target_repo, and not reused. _ensure_target_repo becomes the single named lifecycle seam. (~6 lines removed.) _git_url stays as-is — it is a URL-formatting concern reused twice for the mirror, not a lifecycle helper.

  2. Test the create-or-populate branching. _ensure_target_repo holds the meatiest untested decision tree in the orchestrator — delete-existing vs fresh-check vs refuse-duplicate vs create; the org-vs-user endpoint selection; and the 401/403 scope-error messaging — and currently has zero coverage. Reach it through this issue's new MockTransport seam (a mock m.tgt returning 404 / existing / fresh / non-fresh / 403) and assert the external behaviour (which endpoint got hit, what body, whether the repo was deleted).

No TargetRepo abstraction — one call site, one sequence; a class for a caller-of-one is ceremony the no-monolith rule exists to prevent.

[Generated by AI]

## Absorbs review candidate #4 (target-repo lifecycle helpers) Architecture-review candidate #4 — "collapse the target-repo lifecycle helpers" — was grilled and resolved to **dissolve into this issue**, not stand alone. The repetition it nominally fixed (the `(tgt, owner, name)` threading and the `/repos/{owner}/{name}` path rebuilt ~5×) is exactly the problem this `Migration` handle solves. What remains is two residual items this issue should own: 1. **Inline the trivial single-call-site helpers.** When rewriting the `migrate.py` target-repo helpers to take the `Migration` handle, fold `_target_exists` and `_is_fresh` straight into `_ensure_target_repo` — they are private, called only from `_ensure_target_repo`, and not reused. `_ensure_target_repo` becomes the single named lifecycle seam. (~6 lines removed.) `_git_url` stays as-is — it is a URL-formatting concern reused twice for the mirror, not a lifecycle helper. 2. **Test the create-or-populate branching.** `_ensure_target_repo` holds the meatiest *untested* decision tree in the orchestrator — delete-existing vs fresh-check vs refuse-duplicate vs create; the org-vs-user endpoint selection; and the 401/403 scope-error messaging — and currently has zero coverage. Reach it through this issue's new MockTransport seam (a mock `m.tgt` returning 404 / existing / fresh / non-fresh / 403) and assert the external behaviour (which endpoint got hit, what body, whether the repo was deleted). No `TargetRepo` abstraction — one call site, one sequence; a class for a caller-of-one is ceremony the no-monolith rule exists to prevent. [Generated by AI]
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: AlexKucera/codeberg-to-gitea-migrator#2