From a323ee9a346cff62498ff3eb3c3c1e4efe3965bb Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 11:15:10 +0000 Subject: [PATCH 1/9] The code index reads merged-PR history from a Forgejo host A repository entry with "forge": "forgejo" gets its merged PRs, with their changed files, from the host's REST API into code_pr_history, in the code_pr_history worker and in `loom code backfill-prs`. The API has no target-branch filter and no merged-date search, so the branch is matched on each PR's base ref and the backfill walks closed PRs newest close first (sort=recentclose, Forgejo 12 or later), resuming at the page it stopped at. A page cut by the PR budget is read whole, so a resume never repeats a PR. The deployment's GitHub token is never sent to a Forgejo host: an entry reads with its own github_token, or anonymously. Review comments, the issue mirror and open-PR heads stay GitHub-only. PR links for a Forgejo repository point at the host's /pulls/N page. Closes issue 1682 Signed-off-by: Kaloyan Naumov --- docs/architecture/code-index-architecture.md | 2 +- docs/features/code-index/history-and-prs.md | 14 + docs/operations/code-index-operations.md | 10 +- docs/reference/cli.md | 2 +- docs/reference/configuration.md | 2 +- docs/reference/status.md | 2 +- docs/reference/workers.md | 2 +- loom.example.yaml | 3 +- schemas/loom-settings.schema.json | 2 +- server/cli/code.py | 2 +- server/cli/code_prs.py | 67 ++- server/clients/forgejo.py | 202 +++++++ server/code/app/bisect_scan.py | 3 +- server/code/domain/index/blame_range.py | 3 +- server/code/domain/index/remote.py | 23 + server/code/domain/index/repos.py | 20 +- server/code/workers/pr_history.py | 38 +- server/settings/catalog.py | 3 +- tests/unit/fixtures/README.md | 1 + .../unit/fixtures/forgejo_pull_requests.json | 557 ++++++++++++++++++ tests/unit/snapshots/cli_help.json | 2 +- tests/unit/snapshots/cli_tree.json | 2 +- .../test_code_worker_failures_are_noted.py | 1 + tests/unit/test_forgejo_pr_source.py | 379 ++++++++++++ 24 files changed, 1314 insertions(+), 28 deletions(-) create mode 100644 server/clients/forgejo.py create mode 100644 tests/unit/fixtures/forgejo_pull_requests.json create mode 100644 tests/unit/test_forgejo_pr_source.py diff --git a/docs/architecture/code-index-architecture.md b/docs/architecture/code-index-architecture.md index 7db46d2a667..ff61ca0098c 100644 --- a/docs/architecture/code-index-architecture.md +++ b/docs/architecture/code-index-architecture.md @@ -509,7 +509,7 @@ What callers see is in [freshness](../features/code-index/freshness.md). | Table | Writer | Holds | | ------------------------------------------------------ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -| `code_pr_history`, `code_pr_reviews`, `code_gh_items` | `code_pr_history` (GitHub REST, cursor on `updated_at`) | Merged PRs with files, review comments, issues. A rate limit or 5xx leaves the cursor unmoved. | +| `code_pr_history`, `code_pr_reviews`, `code_gh_items` | `code_pr_history` (GitHub or Forgejo REST) | Merged PRs with files, review comments, issues. A rate limit or 5xx leaves the cursor unmoved. | | `code_context_packs`, `code_review_briefs` | `code_ingest` at the merge commit, or on demand | Per-PR context pack and reviewer's brief. | | `code_backport_gaps` | `code_backport_gaps` (nightly; needs `code_pr_history`) | Per backport-labelled trunk PR, one row per release-branch namespace: covered, owed, not affected. | | `code_test_map`, `code_symbol_stats`, `code_unit_risk` | `code_graph_stats` (weekly), `loom code crossref` | Test↔source map, symbol fan-in, per-unit risk. | diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index fdf1936b7a9..9fbf8fdb69d 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -30,6 +30,20 @@ so "what changed on 2.4" reads the 2.4 namespace. `loom code backfill-prs` loads `LOOM_CODE_PR_BACKFILL_MONTHS` (12) of history for a new repository ([code index operations](../../operations/code-index-operations.md#first-index)). +## Forgejo hosts + +An entry in `LOOM_CODE_REPOS_JSON` with `"forge": "forgejo"` and an HTTPS or SSH +`git_remote` reads its merged PRs from that host's REST API (`https:///api/v1`) +into `loom.code_pr_history`; the Repositories page does not set `forge`. The entry's +`github_token` is then the host's access token (scope `read:repository`; a public +repository reads without one), never `LOOM_CODE_GITHUB_TOKEN`, which is not sent to a +Forgejo host. The entry's `repo` is `host/owner/name`, which is also what its PR links +are built from. `backfill-prs` sorts by close time (`sort=recentclose`), which needs +Forgejo 12 or later. Review comments, the issue mirror and open-PR heads stay GitHub-only. The API has no target-branch filter and +no merged-date search, so the branch is matched on each PR's `base.ref` and +`backfill-prs` walks closed PRs newest close first back to +`LOOM_CODE_PR_BACKFILL_MONTHS`, resuming at the page it stopped at. + ## Which op answers which question | Question | Op | diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 5edd518d2e8..ccc15810239 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -94,7 +94,9 @@ when the deployment indexes more than one repository. run the commands above again once a colour deployment's previous colour has stopped. - **A GitHub token** (`LOOM_CODE_GITHUB_TOKEN`, or `github_token` per entry) for - merged-PR history and for private remotes. + merged-PR history and for private remotes. On a Forgejo host the entry's + `github_token` is that host's token, never `LOOM_CODE_GITHUB_TOKEN` + ([PR history from Forgejo](../features/code-index/history-and-prs.md#forgejo-hosts)). ## Configure the entry @@ -116,7 +118,7 @@ LOOM_CODE_REPOS_JSON='[ | Field | Meaning | | ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- | | `namespace`, `org` | where the index lives | -| `repo` | `owner/name` on GitHub | +| `repo` | `owner/name` on GitHub, `host/owner/name` on a Forgejo host | | `git_dir`, `git_remote` | the bare clone and its remote; branches of one repository share one clone | | `git_branch` | the branch this namespace tracks | | `path_prefixes` | comma-separated prefixes to index; an entry without it indexes the whole tree minus the built-in denylist | @@ -132,6 +134,7 @@ LOOM_CODE_REPOS_JSON='[ | `scip_extra_producers` | further compiler-tier producers over the same tree (a Python repository with a TypeScript frontend), each in its own checkout | | `git_extra_branches` | globs of other remote branches the shared mirror should carry | | `github_token` | per-entry override of `LOOM_CODE_GITHUB_TOKEN` | +| `forge` | `forgejo` for a Forgejo host: its pull requests are read from the host's API | | `git_proxy_identity` | the user name its git presents to an operator's [git proxy](#git-through-a-forward-proxy); unset, the deployment's default | Name a `git_remote` host in ASCII, as punycode for an internationalised name: a page @@ -284,7 +287,8 @@ docker exec loom-workers loom code backfill-prs --namespace code-myrepo --org ac runs it. `--dialect-folder-pass` lets SQL files of undecided dialect take the dialect their directory agrees on. - `backfill-prs` loads merged-PR history from GitHub, resumable by cursor and bounded by - GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12). `backfill-reviews` + GitHub's rate limit (`LOOM_CODE_PR_BACKFILL_MONTHS`, default 12), or from a Forgejo + host's API. `backfill-reviews` adds inline review comments, `backfill-assignees` requested reviewers, and `backfill-items` issues and PRs in any state. - **The worker does not start a first index for a configured entry.** An entry without a diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 5141ff16320..1c8ae3179f2 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -237,7 +237,7 @@ python scripts/codegen/docs_reference.py | `loom code crossref` | SQL/shell test -> implementing C++ reference pass (writes code_test_map method=content_reference; idempotent). | `--org`, `--namespace` | | `loom code coverage-import` | Import the newest per-test line coverage run of the configured source (writes code_test_map method=coverage and code_coverage_files). | `--org`, `--namespace`, `--dry-run` | | `loom code export-pairs` | Export (query -> acted-on unit, hard negatives) retrieval pairs from real traffic (trace x outcome join) for embedder/reranker fine-tuning. | `--org`, `--namespace`, `--days`, `--out` | -| `loom code backfill-prs` | Merged-PR history from GitHub. | `--org`, `--namespace`, `--months`, `--max-prs` | +| `loom code backfill-prs` | Merged-PR history from GitHub or a Forgejo host. | `--org`, `--namespace`, `--months`, `--max-prs` | | `loom code repack` | Regenerate context packs for recently merged PRs in the current pack shape. | `--org`, `--namespace`, `--days`, `--limit`, `--dry-run` | | `loom code describe` | LLM contextual one-liners for top-PageRank chunks. | `--org`, `--namespace`, `--top-pct`, `--limit`, `--suffix`, `--concurrency` | | `loom code answers-purge` | Tombstone cached code.ask answers (after a synthesis-model upgrade, stale weaker-model answers would otherwise be served forever — the cache only self-invalidates on cited-file change). | `--llm-model`, `--all`, `--apply`, `--dry-run`, `--org`, `--namespace` | diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 251101e9d6c..c94aee49577 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -488,7 +488,7 @@ The code index's network git (clone, fetch, ls-remote, submodule update) through | Variable | Type | Default | Live | Meaning | | --- | --- | --- | --- | --- | -| `LOOM_CODE_PR_HISTORY_ENABLED` | `bool` | `False` | | Merged-PR history sync (GitHub REST, cursor-resumable). | +| `LOOM_CODE_PR_HISTORY_ENABLED` | `bool` | `False` | | Merged-PR history sync (GitHub REST, or the REST API of a Forgejo host; cursor-resumable). | | `LOOM_CODE_PR_HISTORY_INTERVAL_SECONDS` | `int` | `900` | | Seconds between PR-history sync passes. | ### The set-wide backport report diff --git a/docs/reference/status.md b/docs/reference/status.md index 693dec19cca..83d99f7a462 100644 --- a/docs/reference/status.md +++ b/docs/reference/status.md @@ -103,7 +103,7 @@ default is `off`) are not listed here. | `LOOM_CODE_HOST_ISLANDS` | Shell inside CI/build files (Actions `run:`, GitLab `script:`, Dockerfile `RUN`, Makefile recipes, Jenkinsfile `sh`) is parsed for facets, script `includes` edges and SQL; jobs, targets and stages… | | `LOOM_CODE_INGEST_DENYLIST_BUILTIN` | True applies the built-in generated, minified and vendored ingest rules (code/app/index/denylist.py), which match 0.19% of rows. | | `LOOM_CODE_ORG_READABLE` | True lets every authenticated principal of the org read every configured code namespace (right for public or org-internal repos); false leaves reads to the namespace's own visibility and grants. | -| `LOOM_CODE_PR_HISTORY_ENABLED` | Merged-PR history sync (GitHub REST, cursor-resumable). | +| `LOOM_CODE_PR_HISTORY_ENABLED` | Merged-PR history sync (GitHub REST, or the REST API of a Forgejo host; cursor-resumable). | | `LOOM_CODE_PY_SQL_ISLANDS` | SQL a Python file runs (database-client call arguments and SQL-looking literals) becomes `statement` symbols, facets (confidence 0.7 with a format hole) and table edges. | | `LOOM_CODE_REPO_PUBLIC` | The scalar repo entry is public: its namespace registers join_policy=open and discoverable. | | `LOOM_CODE_SANDBOX_REQUIRED` | Set by deployments that ship the sandbox profiles: a repository job refuses to run rather than run unsandboxed, and /v1/health reports the missing sandbox as an error. | diff --git a/docs/reference/workers.md b/docs/reference/workers.md index 2f596758e35..7f9bfb56284 100644 --- a/docs/reference/workers.md +++ b/docs/reference/workers.md @@ -212,7 +212,7 @@ adding its row. | `code_embed_recovery` | Embedding recovery for the code plane (mirror of the memory plane's embedding worker). | `LOOM_CODE_EMBED_RECOVERY_ENABLED` | False | `LOOM_CODE_EMBED_RECOVERY_INTERVAL_SECONDS` | 30 | | `code_graph_stats` | Weekly graph statistics: PageRank over the include graph, per-file degrees, and the test↔source map. | `LOOM_CODE_GRAPH_STATS_ENABLED` | False | `LOOM_CODE_GRAPH_STATS_INTERVAL_SECONDS` | 604800 | | `code_ingest` | Per-merge fast-tier ingest for the code plane. | `LOOM_CODE_INGEST_ENABLED` | True | `LOOM_CODE_INGEST_INTERVAL_SECONDS` | 120 | -| `code_pr_history` | Merged-PR history sync from the GitHub REST API (cursor-resumable). | `LOOM_CODE_PR_HISTORY_ENABLED` | False | `LOOM_CODE_PR_HISTORY_INTERVAL_SECONDS` | 900 | +| `code_pr_history` | Merged-PR history sync from the GitHub REST API, or a Forgejo host's (cursor-resumable). | `LOOM_CODE_PR_HISTORY_ENABLED` | False | `LOOM_CODE_PR_HISTORY_INTERVAL_SECONDS` | 900 | | `code_scip_apply` | Apply staged SCIP deltas to the compiler-grade tier. | `LOOM_CODE_SCIP_APPLY_ENABLED` | False | `LOOM_CODE_SCIP_APPLY_INTERVAL_SECONDS` | 60 | | `code_scip_delta` | Per-merge compiler-tier freshness: scip-clang deltas. | `LOOM_CODE_SCIP_DELTA_ENABLED` | True | `LOOM_CODE_SCIP_DELTA_INTERVAL_SECONDS` | 300 | | `code_scip_full` | C++ full re-index, one entry per pass. | `LOOM_CODE_SCIP_FULL_ENABLED` | True | `LOOM_CODE_SCIP_FULL_INTERVAL_SECONDS` | 900 | diff --git a/loom.example.yaml b/loom.example.yaml index 8dbfc14df7e..63a7921d5c9 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1606,7 +1606,8 @@ settings: # --- PR history --- - # Merged-PR history sync (GitHub REST, cursor-resumable). [restart] + # Merged-PR history sync (GitHub REST, or the REST API of a Forgejo host; + # cursor-resumable). [restart] # code_pr_history_enabled: false # Seconds between PR-history sync passes. [restart] diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index d1defd9cc84..09bceed4b7a 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1570,7 +1570,7 @@ "code_pr_history_enabled": { "default": false, "type": "boolean", - "description": "Merged-PR history sync (GitHub REST, cursor-resumable)." + "description": "Merged-PR history sync (GitHub REST, or the REST API of a Forgejo host; cursor-resumable)." }, "code_pr_history_interval_seconds": { "default": 900, diff --git a/server/cli/code.py b/server/cli/code.py index 8a6527f0856..7f6a34c858c 100644 --- a/server/cli/code.py +++ b/server/cli/code.py @@ -467,7 +467,7 @@ def register_code_cli(sub: argparse._SubParsersAction[argparse.ArgumentParser]) def _register_backfill_prs(csub: argparse._SubParsersAction[argparse.ArgumentParser]) -> None: - p_prs = csub.add_parser("backfill-prs", help="Merged-PR history from GitHub.") + p_prs = csub.add_parser("backfill-prs", help="Merged-PR history from GitHub or a Forgejo host.") _add_common(p_prs) p_prs.add_argument("--months", type=int, default=None) p_prs.add_argument("--max-prs", type=int, default=100000) diff --git a/server/cli/code_prs.py b/server/cli/code_prs.py index 536bead04af..1728f441c5a 100644 --- a/server/cli/code_prs.py +++ b/server/cli/code_prs.py @@ -1,10 +1,11 @@ -"""`loom code backfill-prs` and the GitHub history backfills: merged PRs, +"""`loom code backfill-prs` (GitHub or Forgejo) and the GitHub history backfills: reviews, items and assignees.""" from __future__ import annotations import argparse import sys +from typing import Any from server.cli._ch import connect_code_plane from server.cli.code_run import _identity, _note, _repo_cfg @@ -21,6 +22,8 @@ async def _backfill_prs(args: argparse.Namespace) -> int: from server.settings import settings cfg = _repo_cfg(args) + if cfg.pr_source == "forgejo": + return await _backfill_prs_forgejo(args, cfg) if not cfg.github_token: # Same policy as the code_pr_history worker: public repos read fine # anonymously, but at 60 req/h a day of ClickHouse merges (~100 PRs, @@ -66,6 +69,59 @@ async def _backfill_prs(args: argparse.Namespace) -> int: return 0 +async def _backfill_prs_forgejo(args: argparse.Namespace, cfg: Any) -> int: + """Merged PRs newest close first, back to `--months`, from the page the last run + stopped at (`pr_backfill_page`; a finished walk starts over at page 1, its rows + rewritten as the same versions). Forgejo's API has no merged-date search, so this + walk replaces GitHub's day windows.""" + from datetime import timedelta + + from server.clients import forgejo + from server.clients.github import GitHubError, RateLimited + from server.code.domain.index.remote import forgejo_api_repo + from server.code.store.index import CodeRepo + from server.code.workers.pr_history import pr_rows + from server.core.ch import get_client + from server.settings import settings + + api = forgejo_api_repo(cfg.git_remote) + await connect_code_plane(get_client(), args) + org, ns = cfg.org, cfg.namespace + repo = CodeRepo() + months = args.months or settings.code_pr_backfill_months + oldest = naive_utc_now() - timedelta(days=30 * months) + page = int(await repo.get_state(org, ns, "pr_backfill_page") or 1) + total = 0 + while total < args.max_prs: + try: + prs, nxt = await forgejo.merged_prs_back_to( + api, + cfg.github_token, + oldest, + max_prs=min(200, args.max_prs - total), + base=cfg.git_branch, + start_page=page, + max_pages=5, + ) + except RateLimited as e: + print(f"rate limited ({e}); resume later — cursor kept at page {page}", file=sys.stderr) + return 1 + except GitHubError as e: + print(f"forgejo error at page {page}: {e}", file=sys.stderr) + return 1 + if prs: + await repo.insert_rows("code_pr_history", await pr_rows(repo, org, ns, prs)) + total += len(prs) + print(f" from page {page}: {len(prs)} merged PRs (total {total})") + await repo.set_state(org, ns, "pr_backfill_page", str(nxt or 1)) + if not nxt: + break + page = nxt + print(f"backfill-prs: {total} PRs back to {oldest.date()}") + _note(prs=total) + return 0 + + async def _backfill_reviews(args: argparse.Namespace) -> int: from server.clients.github import GitHubError, RateLimited, pr_review_comments from server.code.store.index import CodeRepo @@ -73,6 +129,9 @@ async def _backfill_reviews(args: argparse.Namespace) -> int: from server.core.ch import get_client cfg = _repo_cfg(args) + if cfg.pr_source != "github": + print("backfill-reviews: GitHub repositories only", file=sys.stderr) + return 2 if not cfg.github_token: print( "backfill-reviews: LOOM_CODE_GITHUB_TOKEN required (one request per PR)", @@ -130,6 +189,9 @@ async def _backfill_items(args: argparse.Namespace) -> int: from server.settings import settings cfg = _repo_cfg(args) + if cfg.pr_source != "github": + print("backfill-items: GitHub repositories only", file=sys.stderr) + return 2 if not cfg.github_token: print("backfill-items: LOOM_CODE_GITHUB_TOKEN required", file=sys.stderr) return 2 @@ -193,6 +255,9 @@ async def _backfill_assignees(args: argparse.Namespace) -> int: from server.core.ch import get_client cfg = _repo_cfg(args) + if cfg.pr_source != "github": + print("backfill-assignees: GitHub repositories only", file=sys.stderr) + return 2 if not cfg.github_token: print("backfill-assignees: LOOM_CODE_GITHUB_TOKEN required", file=sys.stderr) return 2 diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py new file mode 100644 index 00000000000..29b3613c87d --- /dev/null +++ b/server/clients/forgejo.py @@ -0,0 +1,202 @@ +"""Forgejo REST API client for the code plane's merged-PR history. + +The counterpart of `github.merged_prs_since` for a repository on a Forgejo host: merged +PRs with their files and reviewers (`loom.code_pr_history`). It returns `github`'s +`MergedPR` and raises its errors (`GitHubError`, `RateLimited` for a 429), so the worker +keeps one "stop, cursor unmoved" path for both sources. + +`repo` is the API URL of the repository (`remote.forgejo_api_repo`). Where the API +differs from GitHub's: + +- Pages follow the `Link: rel="next"` header; the server caps a page at its + `MAX_RESPONSE_ITEMS` (50 by default) whatever `limit` asks for. +- Timestamps carry the server's UTC offset; they are converted to naive UTC. +- `/pulls` has no `base` filter: the target branch is filtered here, on `base.ref`. +- There is no merged-date search: the backfill walks closed PRs by close time + (`sort=recentclose`, Forgejo 12 or later). +""" + +from __future__ import annotations + +from datetime import UTC, datetime +from typing import Any + +import httpx + +from server.clients._http import get_client +from server.clients.github import ( + GitHubError, + MergedPR, + RateLimited, + pr_assignees, + pr_base_ref, +) + +# Forgejo caps a page at its own MAX_RESPONSE_ITEMS (50 by default), so a larger value +# would change nothing. +_PAGE_SIZE = 50 # not a setting: the server's own cap + + +def _headers(token: str) -> dict[str, str]: + h = {"Accept": "application/json", "User-Agent": "loom-code-intel/1.0"} + if token: + h["Authorization"] = f"token {token}" + return h + + +def _has_next(resp: httpx.Response) -> bool: + return 'rel="next"' in resp.headers.get("Link", "") + + +async def _get_page( + url: str, token: str, params: dict[str, Any] +) -> tuple[list[dict[str, Any]], bool]: + """One list page's objects and whether the server names a next page. Every failure + is a `GitHubError` (a 429 its `RateLimited` subclass).""" + try: + resp = await get_client().get(url, headers=_headers(token), params=params) + except httpx.RequestError as e: + raise GitHubError(f"GET {url} -> {type(e).__name__}") from e + if resp.status_code == 429: + raise RateLimited(f"rate limited; retry after {resp.headers.get('Retry-After', '?')}s") + if resp.status_code >= 400: + raise GitHubError(f"GET {url} -> {resp.status_code}: {resp.text[:200]}") + try: + body = resp.json() + except ValueError as e: + raise GitHubError(f"GET {url} -> {resp.status_code}: body is not JSON") from e + if not isinstance(body, list): + raise GitHubError(f"GET {url} -> expected a JSON array, got {type(body).__name__}") + return [item for item in body if isinstance(item, dict)], _has_next(resp) + + +def _parse_dt(s: str | None) -> datetime | None: + """An RFC 3339 timestamp with any offset as naive UTC.""" + if not s: + return None + dt = datetime.fromisoformat(s.replace("Z", "+00:00")) + if dt.tzinfo is not None: + dt = dt.astimezone(UTC) + return dt.replace(tzinfo=None) + + +async def pr_files(repo: str, token: str, number: int, *, max_pages: int = 12) -> list[str]: + """Changed file paths of one PR (capped at max_pages pages).""" + files: list[str] = [] + for page in range(1, max_pages + 1): + rows, more = await _get_page( + f"{repo}/pulls/{int(number)}/files", token, {"limit": _PAGE_SIZE, "page": page} + ) + files.extend(str(r.get("filename") or "") for r in rows) + if not more: + break + return [f for f in files if f] + + +async def _hydrate_pr( + repo: str, token: str, pr: dict[str, Any], merged: datetime, updated: datetime | None +) -> MergedPR: + return MergedPR( + number=int(pr["number"]), + title=str(pr.get("title") or "")[:500], + body_excerpt=str(pr.get("body") or "")[:2000], + author=str((pr.get("user") or {}).get("login") or ""), + labels=[str(lb.get("name") or "") for lb in pr.get("labels") or []][:20], + merge_commit_sha=str(pr.get("merge_commit_sha") or ""), + merged_at=merged, + updated_at=updated or merged, + opened_at=_parse_dt(pr.get("created_at")), + additions=int(pr.get("additions") or 0), + deletions=int(pr.get("deletions") or 0), + files=await pr_files(repo, token, int(pr["number"])), + assignees=pr_assignees(pr), + body=str(pr.get("body") or ""), + target_branch=pr_base_ref(pr), + ) + + +def _merged_into(pr: dict[str, Any], base: str) -> datetime | None: + """merged_at of a PR merged into `base` ('' = any branch); None otherwise.""" + merged = _parse_dt(pr.get("merged_at")) if pr.get("merged") is not False else None + if merged is None or (base and pr_base_ref(pr) != base): + return None + return merged + + +async def merged_prs_since( + repo: str, + token: str, + since: datetime | None, + *, + max_prs: int = 50, + base: str = "", +) -> list[MergedPR]: + """PRs merged into `base` and updated after `since`, with files, oldest-updated + first: closed PRs newest update first (`sort=recentupdate`), stopping at the first + one at or before `since`, at most 10 pages, as `github.merged_prs_since` walks.""" + collected: list[MergedPR] = [] + page = 1 + while len(collected) < max_prs and page <= 10: + prs, more = await _get_page( + f"{repo}/pulls", + token, + {"state": "closed", "sort": "recentupdate", "limit": _PAGE_SIZE, "page": page}, + ) + drained = False + for pr in prs: + updated = _parse_dt(pr.get("updated_at")) + if since is not None and updated is not None and updated <= since: + drained = True + break + merged = _merged_into(pr, base) + if merged is None: + continue + collected.append(await _hydrate_pr(repo, token, pr, merged, updated)) + if len(collected) >= max_prs: + break + if drained or not more: + break + page += 1 + collected.sort(key=lambda p: p.updated_at) + return collected + + +async def merged_prs_back_to( + repo: str, + token: str, + oldest: datetime, + *, + max_prs: int = 1000, + base: str = "", + start_page: int = 1, + max_pages: int = 20, +) -> tuple[list[MergedPR], int]: + """PRs merged into `base` and closed at or after `oldest`, newest close first + (`sort=recentclose`), from `start_page` on; returns them with the page to resume + at, 0 once the walk reached `oldest` or the last page. A page is read whole, so + `max_prs` is checked between pages and a resume never repeats a PR. The + deep-history backfill: the API has no merged-date search, and close time is merge + time for a merged PR. `sort=recentclose` needs Forgejo 12 or later; older servers + ignore it and answer in creation order.""" + out: list[MergedPR] = [] + page = max(1, start_page) + for _ in range(max_pages): + prs, more = await _get_page( + f"{repo}/pulls", + token, + {"state": "closed", "sort": "recentclose", "limit": _PAGE_SIZE, "page": page}, + ) + for pr in prs: + closed = _parse_dt(pr.get("closed_at")) + if closed is not None and closed < oldest: + return out, 0 + merged = _merged_into(pr, base) + if merged is None: + continue + out.append(await _hydrate_pr(repo, token, pr, merged, _parse_dt(pr.get("updated_at")))) + if not more: + return out, 0 + page += 1 + if len(out) >= max_prs: + return out, page + return out, page diff --git a/server/code/app/bisect_scan.py b/server/code/app/bisect_scan.py index 925f5126a41..b0c7cb03fef 100644 --- a/server/code/app/bisect_scan.py +++ b/server/code/app/bisect_scan.py @@ -11,6 +11,7 @@ from server.code.app.bisect_facts import _MAX_PATHS, IssueFacts, Widening from server.code.app.spans import code_span +from server.code.domain.index.remote import pr_web_url from server.core.datetimes import naive_utc_now_seconds from server.settings import settings from server.tracker.domain import bisect as bi @@ -281,7 +282,7 @@ async def _code_history_rows( "merged_at": r.get("merged_at"), "matched_paths": matched, "affected_file_paths": files, - "url": f"https://github.com/{repo}/pull/{n}" if repo and n else "", + "url": pr_web_url(repo, n), "additions": int(r.get("additions") or 0), "deletions": int(r.get("deletions") or 0), } diff --git a/server/code/domain/index/blame_range.py b/server/code/domain/index/blame_range.py index 55570a4d1e4..54dda7144d3 100644 --- a/server/code/domain/index/blame_range.py +++ b/server/code/domain/index/blame_range.py @@ -26,6 +26,7 @@ from datetime import UTC, datetime from typing import Any +from server.code.domain.index.remote import pr_web_url from server.settings import settings CANDIDATES = "candidates" @@ -605,7 +606,7 @@ def merge_legs( merge_commit_sha=sha, merge_sha_source=("stored" if stored else "mirror") if sha else "", kind=kind_of(title), - url=f"https://github.com/{repo}/pull/{n}" if repo else "", + url=pr_web_url(repo, n), ) ) out.sort(key=lambda c: (-c.lines_blamed, -unix_of(c.merged_at), -c.pr_number)) diff --git a/server/code/domain/index/remote.py b/server/code/domain/index/remote.py index f6970543da5..09b352dd753 100644 --- a/server/code/domain/index/remote.py +++ b/server/code/domain/index/remote.py @@ -164,6 +164,29 @@ def provider_for(remote: str) -> str: return "git" +def forgejo_api_repo(remote: str) -> str: + """`https://[:port]/api/v1/repos//` for a Forgejo remote, HTTPS or + SSH: the API is served over HTTPS on the remote's host. ValueError for a remote that + names no `/`.""" + spec = parse_remote(remote) + owner, _, name = spec.repo.removeprefix(f"{spec.host}/").partition("/") + if not owner or not name or "/" in name: + raise ValueError("a Forgejo remote names /") + port = urlsplit(spec.url).port if spec.url.startswith("https:") else None + return f"https://{spec.host}{f':{port}' if port else ''}/api/v1/repos/{owner}/{name}" + + +def pr_web_url(repo: str, number: int) -> str: + """The web page of pull request `number` of `repo` as configured: GitHub's `/pull/N` + for `owner/name`, Forgejo's `/pulls/N` for `host/owner/name`. '' without a + repository or number.""" + if not repo or not number: + return "" + if "." in repo.split("/", 1)[0]: + return f"https://{repo}/pulls/{number}" + return f"https://github.com/{repo}/pull/{number}" + + def repo_tag(remote: str) -> str: """The `repo:` tag the coding plugins stamp on session memories for this remote: 10 hex of sha256 over `host/owner/name`, lower-cased, with the scheme, user, port and diff --git a/server/code/domain/index/repos.py b/server/code/domain/index/repos.py index 76ccac0cdda..6e3db66eda1 100644 --- a/server/code/domain/index/repos.py +++ b/server/code/domain/index/repos.py @@ -20,7 +20,7 @@ "include_contrib": false, "ignore_file": ".loomignore", "github_token": "", "org_readable": true, "git_extra_branches": "release/*", - "git_proxy_identity": "", + "git_proxy_identity": "", "forge": "", "classification": "standard"}] Missing per-repo fields fall back to the scalar settings, so a second repo only declares @@ -138,6 +138,9 @@ class RepoConfig: # what the fetch may reach and with which credential. '' = the deployment's # settings.code_git_proxy_identity. Not a secret. git_proxy_identity: str = "" + # `forgejo` when the entry's remote is a Forgejo host: its pull requests are then + # read from that host's REST API. '' = the host says (GitHub) or has no PR source. + forge: str = "" @property def label(self) -> str: @@ -156,6 +159,14 @@ def provider(self) -> str: pass return "git" + @property + def pr_source(self) -> str: + """Where the entry's merged-PR history is read from: `github`, `forgejo`, or '' + for a host with no PR source.""" + if self.forge == "forgejo": + return "forgejo" + return "github" if self.provider == "github" else "" + @property def profile(self) -> str: from server.code.domain.index.profiles import profile_for_repo @@ -577,6 +588,7 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC org_readable = False git_dir, git_remote = _entry_clone_fields(e, ns, repo_name, base) proxy_identity = _entry_git_proxy_identity(e, ns, errors) + forge = str(e.get("forge") or "").strip().lower() if proxy_identity is None: continue repos.append( @@ -590,7 +602,10 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC # An entry that names no prefixes indexes its whole tree (the denylist # governs); the scalar's prefixes belong to the scalar entry alone path_prefixes=_prefixes(str(e.get("path_prefixes") or "")) or WHOLE_TREE, - github_token=str(e.get("github_token") or base.github_token), + # The deployment's GitHub token never goes to another forge's host + github_token=str( + e.get("github_token") or ("" if forge == "forgejo" else base.github_token) + ), org_readable=org_readable, classification=classification, public=(bool(e["public"]) if "public" in e else base.public) @@ -622,6 +637,7 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC ), ignore_file=(str(e["ignore_file"]) if "ignore_file" in e else base.ignore_file), git_proxy_identity=proxy_identity, + forge=forge, ) ) if not repos: diff --git a/server/code/workers/pr_history.py b/server/code/workers/pr_history.py index e6a6d65eca3..c5715343e77 100644 --- a/server/code/workers/pr_history.py +++ b/server/code/workers/pr_history.py @@ -1,4 +1,4 @@ -"""Merged-PR history sync from the GitHub REST API (cursor-resumable). +"""Merged-PR history sync from the GitHub REST API, or a Forgejo host's (cursor-resumable). Keeps `loom.code_pr_history` current so code.history / code.examples / context packs can rank by ownership and recency. The cursor is the max @@ -83,7 +83,7 @@ async def _run(result: CodePrHistoryResult) -> None: nxt = repos[i + 1] if i + 1 < len(repos) else configured[0] pass_context.set_cursor(nxt.namespace) pass_context.set_namespace(cfg.namespace) - if cfg.provider != "github": + if not cfg.pr_source: result.note = f"PR history is not available for {cfg.provider} remotes" continue try: @@ -91,8 +91,9 @@ async def _run(result: CodePrHistoryResult) -> None: result.note = f"{cfg.label}: no git_head watermark yet; run `loom code backfill`" continue await _sync_repo(cfg, repo, result) - await _sync_items(cfg, repo, result) - await _fill_pr_heads(cfg, repo, result) + if cfg.pr_source == "github": # issues, PR heads and reviews are GitHub's alone + await _sync_items(cfg, repo, result) + await _fill_pr_heads(cfg, repo, result) except Exception as e: result.errors.append(f"{cfg.label}: {type(e).__name__}: {e}") logger.exception("code_pr_history: repo %s failed", cfg.label) @@ -151,12 +152,29 @@ async def pr_rows(repo: Any, org: str, ns: str, prs: list[Any]) -> list[dict[str ] +async def _merged_prs(cfg: Any, since: datetime) -> list[Any]: + """The PRs merged into the entry's branch since `since`, from its PR source.""" + if cfg.pr_source == "forgejo": + from server.clients import forgejo + from server.code.domain.index.remote import forgejo_api_repo + + api = forgejo_api_repo(cfg.git_remote) + return await forgejo.merged_prs_since( + api, cfg.github_token, since, max_prs=40, base=cfg.git_branch + ) + from server.clients.github import merged_prs_since + + return await merged_prs_since( + cfg.repo, cfg.github_token, since, max_prs=40, base=cfg.git_branch + ) + + async def _sync_repo(cfg: Any, repo: Any, result: CodePrHistoryResult) -> None: global _warned_no_token - from server.clients.github import GitHubError, RateLimited, merged_prs_since + from server.clients.github import GitHubError, RateLimited token = cfg.github_token - if not token: + if not token and cfg.pr_source == "github": # Public repos read fine anonymously (60 req/h shared per IP; one # pass is ~1 request). A private repo 404s and lands in errors — # the operator sees it on the Health tab instead of a silent no-op. @@ -180,14 +198,16 @@ async def _sync_repo(cfg: Any, repo: Any, result: CodePrHistoryResult) -> None: try: # Only PRs merged INTO this entry's branch: a release-branch namespace # is about its backports, not master's firehose. - prs = await merged_prs_since(cfg.repo, token, since, max_prs=40, base=cfg.git_branch) + prs = await _merged_prs(cfg, since) except RateLimited as e: result.note = f"rate limited: {e}" return except GitHubError as e: # Logged as well as counted: a private repo 404ing or a revoked token # would otherwise show only as a count on the Health tab. - logger.warning("code_pr_history: %s github error (cursor kept): %s", cfg.label, e) + logger.warning( + "code_pr_history: %s %s error (cursor kept): %s", cfg.label, cfg.pr_source, e + ) result.errors.append(f"{cfg.label}: {e}") return @@ -199,7 +219,7 @@ async def _sync_repo(cfg: Any, repo: Any, result: CodePrHistoryResult) -> None: pass_context.check_stop() # after the GitHub reads: a lost lease writes nothing await repo.insert_rows("code_pr_history", rows) result.prs_upserted = len(rows) - if token and settings.code_pr_reviews_enabled: + if token and settings.code_pr_reviews_enabled and cfg.pr_source == "github": result.reviews_upserted += await _sync_reviews( cfg, repo, org, ns, [pr.number for pr in prs] ) diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 1c941424ea8..a0ad9d144db 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1372,7 +1372,8 @@ def _check_git_proxy(self) -> CodeSettings: code_scip_go_private: str = "" # --- PR history --- - # Merged-PR history sync (GitHub REST, cursor-resumable). + # Merged-PR history sync (GitHub REST, or the REST API of a Forgejo host; + # cursor-resumable). code_pr_history_enabled: bool = False # Seconds between PR-history sync passes. code_pr_history_interval_seconds: int = 900 diff --git a/tests/unit/fixtures/README.md b/tests/unit/fixtures/README.md index 4292e9e96e4..435abee29f8 100644 --- a/tests/unit/fixtures/README.md +++ b/tests/unit/fixtures/README.md @@ -17,6 +17,7 @@ or credential-shaped strings. | `loom_search_mcp_answers.json` | `test_loom_search_mcp_render.py` | golden output | object | The MCP `loom_search` answer (text block and structured result) and the fan-out call it made, per scenario, for a fixed payload. Rendered by the product code. Regenerate with `python -m tests.unit.test_loom_search_mcp_render --write` only when the rendering changes on purpose. | | `prompt_golden.json` | `test_prompt_blocks.py` | golden output | list | The strong synthesis prompt, per scenario (`name`, `system`, `user`), from before block accounting existed: accounting must not move a byte. Regenerate with `python -m tests.unit.test_prompt_blocks --capture` only when the prompt changes on purpose. | | `bisect_fusion_cases.json` | `test_bisect_fusion.py` | held-out input cases | list | Three frozen regression reports from the public ClickHouse issue tracker, each with the candidate rows, paths, vector order and known culprit PR. Hand-curated, with no generator. Adding a case is a new held-out case, never a relabel of an existing one. | +| `forgejo_pull_requests.json` | `test_forgejo_pr_source.py` | recorded API replies | object | Replies of a public Forgejo server's REST API (closed PRs by recent update and by recent close, and one PR's changed files), cut to the fields the client reads, logins replaced by neutral names, bodies shortened and links removed. Recorded read-only by hand; re-record only when the client reads a new field. | | `durable_facts.json` | `test_durable_facts.py` | labelled input corpus | object | Synthetic facts shaped like a coding session's SessionEnd extraction, labelled `real` / junk-by-class. Hand-written, with no generator. | | `section_values.json` | `test_section_value.py` | labelled input corpus | object | Synthetic document sections (design docs, meeting notes, status reports, templates), labelled `design` / `noise` with a kind, in a `dev` half the rules were written from and a `held_out` half they were not written from but whose scores were checked after each rule fix, so it no longer measures the rules blind; the test pins both halves' scores. Written once by a writer who did not see the rules, with no generator. A fresh held-out half replaces this one before the rules are tuned again. | diff --git a/tests/unit/fixtures/forgejo_pull_requests.json b/tests/unit/fixtures/forgejo_pull_requests.json new file mode 100644 index 00000000000..3f11fe28a1c --- /dev/null +++ b/tests/unit/fixtures/forgejo_pull_requests.json @@ -0,0 +1,557 @@ +{ + "pull_files": [ + { + "additions": 10, + "deletions": 0, + "filename": "docs/contributor/customization.md", + "previous_filename": null, + "status": "changed" + } + ], + "pulls_closed_recentclose": [ + { + "additions": 0, + "assignees": [], + "base": { + "ref": "next", + "sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4" + }, + "body": "As per [Drew's blogpost](, redict is now deprecated. The project recommendation is to migrate to Valkey, which we already have listed as one of the al", + "changed_files": 0, + "closed_at": "2026-11-27T01:18:58+01:00", + "created_at": "2026-11-26T23:30:02+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/2290/head", + "sha": "299b83a1e63e4304aa161098f4f4d977fdf97000" + }, + "labels": [], + "merge_base": "b013e04e2d69a3ed94ab2889f06d07a00e173bad", + "merge_commit_sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4", + "merged": true, + "merged_at": "2026-11-27T01:18:58+01:00", + "number": 2290, + "requested_reviewers": [ + { + "login": "grace" + } + ], + "state": "closed", + "title": "Remove redict from recommendation page", + "updated_at": "2026-11-27T01:19:09+01:00", + "user": { + "login": "frank" + } + }, + { + "additions": 10, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "Following this [PR]( I think its useful to have an example of the path and an a description of the actual behavior.", + "changed_files": 1, + "closed_at": "2026-11-26T14:28:29+01:00", + "created_at": "2026-10-14T16:51:20+02:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "feature/locale-loading", + "sha": "bb4a691912b2faece47c0a796a47b889bc00d139" + }, + "labels": [], + "merge_base": "6b64d95baa0d775f46fb872e16d88e8aad8f9b13", + "merge_commit_sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad", + "merged": true, + "merged_at": "2026-11-26T14:28:29+01:00", + "number": 2231, + "requested_reviewers": [ + { + "login": "alice" + } + ], + "state": "closed", + "title": "Add docs for custom locale loading", + "updated_at": "2026-11-26T14:28:30+01:00", + "user": { + "login": "bob" + } + }, + { + "additions": 6, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "For a future PR", + "changed_files": 1, + "closed_at": "2026-11-26T13:32:33+01:00", + "created_at": "2026-11-15T02:59:37+01:00", + "deletions": 5, + "draft": true, + "head": { + "ref": "feature/merged-filter", + "sha": "8326ed0cbac4ea898cc0b8ba11a57fd478aaf06c" + }, + "labels": [], + "merge_base": "78fdf01ae6f06c0beae28c39a9f7138d0ed25c46", + "merge_commit_sha": null, + "merged": false, + "merged_at": null, + "number": 2277, + "requested_reviewers": [], + "state": "closed", + "title": "WIP: docs: add is:merged/unmerged to filters", + "updated_at": "2026-11-26T13:32:33+01:00", + "user": { + "login": "carol" + } + }, + { + "additions": 0, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "As v19 LTS starts to pop up in discussions of deprecation, it seemed prudent to extend the future release schedule a bit. This maintains quarterly releases with", + "changed_files": 0, + "closed_at": "2026-11-26T03:42:52+01:00", + "created_at": "2026-11-21T03:16:01+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/2285/head", + "sha": "8cf797ad786e1b15d81b3192e22397e51fcfb97f" + }, + "labels": [], + "merge_base": "838ac8f1b58670726023754dfbf2a4ff49f2c494", + "merge_commit_sha": "9e47968acab7556fd4179982e71d7297b68b3133", + "merged": true, + "merged_at": "2026-11-26T03:42:52+01:00", + "number": 2285, + "requested_reviewers": [ + { + "login": "dave" + } + ], + "state": "closed", + "title": "chore: extend release schedule by 1 year", + "updated_at": "2026-11-26T03:42:54+01:00", + "user": { + "login": "erin" + } + }, + { + "additions": 6, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "This PR contains the following updates: | Package | Change | [Age]( | [Confidence]( | |---|---|---|---| | [lint-staged]( | [`17.6.1` → `17.6.2`]( | ![age]( | ![", + "changed_files": 2, + "closed_at": "2026-11-26T00:10:14+01:00", + "created_at": "2026-11-26T00:04:58+01:00", + "deletions": 6, + "draft": false, + "head": { + "ref": "refs/pull/2288/head", + "sha": "966499fcaebf82a115a44fd8aae62bc04fde3b36" + }, + "labels": [], + "merge_base": "d596d9d0f7170482756f03a8053295869aeb6bf7", + "merge_commit_sha": "ed5df4e37d977b4c32aea32fa3acd5a5e02258d6", + "merged": true, + "merged_at": "2026-11-26T00:10:14+01:00", + "number": 2288, + "requested_reviewers": [ + { + "login": "alice" + } + ], + "state": "closed", + "title": "Update dependency lint-staged to v17.6.2", + "updated_at": "2026-11-26T00:10:17+01:00", + "user": { + "login": "frank" + } + }, + { + "additions": 77, + "assignees": [], + "base": { + "ref": "next", + "sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4" + }, + "body": "This PR contains the following updates:\n\n| Update | Change |\n|---|---|\n| lockFileMaintenance | All locks refreshed |\n\n🔧 This Pull Request updates lock", + "changed_files": 1, + "closed_at": "2026-11-23T11:06:37+01:00", + "created_at": "2026-11-23T00:04:11+01:00", + "deletions": 251, + "draft": false, + "head": { + "ref": "refs/pull/2287/head", + "sha": "94742f3cb0d6ac0d707a2f5a3cb63c14a4a3e98a" + }, + "labels": [], + "merge_base": "b5c1cf04195f1953987ee97c84b2b1ae895530a9", + "merge_commit_sha": "d596d9d0f7170482756f03a8053295869aeb6bf7", + "merged": true, + "merged_at": "2026-11-23T11:06:37+01:00", + "number": 2287, + "requested_reviewers": [ + { + "login": "ivan" + } + ], + "state": "closed", + "title": "Lock file maintenance", + "updated_at": "2026-11-23T11:07:49+01:00", + "user": { + "login": "heidi" + } + }, + { + "additions": 0, + "assignees": [], + "base": { + "ref": "next", + "sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4" + }, + "body": "MariaDB 10.6, and PostgreSQL 14, are no longer supported by their upstream maintainers, and so we'll remove support for them from Forgejo as well. We", + "changed_files": 0, + "closed_at": "2026-11-23T01:25:36+01:00", + "created_at": "2026-11-21T22:36:46+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/2286/head", + "sha": "6a60262d6e30e276d742f0a9c9b21e15e727d4dc" + }, + "labels": [], + "merge_base": "838ac8f1b58670726023754dfbf2a4ff49f2c494", + "merge_commit_sha": "b5c1cf04195f1953987ee97c84b2b1ae895530a9", + "merged": true, + "merged_at": "2026-11-23T01:25:36+01:00", + "number": 2286, + "requested_reviewers": [ + { + "login": "judy" + } + ], + "state": "closed", + "title": "chore: update supported databases", + "updated_at": "2026-11-23T01:26:19+01:00", + "user": { + "login": "grace" + } + }, + { + "additions": 2, + "assignees": [], + "base": { + "ref": "v17.0", + "sha": "94ae52ce478342ec468f9174d35fcd28cc238c8b" + }, + "body": "**Backport:** \r\n\r\nAdd missing directives, related to ", + "changed_files": 1, + "closed_at": "2026-11-19T13:25:18+01:00", + "created_at": "2026-11-19T09:48:47+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/2284/head", + "sha": "a4c347ad6f7e23c0a4ad093ea72554e7e90940e9" + }, + "labels": [], + "merge_base": "b8f247bf96233d1351e2d781afeca2187b26ceb8", + "merge_commit_sha": "94ae52ce478342ec468f9174d35fcd28cc238c8b", + "merged": true, + "merged_at": "2026-11-19T13:25:18+01:00", + "number": 2284, + "requested_reviewers": [ + { + "login": "ivan" + }, + { + "login": "liam" + } + ], + "state": "closed", + "title": "[v17.0] cheat-sheet: Add missing *_KEYS_ACCEPTED directives", + "updated_at": "2026-11-19T13:25:30+01:00", + "user": { + "login": "karl" + } + }, + { + "additions": 2, + "assignees": [], + "base": { + "ref": "next", + "sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4" + }, + "body": "Add missing directives, related to ", + "changed_files": 1, + "closed_at": "2026-11-19T09:47:50+01:00", + "created_at": "2026-11-18T19:15:49+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "add.missing.ID_TOKEN_KEYS_ACCEPTED", + "sha": "931ae4e881edbdcede1c6c727681baf39db0fc88" + }, + "labels": [ + { + "name": "backport/v17.0" + } + ], + "merge_base": "18ce22339c5d06920530000f672b673cf2d6ec74", + "merge_commit_sha": "838ac8f1b58670726023754dfbf2a4ff49f2c494", + "merged": true, + "merged_at": "2026-11-19T09:47:50+01:00", + "number": 2281, + "requested_reviewers": [ + { + "login": "ivan" + } + ], + "state": "closed", + "title": "cheat-sheet: Add missing *_KEYS_ACCEPTED directives", + "updated_at": "2026-11-19T13:25:21+01:00", + "user": { + "login": "liam" + } + }, + { + "additions": 33, + "assignees": [], + "base": { + "ref": "next", + "sha": "10c0d0c6eb4c7794fc4f1c41354f9b6cf648b3a4" + }, + "body": "I noticed the `.volume` was missing in the container file for the podman quadlet example. I have made this mistake before and was hoping to stop a few", + "changed_files": 1, + "closed_at": "2026-10-26T16:48:52+01:00", + "created_at": "2026-10-26T00:10:13+01:00", + "deletions": 30, + "draft": false, + "head": { + "ref": "next", + "sha": "03e738f779025dcd6613774131dab219cec890dc" + }, + "labels": [ + { + "name": "backport/v15.0" + }, + { + "name": "backport/v17.0" + } + ], + "merge_base": "65faeb1c07bbc43cbc3ac32aef19a7671500dd78", + "merge_commit_sha": "54a3d8656a1f60b86aef33659ae8334bfe099529", + "merged": true, + "merged_at": "2026-10-26T16:48:52+01:00", + "number": 2251, + "requested_reviewers": [ + { + "login": "ivan" + } + ], + "state": "closed", + "title": "update docker.md to properly utilize the forgejo-data.volume file for podman", + "updated_at": "2026-11-16T18:08:33+01:00", + "user": { + "login": "mona" + } + } + ], + "pulls_closed_recentupdate": [ + { + "additions": 10, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "Following this [PR]( I think its useful to have an example of the path and an a description of the actual behavior.", + "changed_files": 1, + "closed_at": "2026-11-26T14:28:29+01:00", + "created_at": "2026-10-14T16:51:20+02:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "feature/locale-loading", + "sha": "bb4a691912b2faece47c0a796a47b889bc00d139" + }, + "labels": [], + "merge_base": "6b64d95baa0d775f46fb872e16d88e8aad8f9b13", + "merge_commit_sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad", + "merged": true, + "merged_at": "2026-11-26T14:28:29+01:00", + "number": 2231, + "requested_reviewers": [ + { + "login": "alice" + } + ], + "state": "closed", + "title": "Add docs for custom locale loading", + "updated_at": "2026-11-26T14:28:30+01:00", + "user": { + "login": "bob" + } + }, + { + "additions": 6, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "For a future PR", + "changed_files": 1, + "closed_at": "2026-11-26T13:32:33+01:00", + "created_at": "2026-11-15T02:59:37+01:00", + "deletions": 5, + "draft": true, + "head": { + "ref": "feature/merged-filter", + "sha": "8326ed0cbac4ea898cc0b8ba11a57fd478aaf06c" + }, + "labels": [], + "merge_base": "78fdf01ae6f06c0beae28c39a9f7138d0ed25c46", + "merge_commit_sha": null, + "merged": false, + "merged_at": null, + "number": 2277, + "requested_reviewers": [], + "state": "closed", + "title": "WIP: docs: add is:merged/unmerged to filters", + "updated_at": "2026-11-26T13:32:33+01:00", + "user": { + "login": "carol" + } + }, + { + "additions": 0, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "As v19 LTS starts to pop up in discussions of deprecation, it seemed prudent to extend the future release schedule a bit. This maintains quarterly releases with", + "changed_files": 0, + "closed_at": "2026-11-26T03:42:52+01:00", + "created_at": "2026-11-21T03:16:01+01:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/2285/head", + "sha": "8cf797ad786e1b15d81b3192e22397e51fcfb97f" + }, + "labels": [], + "merge_base": "838ac8f1b58670726023754dfbf2a4ff49f2c494", + "merge_commit_sha": "9e47968acab7556fd4179982e71d7297b68b3133", + "merged": true, + "merged_at": "2026-11-26T03:42:52+01:00", + "number": 2285, + "requested_reviewers": [ + { + "login": "dave" + } + ], + "state": "closed", + "title": "chore: extend release schedule by 1 year", + "updated_at": "2026-11-26T03:42:54+01:00", + "user": { + "login": "erin" + } + }, + { + "additions": 6, + "assignees": [], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "This PR contains the following updates: | Package | Change | [Age]( | [Confidence]( | |---|---|---|---| | [lint-staged]( | [`17.6.1` → `17.6.2`]( | ![age]( | ![", + "changed_files": 2, + "closed_at": "2026-11-26T00:10:14+01:00", + "created_at": "2026-11-26T00:04:58+01:00", + "deletions": 6, + "draft": false, + "head": { + "ref": "refs/pull/2288/head", + "sha": "966499fcaebf82a115a44fd8aae62bc04fde3b36" + }, + "labels": [], + "merge_base": "d596d9d0f7170482756f03a8053295869aeb6bf7", + "merge_commit_sha": "ed5df4e37d977b4c32aea32fa3acd5a5e02258d6", + "merged": true, + "merged_at": "2026-11-26T00:10:14+01:00", + "number": 2288, + "requested_reviewers": [ + { + "login": "alice" + } + ], + "state": "closed", + "title": "Update dependency lint-staged to v17.6.2", + "updated_at": "2026-11-26T00:10:17+01:00", + "user": { + "login": "frank" + } + }, + { + "additions": 0, + "assignees": [ + { + "login": "grace" + } + ], + "base": { + "ref": "next", + "sha": "b013e04e2d69a3ed94ab2889f06d07a00e173bad" + }, + "body": "And how it must be set when using the matrix strategy.", + "changed_files": 0, + "closed_at": "2025-08-11T23:11:41+02:00", + "created_at": "2025-08-11T21:57:41+02:00", + "deletions": 0, + "draft": false, + "head": { + "ref": "refs/pull/1379/head", + "sha": "3b2dbc246edaaa66fb0b2bdf61c261be678260ab" + }, + "labels": [ + { + "name": "backport/v12.0" + } + ], + "merge_base": "a4d2e3e85491c566a9d80246ed6f2f7eb38c5ac5", + "merge_commit_sha": "427cbbedcb2e98b7a56d65ff3786f135a878b809", + "merged": true, + "merged_at": "2025-08-11T23:11:42+02:00", + "number": 1379, + "requested_reviewers": [ + { + "login": "alice" + }, + { + "login": "heidi" + } + ], + "state": "closed", + "title": "user: actions: add `jobs..name`", + "updated_at": "2026-11-24T00:59:06+01:00", + "user": { + "login": "grace" + } + } + ] +} diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index 7ce07e3261c..af1394c6c7a 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -7,7 +7,7 @@ ], "loom code": [ "usage: loom code [-h] {init,backfill,reconcile,compact,reembed,vector-twin,crossref,coverage-import,export-pairs,backfill-prs,repack,describe,answers-purge,scip-full,scip-lock-path,entry-lock,scip-delta,entries,warm,scip-retry,backfill-reviews,backfill-assignees,backfill-items,stats,export-matrix,lint-instructions} ...", - "positional arguments: {init,backfill,reconcile,compact,reembed,vector-twin,crossref,coverage-import,export-pairs,backfill-prs,repack,describe,answers-purge,scip-full,scip-lock-path,entry-lock,scip-delta,entries,warm,scip-retry,backfill-reviews,backfill-assignees,backfill-items,stats,export-matrix,lint-instructions} init Create the bare clone + seed state. backfill Full-tree indexing (resumable). reconcile Content-based staleness check: paths whose chunks predate their last change at the branch head; --heal re-ingests them (watermark untouched). compact OPTIMIZE ... FINAL a code vector table when its physical copies per key reach --min-ratio, and wait for the merge. Dry run by default (measures the ratio); --apply optimizes. reembed Write the namespace's live chunks under a second embedding model's label: in-database, resumable, no checkout. vector-twin Fill a namespace's Matryoshka-prefix twin of the chunk vectors inside ClickHouse: no re-embed, resumable. crossref SQL/shell test -> implementing C++ reference pass (writes code_test_map method=content_reference; idempotent). coverage-import Import the newest per-test line coverage run of the configured source (writes code_test_map method=coverage and code_coverage_files). export-pairs Export (query -> acted-on unit, hard negatives) retrieval pairs from real traffic (trace x outcome join) for embedder/reranker fine-tuning. backfill-prs Merged-PR history from GitHub. repack Regenerate context packs for recently merged PRs in the current pack shape. describe LLM contextual one-liners for top-PageRank chunks. answers-purge Tombstone cached code.ask answers (after a synthesis-model upgrade, stale weaker-model answers would otherwise be served forever — the cache only self-invalidates on cited-file change). Dry run by default (counts and samples the matches); --apply tombstones. scip-full Full compiler-tier re-index by hand (the code_scip_full worker runs it weekly by default: heals the TU-cap degrades of per-merge deltas and any drift). Heavy: ~50 min of scip-clang + apply, on this host rather than in the server. scip-lock-path Print the entry's compiler-tier lock file on this host. A manual harness run goes under `loom code entry-lock`, which takes this file and the deployment lease; scip-full and scip-delta take both themselves. entry-lock Run a command under the entry's compiler-tier lock (this host's file and the deployment's lease): exit 75 when another pass holds it, 3 when the lease is lost mid-run (the command is stopped). scip-delta One compiler-tier delta pass (same code as the code_scip_delta worker), by hand: git_head vs scip_commit per configured repo, scip-clang over the changed TUs, apply. Prints `RESULT: ...`. entries One line per configured repository: org namespace checkout lock-file (the lock path resolved; a manual run takes it through `loom code entry-lock`). warm Pre-seed the code.ask answer cache from a question list (one question per line, or JSONL with a 'question' field). Each miss pays one synthesis; every future asker fleet-wide gets the cached answer. Safe to re-run: hits are free. scip-retry Reset a failed SCIP batch to pending. backfill-reviews Inline review comments for merged PRs already in code_pr_history that have none stored yet (newest first, one GitHub request per PR). backfill-assignees Fill code_pr_history.assignees (who the repo assigned to review) for merged PRs already stored, walking the newest closed PRs 100 per request. backfill-items Fill code_gh_items (issues + PRs, any state) updated since a date, 100 per request, oldest update first; moves gh_items_cursor. stats Watermarks + live row counts. export-matrix Maintenance matrix from merged-PR co-change: 'when this file changes, these usually change too', with evidence, as markdown for an instructions file (AGENTS.md / copilot-instructions.md). lint-instructions Agent-instruction files (CLAUDE.md, AGENTS.md, copilot-instructions, .claude/**.md, skills) whose path or symbol references no longer resolve at the clone's head.", + "positional arguments: {init,backfill,reconcile,compact,reembed,vector-twin,crossref,coverage-import,export-pairs,backfill-prs,repack,describe,answers-purge,scip-full,scip-lock-path,entry-lock,scip-delta,entries,warm,scip-retry,backfill-reviews,backfill-assignees,backfill-items,stats,export-matrix,lint-instructions} init Create the bare clone + seed state. backfill Full-tree indexing (resumable). reconcile Content-based staleness check: paths whose chunks predate their last change at the branch head; --heal re-ingests them (watermark untouched). compact OPTIMIZE ... FINAL a code vector table when its physical copies per key reach --min-ratio, and wait for the merge. Dry run by default (measures the ratio); --apply optimizes. reembed Write the namespace's live chunks under a second embedding model's label: in-database, resumable, no checkout. vector-twin Fill a namespace's Matryoshka-prefix twin of the chunk vectors inside ClickHouse: no re-embed, resumable. crossref SQL/shell test -> implementing C++ reference pass (writes code_test_map method=content_reference; idempotent). coverage-import Import the newest per-test line coverage run of the configured source (writes code_test_map method=coverage and code_coverage_files). export-pairs Export (query -> acted-on unit, hard negatives) retrieval pairs from real traffic (trace x outcome join) for embedder/reranker fine-tuning. backfill-prs Merged-PR history from GitHub or a Forgejo host. repack Regenerate context packs for recently merged PRs in the current pack shape. describe LLM contextual one-liners for top-PageRank chunks. answers-purge Tombstone cached code.ask answers (after a synthesis-model upgrade, stale weaker-model answers would otherwise be served forever — the cache only self-invalidates on cited-file change). Dry run by default (counts and samples the matches); --apply tombstones. scip-full Full compiler-tier re-index by hand (the code_scip_full worker runs it weekly by default: heals the TU-cap degrades of per-merge deltas and any drift). Heavy: ~50 min of scip-clang + apply, on this host rather than in the server. scip-lock-path Print the entry's compiler-tier lock file on this host. A manual harness run goes under `loom code entry-lock`, which takes this file and the deployment lease; scip-full and scip-delta take both themselves. entry-lock Run a command under the entry's compiler-tier lock (this host's file and the deployment's lease): exit 75 when another pass holds it, 3 when the lease is lost mid-run (the command is stopped). scip-delta One compiler-tier delta pass (same code as the code_scip_delta worker), by hand: git_head vs scip_commit per configured repo, scip-clang over the changed TUs, apply. Prints `RESULT: ...`. entries One line per configured repository: org namespace checkout lock-file (the lock path resolved; a manual run takes it through `loom code entry-lock`). warm Pre-seed the code.ask answer cache from a question list (one question per line, or JSONL with a 'question' field). Each miss pays one synthesis; every future asker fleet-wide gets the cached answer. Safe to re-run: hits are free. scip-retry Reset a failed SCIP batch to pending. backfill-reviews Inline review comments for merged PRs already in code_pr_history that have none stored yet (newest first, one GitHub request per PR). backfill-assignees Fill code_pr_history.assignees (who the repo assigned to review) for merged PRs already stored, walking the newest closed PRs 100 per request. backfill-items Fill code_gh_items (issues + PRs, any state) updated since a date, 100 per request, oldest update first; moves gh_items_cursor. stats Watermarks + live row counts. export-matrix Maintenance matrix from merged-PR co-change: 'when this file changes, these usually change too', with evidence, as markdown for an instructions file (AGENTS.md / copilot-instructions.md). lint-instructions Agent-instruction files (CLAUDE.md, AGENTS.md, copilot-instructions, .claude/**.md, skills) whose path or symbol references no longer resolve at the clone's head.", "options: -h, --help show this help message and exit" ], "loom code init": [ diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 7c6ea36f19c..0d5bfd7d9fd 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -3307,7 +3307,7 @@ }, { "dest": "backfill-prs", - "help": "Merged-PR history from GitHub.", + "help": "Merged-PR history from GitHub or a Forgejo host.", "metavar": "backfill-prs" }, { diff --git a/tests/unit/test_code_worker_failures_are_noted.py b/tests/unit/test_code_worker_failures_are_noted.py index 84b121ced2f..d87f9c0bd22 100644 --- a/tests/unit/test_code_worker_failures_are_noted.py +++ b/tests/unit/test_code_worker_failures_are_noted.py @@ -23,6 +23,7 @@ class _Cfg: label = "o/code-x" repo = "Org/Repo" provider = "github" + pr_source = "github" github_token = "tok" git_dir = "" source = "config" diff --git a/tests/unit/test_forgejo_pr_source.py b/tests/unit/test_forgejo_pr_source.py new file mode 100644 index 00000000000..95d71597d28 --- /dev/null +++ b/tests/unit/test_forgejo_pr_source.py @@ -0,0 +1,379 @@ +"""Merged-PR history from a Forgejo host. + +An entry whose `forge` is `forgejo` reads its pull requests from the host's REST API; +the client maps them onto the GitHub client's `MergedPR`, so the worker writes the same +`code_pr_history` rows from either source. The responses replayed here are recorded ones +(`fixtures/forgejo_pull_requests.json`). CH-free. +""" + +from __future__ import annotations + +import json +from datetime import datetime +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock, patch + +import httpx +import pytest + +from server.clients import forgejo +from server.clients.github import GitHubError, RateLimited +from server.code.domain.index import repos as r +from server.code.domain.index.remote import forgejo_api_repo, pr_web_url +from server.settings import settings +from tests.unit.code_fixtures import repo_config + +FIXTURE = json.loads( + (Path(__file__).parent / "fixtures" / "forgejo_pull_requests.json").read_text() +) +API = "https://forgejo.example.org/api/v1/repos/acme/widgets" +REMOTE = "https://forgejo.example.org/acme/widgets.git" + + +# ---- choosing the source ----------------------------------------------------------- + + +def test_pr_source_is_github_for_github_and_forgejo_only_when_the_entry_says_so() -> None: + assert repo_config(repo="acme/widgets").pr_source == "github" + assert repo_config(git_remote="https://github.com/acme/widgets.git").pr_source == "github" + assert repo_config(git_remote=REMOTE).pr_source == "" + assert repo_config(git_remote=REMOTE, forge="forgejo").pr_source == "forgejo" + + +def test_entry_forge_key_is_read(monkeypatch: pytest.MonkeyPatch) -> None: + entries = [ + { + "org": "o", + "namespace": "code-a", + "repo": "forgejo.example.org/acme/widgets", + "git_remote": REMOTE, + "git_branch": "main", + "forge": " Forgejo ", + }, + {"org": "o", "namespace": "code-b", "repo": "acme/other", "git_branch": "main"}, + ] + monkeypatch.setattr(settings, "code_repos_json", json.dumps(entries)) + forge, plain = r.configured_repos() + assert (forge.forge, forge.pr_source) == ("forgejo", "forgejo") + assert (plain.forge, plain.pr_source) == ("", "github") + + +def test_a_forgejo_entry_never_inherits_the_deployment_github_token( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(settings, "code_github_token", "deploy-token") + host = {"org": "o", "repo": "forgejo.example.org/acme/widgets", "git_remote": REMOTE} + entries = [ + {**host, "namespace": "code-a", "git_branch": "main", "forge": "forgejo"}, + {**host, "namespace": "code-b", "forge": "forgejo", "github_token": "host-token"}, + {"org": "o", "namespace": "code-c", "repo": "acme/other", "git_branch": "main"}, + ] + monkeypatch.setattr(settings, "code_repos_json", json.dumps(entries)) + own, named, github = r.configured_repos() + assert (own.github_token, named.github_token) == ("", "host-token") + assert github.github_token == "deploy-token" + plain = {**host, "namespace": "code-d", "forge": "github"} + monkeypatch.setattr(settings, "code_repos_json", json.dumps([plain])) + assert r.configured_repos()[0].github_token == "deploy-token" + + +@pytest.mark.asyncio +async def test_a_forgejo_request_carries_no_github_token(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(settings, "code_github_token", "deploy-token") + entry = { + "org": "o", + "namespace": "code-a", + "repo": "forgejo.example.org/acme/widgets", + "git_remote": REMOTE, + "git_branch": "main", + "forge": "forgejo", + } + monkeypatch.setattr(settings, "code_repos_json", json.dumps([entry])) + (cfg,) = r.configured_repos() + calls: list[httpx.Request] = [] + with patch.object(forgejo, "get_client", return_value=_replay({"/pulls": []}, calls)): + await forgejo.merged_prs_since(forgejo_api_repo(cfg.git_remote), cfg.github_token, None) + assert calls and all("Authorization" not in c.headers for c in calls) + + +@pytest.mark.parametrize( + ("remote", "api"), + [ + (REMOTE, API), + ("git@forgejo.example.org:acme/widgets.git", API), + ("ssh://git@forgejo.example.org:2222/acme/widgets.git", API), + ( + "https://forgejo.example.org:8443/acme/widgets.git", + "https://forgejo.example.org:8443/api/v1/repos/acme/widgets", + ), + ], +) +def test_api_url_is_https_on_the_remote_host(remote: str, api: str) -> None: + assert forgejo_api_repo(remote) == api + + +def test_api_url_needs_an_owner_and_a_repository() -> None: + with pytest.raises(ValueError, match="owner"): + forgejo_api_repo("https://forgejo.example.org/widgets") + + +def test_pr_web_url_per_host() -> None: + assert pr_web_url("acme/widgets", 7) == "https://github.com/acme/widgets/pull/7" + assert ( + pr_web_url("forgejo.example.org/acme/widgets", 7) + == "https://forgejo.example.org/acme/widgets/pulls/7" + ) + assert pr_web_url("", 7) == "" and pr_web_url("acme/widgets", 0) == "" + + +# ---- the client over recorded responses -------------------------------------------- + + +def _replay(routes: dict[str, Any], calls: list[httpx.Request]) -> httpx.AsyncClient: + """A client answering each path from `routes` (a page of a list as `path?page=N`, + else the bare path): a body (200), or (status, body, headers).""" + + def handler(request: httpx.Request) -> httpx.Response: + calls.append(request) + key = request.url.path.removeprefix("/api/v1/repos/acme/widgets") + page = request.url.params.get("page", "1") + answer = routes.get(f"{key}?page={page}", routes.get(key)) + if answer is None: + return httpx.Response(404, json={"message": "The target couldn't be found."}) + if isinstance(answer, tuple): + status, body, headers = answer + return httpx.Response(status, json=body, headers=headers) + return httpx.Response(200, json=answer) + + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +def _no_files(pulls: list[dict[str, Any]]) -> dict[str, Any]: + """An empty file list for every recorded PR (the recording kept one PR's files).""" + return {f"/pulls/{p['number']}/files": [] for p in pulls} + + +def _next_link(path: str, page: int) -> dict[str, str]: + return {"Link": f'<{API}{path}?page={page}>; rel="next"'} + + +@pytest.mark.asyncio +async def test_merged_prs_since_filters_the_base_branch_and_reads_files_in_utc() -> None: + pulls = FIXTURE["pulls_closed_recentupdate"] + calls: list[httpx.Request] = [] + routes: dict[str, Any] = { + **_no_files(pulls), + "/pulls?page=1": (200, pulls, _next_link("/pulls", 2)), + "/pulls?page=2": [], + "/pulls/2231/files": FIXTURE["pull_files"], + } + with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): + prs = await forgejo.merged_prs_since(API, "tok", None, max_prs=50, base="next") + # 2277 was closed without merging; the others merged into `next`. + expected = {p["number"] for p in pulls if p["merged"] and p["base"]["ref"] == "next"} + assert 2277 not in expected and {p.number for p in prs} == expected + pr = next(p for p in prs if p.number == 2231) + # 14:28:29+01:00 is 13:28:29 UTC, stored naive. + assert pr.merged_at == datetime(2026, 11, 26, 13, 28, 29) + assert pr.files == ["docs/contributor/customization.md"] + assert pr.target_branch == "next" + assert pr.author == "bob" and pr.assignees == ["alice"] + assert [p.updated_at for p in prs] == sorted(p.updated_at for p in prs) + first = calls[0] + assert first.headers["Authorization"] == "token tok" + assert first.url.params["sort"] == "recentupdate" and first.url.params["state"] == "closed" + assert "base" not in first.url.params, "the API has no base filter: filtered here" + assert [c.url.params.get("page") for c in calls if c.url.path.endswith("/pulls")] == ["1", "2"] + + calls.clear() + with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): + other = await forgejo.merged_prs_since(API, "tok", None, max_prs=50, base="main") + assert other == [] + + +@pytest.mark.asyncio +async def test_merged_prs_since_stops_at_the_cursor() -> None: + pulls = FIXTURE["pulls_closed_recentupdate"] + routes = {"/pulls": pulls, "/pulls/2231/files": FIXTURE["pull_files"]} + since = datetime(2026, 11, 26, 13, 0, 0) # after 2277's update, UTC + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + prs = await forgejo.merged_prs_since(API, "tok", since, max_prs=50, base="next") + assert [p.number for p in prs] == [2231] + + +@pytest.mark.asyncio +async def test_merged_prs_back_to_walks_by_close_time_and_resumes_at_a_page() -> None: + pulls = FIXTURE["pulls_closed_recentclose"] + routes: dict[str, Any] = { + **_no_files(pulls), + "/pulls?page=1": (200, pulls, _next_link("/pulls", 2)), + "/pulls?page=2": [], + } + calls: list[httpx.Request] = [] + oldest = datetime(2026, 11, 1) + with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): + prs, nxt = await forgejo.merged_prs_back_to(API, "tok", oldest, base="next") + # The walk stops at the first PR closed before `oldest`: nothing left to resume. + expected = [ + p["number"] + for p in pulls + if p["merged"] + and p["base"]["ref"] == "next" + and (forgejo._parse_dt(p["closed_at"]) or oldest) >= oldest + ] + assert len(expected) == 7 and [p.number for p in prs] == expected and nxt == 0 + assert calls[0].url.params["sort"] == "recentclose" + + # The cap is checked between pages, so the page is read whole and a resume at the + # returned page never repeats a PR. + calls.clear() + with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): + prs, nxt = await forgejo.merged_prs_back_to( + API, "tok", datetime(2020, 1, 1), base="next", max_prs=2 + ) + assert len(prs) == 8 and nxt == 2 + assert [c.url.params["page"] for c in calls if c.url.path.endswith("/pulls")] == ["1"] + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + rest, nxt = await forgejo.merged_prs_back_to( + API, "tok", datetime(2020, 1, 1), base="next", max_prs=2, start_page=nxt + ) + assert rest == [] and nxt == 0 + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("status", "limited"), + [(429, True), (403, False), (404, False)], +) +async def test_errors_are_the_github_client_errors(status: int, limited: bool) -> None: + routes = {"/pulls": (status, {"message": "refused"}, {"Retry-After": "30"})} + with ( + patch.object(forgejo, "get_client", return_value=_replay(routes, [])), + pytest.raises(GitHubError) as exc, + ): + await forgejo.merged_prs_since(API, "tok", None) + assert isinstance(exc.value, RateLimited) is limited + + +@pytest.mark.asyncio +async def test_a_connection_failure_is_a_github_error() -> None: + def handler(request: httpx.Request) -> httpx.Response: + raise httpx.ConnectError("refused", request=request) + + client = httpx.AsyncClient(transport=httpx.MockTransport(handler)) + with patch.object(forgejo, "get_client", return_value=client), pytest.raises(GitHubError): + await forgejo.pr_files(API, "tok", 1) + + +# ---- the worker writes the same rows from a Forgejo entry -------------------------- + + +def _forgejo_entry() -> Any: + return repo_config( + org="o", + namespace="code-w", + repo="forgejo.example.org/acme/widgets", + git_remote=REMOTE, + git_branch="next", + github_token="tok", + forge="forgejo", + ) + + +@pytest.mark.asyncio +async def test_worker_writes_pr_rows_for_a_forgejo_entry(monkeypatch: pytest.MonkeyPatch) -> None: + from server.code.workers import pr_history as w + + # Issues, PR heads and reviews are GitHub's: on, they still never reach Forgejo. + monkeypatch.setattr(settings, "code_gh_items_enabled", True) + monkeypatch.setattr(settings, "code_pr_reviews_enabled", True) + repo = AsyncMock() + + async def _state(org: str, ns: str, key: str) -> str: + return {"git_head": "a" * 40, "pr_cursor": "2026-01-01T00:00:00"}.get(key, "") + + repo.get_state.side_effect = _state + repo.gh_item_titles.return_value = {} + pulls = FIXTURE["pulls_closed_recentupdate"] + routes = {**_no_files(pulls), "/pulls": pulls, "/pulls/2231/files": FIXTURE["pull_files"]} + calls: list[httpx.Request] = [] + with ( + patch("server.code.store.index.CodeRepo", return_value=repo), + patch("server.code.domain.index.repos.configured_repos", return_value=[_forgejo_entry()]), + patch.object(forgejo, "get_client", return_value=_replay(routes, calls)), + ): + result = await w.run_pass() + assert result.errors == [] and result.prs_upserted == 4 and result.reviews_upserted == 0 + table, rows = repo.insert_rows.call_args_list[0].args + assert table == "code_pr_history" + row = next(x for x in rows if x["pr_number"] == 2231) + assert row["files"] == ["docs/contributor/customization.md"] + assert row["target_branch"] == "next" and row["namespace"] == "code-w" + assert {q.url.path.rsplit("/", 1)[-1] for q in calls} <= {"pulls", "files"} + assert all(str(q.url).startswith(API) for q in calls) + newest = max(forgejo._parse_dt(p["updated_at"]) or datetime.min for p in pulls if p["merged"]) + assert repo.set_state.call_args.args[2:] == ("pr_cursor", newest.isoformat()) + + +@pytest.mark.asyncio +async def test_worker_skips_a_host_with_no_pr_source() -> None: + from server.code.workers import pr_history as w + + cfg = repo_config(repo="forgejo.example.org/acme/w", git_remote=REMOTE) + with ( + patch("server.code.store.index.CodeRepo", return_value=AsyncMock()), + patch("server.code.domain.index.repos.configured_repos", return_value=[cfg]), + ): + result = await w.run_pass() + assert result.note == "PR history is not available for git remotes" + + +@pytest.mark.asyncio +async def test_backfill_walks_by_close_time_and_keeps_its_page() -> None: + from types import SimpleNamespace + + from server.cli import code_prs + + pulls = FIXTURE["pulls_closed_recentclose"] + routes = {**_no_files(pulls), "/pulls": pulls} + repo = AsyncMock() + repo.get_state.return_value = "" + repo.gh_item_titles.return_value = {} + args = SimpleNamespace(months=1, max_prs=10) + with ( + patch.object(forgejo, "get_client", return_value=_replay(routes, [])), + patch.object(code_prs, "naive_utc_now", return_value=datetime(2026, 11, 27)), + patch.object(code_prs, "connect_code_plane", AsyncMock()), + patch("server.code.store.index.CodeRepo", return_value=repo), + ): + rc = await code_prs._backfill_prs_forgejo(args, _forgejo_entry()) + assert rc == 0 + table, rows = repo.insert_rows.call_args.args + # Merged into `next` and closed within the month; the walk stops at the first PR + # closed before it, so the one closed a month earlier is not read. + assert table == "code_pr_history" + assert sorted(x["pr_number"] for x in rows) == [2231, 2281, 2285, 2286, 2287, 2288, 2290] + assert repo.set_state.call_args.args[2:] == ("pr_backfill_page", "1") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("command", ["_backfill_reviews", "_backfill_items", "_backfill_assignees"]) +async def test_the_github_only_backfills_send_nothing_for_a_forgejo_entry(command: str) -> None: + from types import SimpleNamespace + + from server.cli import code_prs + + repo = AsyncMock() + repo._ch.query_all.return_value = [{"pr_number": 2231}] + repo.get_state.return_value = "" + calls: list[httpx.Request] = [] + args = SimpleNamespace(prs=5, pages=1, since=None) + with ( + patch("server.clients.github.get_client", return_value=_replay({}, calls)), + patch.object(code_prs, "_repo_cfg", return_value=_forgejo_entry()), + patch.object(code_prs, "connect_code_plane", AsyncMock()), + patch("server.code.store.index.CodeRepo", return_value=repo), + ): + rc = await getattr(code_prs, command)(args) + assert rc == 2 and calls == [] From 4e8a48d350f4c47685883cf6d74e27a5b444d939 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 19:18:31 +0000 Subject: [PATCH 2/9] The Forgejo backfill resumes after a close time, not at a page The saved page is an offset into the closed list, which moves: a reopened PR leaves it and the later ones move up a page, so a resume at the saved page skipped the PR that moved onto the page before. The backfill keeps the close time of the last PR it read (pr_backfill_closed) beside the page. A resume steps back from the page while it is empty or starts at or past that close time and skips the PRs closed after it. A PR closed in the same second as that close time is read again, as the same row. Within one call the paging is still an offset into a list that can change between two requests, so a PR reopened while one call reads pages can be missed by that call; a later run reads it once it is closed again. Signed-off-by: Kaloyan Naumov --- docs/features/code-index/history-and-prs.md | 2 +- server/cli/code_prs.py | 19 +++- server/clients/forgejo.py | 40 +++++-- tests/unit/test_forgejo_pr_source.py | 115 +++++++++++++++++++- 4 files changed, 152 insertions(+), 24 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 9fbf8fdb69d..85b70b5bf14 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -42,7 +42,7 @@ are built from. `backfill-prs` sorts by close time (`sort=recentclose`), which n Forgejo 12 or later. Review comments, the issue mirror and open-PR heads stay GitHub-only. The API has no target-branch filter and no merged-date search, so the branch is matched on each PR's `base.ref` and `backfill-prs` walks closed PRs newest close first back to -`LOOM_CODE_PR_BACKFILL_MONTHS`, resuming at the page it stopped at. +`LOOM_CODE_PR_BACKFILL_MONTHS`, resuming after the close time it stopped at. ## Which op answers which question diff --git a/server/cli/code_prs.py b/server/cli/code_prs.py index 1728f441c5a..3b571117883 100644 --- a/server/cli/code_prs.py +++ b/server/cli/code_prs.py @@ -70,11 +70,13 @@ async def _backfill_prs(args: argparse.Namespace) -> int: async def _backfill_prs_forgejo(args: argparse.Namespace, cfg: Any) -> int: - """Merged PRs newest close first, back to `--months`, from the page the last run - stopped at (`pr_backfill_page`; a finished walk starts over at page 1, its rows - rewritten as the same versions). Forgejo's API has no merged-date search, so this - walk replaces GitHub's day windows.""" - from datetime import timedelta + """Merged PRs newest close first, back to `--months`, resuming after the close + time the last run stopped at (`pr_backfill_closed`, its page in + `pr_backfill_page`; a finished walk starts over at page 1, its rows rewritten as + the same versions). Forgejo's API has no merged-date search, so this walk + replaces GitHub's day windows. `--max-prs` should exceed the number of PRs closed + in one second, or a resume re-reads that second and makes no progress.""" + from datetime import datetime, timedelta from server.clients import forgejo from server.clients.github import GitHubError, RateLimited @@ -91,16 +93,19 @@ async def _backfill_prs_forgejo(args: argparse.Namespace, cfg: Any) -> int: months = args.months or settings.code_pr_backfill_months oldest = naive_utc_now() - timedelta(days=30 * months) page = int(await repo.get_state(org, ns, "pr_backfill_page") or 1) + closed = await repo.get_state(org, ns, "pr_backfill_closed") + before = datetime.fromisoformat(closed) if closed else None total = 0 while total < args.max_prs: try: - prs, nxt = await forgejo.merged_prs_back_to( + prs, nxt, before = await forgejo.merged_prs_back_to( api, cfg.github_token, oldest, max_prs=min(200, args.max_prs - total), base=cfg.git_branch, start_page=page, + before=before, max_pages=5, ) except RateLimited as e: @@ -113,6 +118,8 @@ async def _backfill_prs_forgejo(args: argparse.Namespace, cfg: Any) -> int: await repo.insert_rows("code_pr_history", await pr_rows(repo, org, ns, prs)) total += len(prs) print(f" from page {page}: {len(prs)} merged PRs (total {total})") + closed = before.isoformat() if nxt and before else "" + await repo.set_state(org, ns, "pr_backfill_closed", closed) await repo.set_state(org, ns, "pr_backfill_page", str(nxt or 1)) if not nxt: break diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 29b3613c87d..7f5b019989a 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -169,34 +169,52 @@ async def merged_prs_back_to( max_prs: int = 1000, base: str = "", start_page: int = 1, + before: datetime | None = None, max_pages: int = 20, -) -> tuple[list[MergedPR], int]: +) -> tuple[list[MergedPR], int, datetime | None]: """PRs merged into `base` and closed at or after `oldest`, newest close first - (`sort=recentclose`), from `start_page` on; returns them with the page to resume - at, 0 once the walk reached `oldest` or the last page. A page is read whole, so - `max_prs` is checked between pages and a resume never repeats a PR. The - deep-history backfill: the API has no merged-date search, and close time is merge - time for a merged PR. `sort=recentclose` needs Forgejo 12 or later; older servers - ignore it and answer in creation order.""" + (`sort=recentclose`), resuming after the close time `before`; returns them with the + page to resume at (0 once the walk reached `oldest` or the last page) and the close + time of the last PR read. The page is only where to look: a reopened PR leaves the + list and moves the later ones up, so a resume steps back from `start_page` while the + page is empty or starts at or past `before`, and skips the PRs closed after it. + Across separate batches that boundary holds. Within one call the paging is an + offset into a list that can change between two requests, so a PR reopened while + the call is reading pages can be missed by that call; a later run reads it once it + is closed again. A page is read whole, so `max_prs` is checked between pages, and + should exceed the number of PRs closed in one second, or a resume re-reads the + boundary second and makes no progress. The deep-history backfill: the API has no + merged-date search, and close time is merge time for a merged PR. + `sort=recentclose` needs Forgejo 12 or later; older servers ignore it and answer in + creation order.""" out: list[MergedPR] = [] page = max(1, start_page) + seek = before is not None for _ in range(max_pages): prs, more = await _get_page( f"{repo}/pulls", token, {"state": "closed", "sort": "recentclose", "limit": _PAGE_SIZE, "page": page}, ) + first = _parse_dt(prs[0].get("closed_at")) if prs else None + if seek and before is not None and page > 1 and (first is None or first <= before): + page -= 1 + continue + seek = False for pr in prs: closed = _parse_dt(pr.get("closed_at")) + if closed is not None and before is not None and closed > before: + continue # read before the resume if closed is not None and closed < oldest: - return out, 0 + return out, 0, before + before = closed or before merged = _merged_into(pr, base) if merged is None: continue out.append(await _hydrate_pr(repo, token, pr, merged, _parse_dt(pr.get("updated_at")))) if not more: - return out, 0 + return out, 0, before page += 1 if len(out) >= max_prs: - return out, page - return out, page + return out, page, before + return out, page, before diff --git a/tests/unit/test_forgejo_pr_source.py b/tests/unit/test_forgejo_pr_source.py index 95d71597d28..db768cbb20f 100644 --- a/tests/unit/test_forgejo_pr_source.py +++ b/tests/unit/test_forgejo_pr_source.py @@ -203,7 +203,7 @@ async def test_merged_prs_since_stops_at_the_cursor() -> None: @pytest.mark.asyncio -async def test_merged_prs_back_to_walks_by_close_time_and_resumes_at_a_page() -> None: +async def test_merged_prs_back_to_walks_by_close_time_and_resumes_after_a_close_time() -> None: pulls = FIXTURE["pulls_closed_recentclose"] routes: dict[str, Any] = { **_no_files(pulls), @@ -213,7 +213,7 @@ async def test_merged_prs_back_to_walks_by_close_time_and_resumes_at_a_page() -> calls: list[httpx.Request] = [] oldest = datetime(2026, 11, 1) with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): - prs, nxt = await forgejo.merged_prs_back_to(API, "tok", oldest, base="next") + prs, nxt, _ = await forgejo.merged_prs_back_to(API, "tok", oldest, base="next") # The walk stops at the first PR closed before `oldest`: nothing left to resume. expected = [ p["number"] @@ -229,16 +229,24 @@ async def test_merged_prs_back_to_walks_by_close_time_and_resumes_at_a_page() -> # returned page never repeats a PR. calls.clear() with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): - prs, nxt = await forgejo.merged_prs_back_to( + prs, nxt, before = await forgejo.merged_prs_back_to( API, "tok", datetime(2020, 1, 1), base="next", max_prs=2 ) assert len(prs) == 8 and nxt == 2 assert [c.url.params["page"] for c in calls if c.url.path.endswith("/pulls")] == ["1"] with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): - rest, nxt = await forgejo.merged_prs_back_to( - API, "tok", datetime(2020, 1, 1), base="next", max_prs=2, start_page=nxt + rest, nxt, _ = await forgejo.merged_prs_back_to( + API, + "tok", + datetime(2020, 1, 1), + base="next", + max_prs=2, + start_page=nxt, + before=before, ) - assert rest == [] and nxt == 0 + # Page 2 is empty, so the resume steps back to page 1 and reads again only the PRs + # closed in the same second as `before`. + assert nxt == 0 and {p.number for p in rest} <= {p.number for p in prs} @pytest.mark.asyncio @@ -377,3 +385,98 @@ async def test_the_github_only_backfills_send_nothing_for_a_forgejo_entry(comman ): rc = await getattr(code_prs, command)(args) assert rc == 2 and calls == [] + + +def _paged(rows: list[dict[str, Any]], size: int) -> dict[str, Any]: + """`rows` as `/pulls` pages of `size`, each but the last naming the next.""" + pages = [rows[i : i + size] for i in range(0, len(rows), size)] + return { + f"/pulls?page={n}": (200, chunk, _next_link("/pulls", n + 1) if n < len(pages) else {}) + for n, chunk in enumerate(pages, 1) + } + + +@pytest.mark.asyncio +async def test_a_backfill_resumed_after_a_reopen_reads_the_pr_that_moved_up() -> None: + from types import SimpleNamespace + + from server.cli import code_prs + + pulls = FIXTURE["pulls_closed_recentclose"] + state: dict[str, str] = {} + written: list[int] = [] + repo = AsyncMock() + repo.get_state.side_effect = lambda org, ns, key: state.get(key, "") + repo.set_state.side_effect = lambda org, ns, key, value: state.__setitem__(key, value) + repo.insert_rows.side_effect = lambda table, rows: written.extend(x["pr_number"] for x in rows) + repo.gh_item_titles.return_value = {} + + async def backfill(rows: list[dict[str, Any]], max_prs: int) -> int: + routes = {**_no_files(pulls), **_paged(rows, 3)} + with ( + patch.object(forgejo, "get_client", return_value=_replay(routes, [])), + patch.object(code_prs, "naive_utc_now", return_value=datetime(2026, 11, 27)), + patch.object(code_prs, "connect_code_plane", AsyncMock()), + patch("server.code.store.index.CodeRepo", return_value=repo), + ): + return await code_prs._backfill_prs_forgejo( + SimpleNamespace(months=1, max_prs=max_prs), _forgejo_entry() + ) + + # The first run stops after page 1: 2290, 2231 and 2277 (closed without merging). + assert await backfill(pulls, 1) == 0 and state["pr_backfill_page"] == "2" + # 2277 is reopened, so 2285, the first PR of page 2, moves up into page 1. + reopened = [p for p in pulls if p["number"] != 2277] + assert await backfill(reopened, 10) == 0 + assert sorted(set(written)) == [2231, 2281, 2285, 2286, 2287, 2288, 2290] + assert state["pr_backfill_page"] == "1" and state["pr_backfill_closed"] == "" + + +@pytest.mark.asyncio +async def test_a_resume_page_past_the_end_of_a_shrunk_list_steps_back() -> None: + # The saved page was the last one; a reopen emptied it. The walk steps back and + # reads the PR that moved up, where it used to return nothing and end the backfill. + pulls = FIXTURE["pulls_closed_recentclose"] + npages = -(-len(pulls) // 3) + routes = {**_no_files(pulls), **_paged(pulls, 3), f"/pulls?page={npages + 1}": []} + before = forgejo._parse_dt(pulls[2]["closed_at"]) + oldest = datetime(2026, 10, 27) + + async def walk(start_page: int) -> list[int]: + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + prs, _nxt, _before = await forgejo.merged_prs_back_to( + API, "tok", oldest, base="next", start_page=start_page, before=before + ) + return [p.number for p in prs] + + expected = await walk(1) + assert expected and await walk(npages + 1) == expected + + +@pytest.mark.asyncio +async def test_a_resume_steps_back_past_a_page_that_starts_in_the_boundary_second() -> None: + # Three PRs closed in the same second straddle a page boundary; a PR above them is + # reopened, so the unread tie member moves up onto the page before the saved one. + base = FIXTURE["pulls_closed_recentclose"][0] + stamps = ["11:00:00", "10:30:00", "10:20:00", "10:10:00", "10:05:00"] + stamps += ["10:00:00", "10:00:00", "10:00:00", "09:00:00"] + rows = [ + { + **base, + "number": n, + "merged": True, + "closed_at": f"2026-11-20T{t}Z", + "merged_at": f"2026-11-20T{t}Z", + "base": {**base["base"], "ref": "next"}, + } + for n, t in enumerate(stamps, 1) + ] + # Run 1 read pages 1 and 2 (down to 6, closed 10:00:00); 1 is then reopened. + reopened = rows[1:] + routes = {**_no_files(rows), **_paged(reopened, 3)} + before = forgejo._parse_dt("2026-11-20T10:00:00Z") + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + prs, _nxt, _before = await forgejo.merged_prs_back_to( + API, "tok", datetime(2026, 10, 27), base="next", start_page=3, before=before + ) + assert {7, 8} <= {p.number for p in prs} From 2c9c4faf61308d05c7b1f31d472c17107cd8449e Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 19:18:31 +0000 Subject: [PATCH 3/9] The Forgejo PR walk reads down to the worker's cursor The list has no branch filter, so ten pages of other branches' PRs could end the walk before the cursor while a PR merged into the tracked branch sat behind them; the cursor then moved to the newest PR read and the one behind was never fetched. The walk reads list pages until the cursor and returns the oldest max_prs of the PRs merged into the branch, plus any updated in the same second as the last of them. The cursor is the newest updated_at returned. The paging is an offset into a list that can change between two requests, so a PR reopened while one walk reads pages can be missed by that walk; a later run reads it once it is closed again. Signed-off-by: Kaloyan Naumov --- server/clients/forgejo.py | 35 ++++++++------ tests/unit/test_forgejo_pr_source.py | 68 ++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+), 14 deletions(-) diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 7f5b019989a..3a7d5e27eda 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -132,33 +132,40 @@ async def merged_prs_since( base: str = "", ) -> list[MergedPR]: """PRs merged into `base` and updated after `since`, with files, oldest-updated - first: closed PRs newest update first (`sort=recentupdate`), stopping at the first - one at or before `since`, at most 10 pages, as `github.merged_prs_since` walks.""" - collected: list[MergedPR] = [] + first: closed PRs newest update first (`sort=recentupdate`) down to the first one + at or before `since`, then the oldest `max_prs` of those merged into `base`, plus + any updated in the same second as the last of them. The walk reads down to + `since` and keeps that tie, so the newest `updated_at` returned is a cursor that + no page-count cut and no tie leaves behind: the list has no branch filter, and a + walk cut at a page count could stop behind other branches' PRs. The paging is an + offset into a list that can change between two requests and has no `since` + filter, so a PR reopened while one walk is reading pages can be missed by that + walk; a later run reads it once it is closed again.""" + found: list[tuple[datetime, dict[str, Any], datetime]] = [] page = 1 - while len(collected) < max_prs and page <= 10: + while True: prs, more = await _get_page( f"{repo}/pulls", token, {"state": "closed", "sort": "recentupdate", "limit": _PAGE_SIZE, "page": page}, ) - drained = False for pr in prs: updated = _parse_dt(pr.get("updated_at")) if since is not None and updated is not None and updated <= since: - drained = True + more = False break merged = _merged_into(pr, base) - if merged is None: - continue - collected.append(await _hydrate_pr(repo, token, pr, merged, updated)) - if len(collected) >= max_prs: - break - if drained or not more: + if merged is not None: + found.append((updated or merged, pr, merged)) + if not more: break page += 1 - collected.sort(key=lambda p: p.updated_at) - return collected + found.sort(key=lambda f: f[0]) + if len(found) > max_prs: + # Keep the PRs updated in the same second as the last one kept: the cursor is + # that second, and the next pass skips every PR at or before it. + found = [f for f in found if f[0] <= found[max_prs - 1][0]] + return [await _hydrate_pr(repo, token, pr, m, u) for u, pr, m in found] async def merged_prs_back_to( diff --git a/tests/unit/test_forgejo_pr_source.py b/tests/unit/test_forgejo_pr_source.py index db768cbb20f..151ddd4a4f1 100644 --- a/tests/unit/test_forgejo_pr_source.py +++ b/tests/unit/test_forgejo_pr_source.py @@ -480,3 +480,71 @@ async def test_a_resume_steps_back_past_a_page_that_starts_in_the_boundary_secon API, "tok", datetime(2026, 10, 27), base="next", start_page=3, before=before ) assert {7, 8} <= {p.number for p in prs} + + +def _pr(number: int, updated: str, ref: str = "next") -> dict[str, Any]: + """The recorded PR 2231 as another PR, updated at `updated`, merged into `ref`.""" + pr = FIXTURE["pulls_closed_recentupdate"][0] + return {**pr, "number": number, "updated_at": updated, "base": {**pr["base"], "ref": ref}} + + +@pytest.mark.asyncio +async def test_the_worker_reads_past_ten_pages_of_other_branches_to_its_cursor() -> None: + from server.code.workers import pr_history as w + + # Newest update first, one PR a page: 9001 into `next`, ten PRs into another + # branch, 9002 into `next`, then 9003, updated before the cursor. + others = [_pr(9100 + i, f"2026-11-20T11:{59 - i:02d}:00Z", "v17.0") for i in range(10)] + rows = [ + _pr(9001, "2026-11-20T12:00:00Z"), + *others, + _pr(9002, "2026-11-10T00:00:00Z"), + _pr(9003, "2026-10-20T00:00:00Z"), + ] + routes = {**_no_files(rows), **_paged(rows, 1)} + repo = AsyncMock() + + async def _state(org: str, ns: str, key: str) -> str: + return {"git_head": "a" * 40, "pr_cursor": "2026-11-01T00:00:00"}.get(key, "") + + repo.get_state.side_effect = _state + repo.gh_item_titles.return_value = {} + with ( + patch("server.code.store.index.CodeRepo", return_value=repo), + patch("server.code.domain.index.repos.configured_repos", return_value=[_forgejo_entry()]), + patch.object(forgejo, "get_client", return_value=_replay(routes, [])), + ): + result = await w.run_pass() + assert result.errors == [] + _table, written = repo.insert_rows.call_args_list[0].args + assert sorted(x["pr_number"] for x in written) == [9001, 9002] + assert repo.set_state.call_args.args[2:] == ("pr_cursor", "2026-11-20T12:00:00") + + # A budget keeps the oldest PRs, so the cursor never passes one left unread. + since = datetime(2026, 11, 1) + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + prs = await forgejo.merged_prs_since(API, "tok", since, max_prs=1, base="next") + assert [p.number for p in prs] == [9002] + + +@pytest.mark.asyncio +async def test_a_tie_at_the_pr_budget_is_read_with_the_rest_of_its_second() -> None: + # 9002 and 9003 were updated in the same second and the budget is one PR. The + # worker's cursor is the newest `updated_at` returned, and the next pass skips + # everything at or before it, so the cut keeps the tie whole. + rows = [ + _pr(9001, "2026-11-20T12:00:00Z"), + _pr(9003, "2026-11-10T00:00:00Z"), + _pr(9002, "2026-11-10T00:00:00Z"), + ] + routes = {**_no_files(rows), **_paged(rows, 2)} + seen: list[int] = [] + cursor: datetime | None = datetime(2026, 11, 1) + for _ in range(3): + with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): + prs = await forgejo.merged_prs_since(API, "tok", cursor, max_prs=1, base="next") + if not prs: + break + seen += [p.number for p in prs] + cursor = max(p.updated_at for p in prs) + assert sorted(seen) == [9001, 9002, 9003] From e3a86501acdd75e1e239707533824f4409ee7c5a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sun, 29 Nov 2026 22:30:17 +0000 Subject: [PATCH 4/9] The Forgejo PR walk reads oldest first and settles each page The worker walk read the closed-PR list newest first down to its cursor and saved the newest PR of the oldest slice. A PR reopened between two page requests moved a different PR onto a page already read, so the cursor could pass a merged PR for good, and a rate limit or deadline anywhere in a long walk left the cursor where it was. The walk now finds the page that holds the cursor by doubling and bisecting, then reads upward from it, oldest update first. A page counts only once the page below it, read again, is unchanged, and a PR updated in the newest second read waits for the next page, so the cursor never passes a PR that has not been read. A failed request after some pages returns the PRs those pages settled, and the next pass goes on from there. Signed-off-by: Kaloyan Naumov --- server/clients/forgejo.py | 133 ++++++++++++++++++++------- tests/unit/test_forgejo_pr_source.py | 99 +++++++++++++++++++- 2 files changed, 198 insertions(+), 34 deletions(-) diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 3a7d5e27eda..7e7b4525475 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -35,6 +35,7 @@ # Forgejo caps a page at its own MAX_RESPONSE_ITEMS (50 by default), so a larger value # would change nothing. _PAGE_SIZE = 50 # not a setting: the server's own cap +_ATTEMPTS = 3 # reads of one page, while the list moves under the walk def _headers(token: str) -> dict[str, str]: @@ -123,6 +124,60 @@ def _merged_into(pr: dict[str, Any], base: str) -> datetime | None: return merged +async def _closed_page(repo: str, token: str, page: int) -> tuple[list[dict[str, Any]], bool]: + return await _get_page( + f"{repo}/pulls", + token, + {"state": "closed", "sort": "recentupdate", "limit": _PAGE_SIZE, "page": page}, + ) + + +def _is_past(prs: list[dict[str, Any]], since: datetime | None) -> bool: + """No PR on this page was updated after `since` (an empty page is past it).""" + first = _parse_dt(prs[0].get("updated_at")) if prs else None + return not prs or (since is not None and first is not None and first <= since) + + +async def _last_page_after( + repo: str, token: str, since: datetime | None, pages: dict[int, list[dict[str, Any]]] +) -> int: + """The highest page that holds a PR updated after `since` (0: none), by galloping + and then bisecting: the list is newest update first, so the pages are in order. + Leaves every page it read, and the one below the answer, in `pages`.""" + lo, hi = 0, 1 + while True: + pages[hi], more = await _closed_page(repo, token, hi) + if _is_past(pages[hi], since): + break + if not more: # the last page still holds PRs after `since` + lo, hi = hi, hi + 1 + pages[hi] = [] + break + lo, hi = hi, hi * 2 + while hi - lo > 1: + mid = (lo + hi) // 2 + pages[mid], _ = await _closed_page(repo, token, mid) + lo, hi = (lo, mid) if _is_past(pages[mid], since) else (mid, hi) + return lo + + +async def _verified_page( + repo: str, token: str, page: int, below: list[dict[str, Any]] +) -> tuple[list[dict[str, Any]], list[dict[str, Any]]] | None: + """`page` and the page below it (older), read so that no PR slipped across the edge + between them: the page below, read again after this one, matches the earlier read + `below`. A PR updated meanwhile pushes the one at this page's end onto the page + below, where neither read has it; the second read of that page has it. None when + the list keeps moving.""" + for _ in range(_ATTEMPTS): + rows, _ = await _closed_page(repo, token, page) + again, _ = await _closed_page(repo, token, page + 1) + if [p.get("number") for p in again] == [p.get("number") for p in below]: + return rows, again + below = again + return None + + async def merged_prs_since( repo: str, token: str, @@ -132,40 +187,56 @@ async def merged_prs_since( base: str = "", ) -> list[MergedPR]: """PRs merged into `base` and updated after `since`, with files, oldest-updated - first: closed PRs newest update first (`sort=recentupdate`) down to the first one - at or before `since`, then the oldest `max_prs` of those merged into `base`, plus - any updated in the same second as the last of them. The walk reads down to - `since` and keeps that tie, so the newest `updated_at` returned is a cursor that - no page-count cut and no tie leaves behind: the list has no branch filter, and a - walk cut at a page count could stop behind other branches' PRs. The paging is an - offset into a list that can change between two requests and has no `since` - filter, so a PR reopened while one walk is reading pages can be missed by that - walk; a later run reads it once it is closed again.""" - found: list[tuple[datetime, dict[str, Any], datetime]] = [] - page = 1 - while True: - prs, more = await _get_page( - f"{repo}/pulls", - token, - {"state": "closed", "sort": "recentupdate", "limit": _PAGE_SIZE, "page": page}, - ) - for pr in prs: - updated = _parse_dt(pr.get("updated_at")) - if since is not None and updated is not None and updated <= since: - more = False + first. The list is closed PRs newest update first (`sort=recentupdate`) with no + branch filter and no `since`, so this finds the page that holds `since`, then reads + upward from it, oldest first, until it has `max_prs` PRs (plus any updated in the + same second as the last of them) or reaches the newest page. A page counts only + once the page below it, read again, is unchanged, and a PR updated in the newest + second read waits for the next page. So the newest `updated_at` returned is a + cursor that no PR reopened, updated or tied at a page edge hides behind, and a + request that fails after some pages returns the PRs they settled: the next pass + reads on from there.""" + pages: dict[int, list[dict[str, Any]]] = {} + found: dict[int, tuple[datetime, dict[str, Any], datetime]] = {} + edge: datetime | None = None # PRs updated at or after it may have peers on the next page + failure: GitHubError | None = None + + def settled() -> list[tuple[datetime, dict[str, Any], datetime]]: + rows = sorted(found.values(), key=lambda f: (f[0], f[1]["number"])) + return [f for f in rows if edge is None or f[0] < edge] + + try: + last = await _last_page_after(repo, token, since, pages) + below = pages.get(last + 1, []) + for page in range(last, 0, -1): + verified = await _verified_page(repo, token, page, below) + if verified is None: break - merged = _merged_into(pr, base) - if merged is not None: - found.append((updated or merged, pr, merged)) - if not more: - break - page += 1 - found.sort(key=lambda f: f[0]) - if len(found) > max_prs: + rows, below = verified[0], verified[1] + for pr in [*below, *rows]: + updated = _parse_dt(pr.get("updated_at")) + if since is not None and updated is not None and updated <= since: + continue + merged = _merged_into(pr, base) + if merged is not None: + found[int(pr["number"])] = (updated or merged, pr, merged) + if page == 1: + edge = None + elif rows: + edge = _parse_dt(rows[0].get("updated_at")) + if len(settled()) >= max_prs: + break + below = rows + except GitHubError as e: # a rate limit included: keep what the settled pages gave + failure = e + out = settled() + if failure is not None and not out: + raise failure + if len(out) > max_prs: # Keep the PRs updated in the same second as the last one kept: the cursor is # that second, and the next pass skips every PR at or before it. - found = [f for f in found if f[0] <= found[max_prs - 1][0]] - return [await _hydrate_pr(repo, token, pr, m, u) for u, pr, m in found] + out = [f for f in out if f[0] <= out[max_prs - 1][0]] + return [await _hydrate_pr(repo, token, pr, m, u) for u, pr, m in out] async def merged_prs_back_to( diff --git a/tests/unit/test_forgejo_pr_source.py b/tests/unit/test_forgejo_pr_source.py index 151ddd4a4f1..f5b16597e93 100644 --- a/tests/unit/test_forgejo_pr_source.py +++ b/tests/unit/test_forgejo_pr_source.py @@ -9,6 +9,7 @@ from __future__ import annotations import json +from collections.abc import Callable from datetime import datetime from pathlib import Path from typing import Any @@ -132,13 +133,16 @@ def test_pr_web_url_per_host() -> None: def _replay(routes: dict[str, Any], calls: list[httpx.Request]) -> httpx.AsyncClient: """A client answering each path from `routes` (a page of a list as `path?page=N`, - else the bare path): a body (200), or (status, body, headers).""" + else the bare path): a body (200), or (status, body, headers). A page of the PR list + that `routes` lacks is empty, as past the end of a list on a server.""" def handler(request: httpx.Request) -> httpx.Response: calls.append(request) key = request.url.path.removeprefix("/api/v1/repos/acme/widgets") page = request.url.params.get("page", "1") answer = routes.get(f"{key}?page={page}", routes.get(key)) + if answer is None and key == "/pulls": + answer = [] if answer is None: return httpx.Response(404, json={"message": "The target couldn't be found."}) if isinstance(answer, tuple): @@ -184,7 +188,14 @@ async def test_merged_prs_since_filters_the_base_branch_and_reads_files_in_utc() assert first.headers["Authorization"] == "token tok" assert first.url.params["sort"] == "recentupdate" and first.url.params["state"] == "closed" assert "base" not in first.url.params, "the API has no base filter: filtered here" - assert [c.url.params.get("page") for c in calls if c.url.path.endswith("/pulls")] == ["1", "2"] + # One page holds every PR: the walk finds it, reads it, and reads the page below it + # again to confirm nothing moved across their edge. + assert [c.url.params.get("page") for c in calls if c.url.path.endswith("/pulls")] == [ + "1", + "2", + "1", + "2", + ] calls.clear() with patch.object(forgejo, "get_client", return_value=_replay(routes, calls)): @@ -195,7 +206,7 @@ async def test_merged_prs_since_filters_the_base_branch_and_reads_files_in_utc() @pytest.mark.asyncio async def test_merged_prs_since_stops_at_the_cursor() -> None: pulls = FIXTURE["pulls_closed_recentupdate"] - routes = {"/pulls": pulls, "/pulls/2231/files": FIXTURE["pull_files"]} + routes = {"/pulls?page=1": pulls, "/pulls/2231/files": FIXTURE["pull_files"]} since = datetime(2026, 11, 26, 13, 0, 0) # after 2277's update, UTC with patch.object(forgejo, "get_client", return_value=_replay(routes, [])): prs = await forgejo.merged_prs_since(API, "tok", since, max_prs=50, base="next") @@ -548,3 +559,85 @@ async def test_a_tie_at_the_pr_budget_is_read_with_the_rest_of_its_second() -> N seen += [p.number for p in prs] cursor = max(p.updated_at for p in prs) assert sorted(seen) == [9001, 9002, 9003] + + +def _live( + rows: list[dict[str, Any]], + size: int, + after: dict[tuple[int, int], Callable[[], None]] | None = None, + outage_from: int | None = None, +) -> httpx.AsyncClient: + """`/pulls` as a server whose list changes between two requests: `rows` newest update + first, `size` to a page. `after[(page, n)]` runs once the n-th request for `page` is + answered; every list request from the `outage_from`-th on is a 429. Files are empty.""" + asked: dict[int, int] = {} + + def handler(request: httpx.Request) -> httpx.Response: + if request.url.path.endswith("/files"): + return httpx.Response(200, json=[]) + page = int(request.url.params["page"]) + n = asked[page] = asked.get(page, 0) + 1 + if outage_from is not None and sum(asked.values()) >= outage_from: + return httpx.Response(429, json={}, headers={"Retry-After": "30"}) + headers = _next_link("/pulls", page + 1) if page * size < len(rows) else {} + response = httpx.Response(200, json=rows[(page - 1) * size : page * size], headers=headers) + if (hook := (after or {}).get((page, n))) is not None: + hook() + return response + + return httpx.AsyncClient(transport=httpx.MockTransport(handler)) + + +async def _passes(client: httpx.AsyncClient, cursor: datetime, count: int) -> list[list[int]]: + """`count` passes of the worker's walk, each from the cursor the last one left.""" + out: list[list[int]] = [] + for _ in range(count): + with patch.object(forgejo, "get_client", return_value=client): + prs = await forgejo.merged_prs_since(API, "tok", cursor, max_prs=50, base="next") + out.append([p.number for p in prs]) + cursor = max([p.updated_at for p in prs], default=cursor) + return out + + +@pytest.mark.asyncio +async def test_a_reopen_during_a_pass_does_not_hide_a_pr_from_the_next_pass() -> None: + # Two PRs a page, newest update first: 4, 3 (closed unmerged), 2, 1. Reopening 3 + # right after the first page is read moves 2 up onto that page, so a walk that + # trusted its pages would return 1 and 4, save 4 as the cursor, and never reach 2. + rows = [ + _pr(4, "2026-11-20T00:40:00Z"), + {**_pr(3, "2026-11-20T00:30:00Z"), "merged": False, "merged_at": None}, + _pr(2, "2026-11-20T00:20:00Z"), + _pr(1, "2026-11-20T00:10:00Z"), + ] + client = _live(rows, 2, after={(1, 1): lambda: rows.pop(1)}) + passes = await _passes(client, datetime(2026, 11, 20), 2) + assert sorted(n for p in passes for n in p) == [1, 2, 4] + + +@pytest.mark.asyncio +async def test_a_pr_updated_during_a_pass_does_not_hide_the_one_it_pushes_down() -> None: + # Five PRs, two a page. Once page 3 is read, a newer PR is added at the top: PR 2 + # moves from page 2 onto page 3, which the walk already read. Reading page 3 again + # after page 2 shows the move, and the walk keeps 2. + rows = [_pr(n, f"2026-11-20T00:{n}0:00Z") for n in (5, 4, 3, 2, 1)] + newer = _pr(6, "2026-11-20T01:00:00Z") + client = _live(rows, 2, after={(3, 2): lambda: rows.insert(0, newer)}) + (numbers,) = await _passes(client, datetime(2026, 11, 20), 1) + assert sorted(numbers) == [1, 2, 3, 4, 5, 6] + + +@pytest.mark.asyncio +async def test_a_failure_mid_walk_keeps_what_the_settled_pages_gave() -> None: + # 64 PRs, two a page, all after the cursor; the server refuses every list request + # from the 20th on. The walk starts at the oldest PRs, so the pages it settled are + # returned and the cursor moves up to them; the next pass goes on from there. + rows = [_pr(n, f"2026-11-20T{n // 60:02d}:{n % 60:02d}:00Z") for n in range(64, 0, -1)] + cursor = datetime(2026, 11, 19) + with patch.object(forgejo, "get_client", return_value=_live(rows, 2, outage_from=20)): + prs = await forgejo.merged_prs_since(API, "tok", cursor, max_prs=50, base="next") + got = [p.number for p in prs] + assert got and got == list(range(1, len(got) + 1)) + cursor = max(p.updated_at for p in prs) + (more,) = await _passes(_live(rows, 2), cursor, 1) + assert more[0] == len(got) + 1 From b56c9fc8bb68e147618edd1a30ad860978f925f4 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Mon, 30 Nov 2026 11:25:26 +0000 Subject: [PATCH 5/9] Forgejo backfill checks its page edges; PR links keep the port Within one backfill call, a PR reopened after a page was read moved the first PR of the next page onto the page already read, so the call could skip a merged PR and still report the walk complete. After each new page the walk now reads the page above it again. If that page changed, the walk reads it again before going on, and skips the PRs it already has, so a PR closed during the call is not returned twice either. PR links for a Forgejo entry were built from the configured `repo`, which has no port, so a host served on 8443 got links on 443. They are now built from the entry's remote, as the API URL is, port included. Signed-off-by: Kaloyan Naumov --- docs/features/code-index/history-and-prs.md | 6 +- server/clients/forgejo.py | 41 ++++++++---- server/code/app/bisect_scan.py | 3 +- server/code/app/blame.py | 2 + server/code/domain/index/blame_range.py | 4 +- server/code/domain/index/remote.py | 37 ++++++++--- tests/unit/test_code_bisect_generic.py | 6 +- tests/unit/test_code_blame_introduced.py | 2 +- tests/unit/test_code_blame_range.py | 2 +- tests/unit/test_forgejo_pr_source.py | 73 +++++++++++++++++++++ 10 files changed, 144 insertions(+), 32 deletions(-) diff --git a/docs/features/code-index/history-and-prs.md b/docs/features/code-index/history-and-prs.md index 85b70b5bf14..5c3cdd54da2 100644 --- a/docs/features/code-index/history-and-prs.md +++ b/docs/features/code-index/history-and-prs.md @@ -33,12 +33,12 @@ so "what changed on 2.4" reads the 2.4 namespace. `loom code backfill-prs` loads ## Forgejo hosts An entry in `LOOM_CODE_REPOS_JSON` with `"forge": "forgejo"` and an HTTPS or SSH -`git_remote` reads its merged PRs from that host's REST API (`https:///api/v1`) +`git_remote` reads its merged PRs from that host's REST API (`https://[:port]/api/v1`) into `loom.code_pr_history`; the Repositories page does not set `forge`. The entry's `github_token` is then the host's access token (scope `read:repository`; a public repository reads without one), never `LOOM_CODE_GITHUB_TOKEN`, which is not sent to a -Forgejo host. The entry's `repo` is `host/owner/name`, which is also what its PR links -are built from. `backfill-prs` sorts by close time (`sort=recentclose`), which needs +Forgejo host. The entry's `repo` is `host/owner/name`; its PR links are built from +`git_remote`, port included. `backfill-prs` sorts by close time (`sort=recentclose`), which needs Forgejo 12 or later. Review comments, the issue mirror and open-PR heads stay GitHub-only. The API has no target-branch filter and no merged-date search, so the branch is matched on each PR's `base.ref` and `backfill-prs` walks closed PRs newest close first back to diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 7e7b4525475..f0cfdb430a5 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -239,6 +239,14 @@ def settled() -> list[tuple[datetime, dict[str, Any], datetime]]: return [await _hydrate_pr(repo, token, pr, m, u) for u, pr, m in out] +async def _page_by_close(repo: str, token: str, page: int) -> tuple[list[dict[str, Any]], bool]: + return await _get_page( + f"{repo}/pulls", + token, + {"state": "closed", "sort": "recentclose", "limit": _PAGE_SIZE, "page": page}, + ) + + async def merged_prs_back_to( repo: str, token: str, @@ -256,24 +264,25 @@ async def merged_prs_back_to( time of the last PR read. The page is only where to look: a reopened PR leaves the list and moves the later ones up, so a resume steps back from `start_page` while the page is empty or starts at or past `before`, and skips the PRs closed after it. - Across separate batches that boundary holds. Within one call the paging is an - offset into a list that can change between two requests, so a PR reopened while - the call is reading pages can be missed by that call; a later run reads it once it - is closed again. A page is read whole, so `max_prs` is checked between pages, and - should exceed the number of PRs closed in one second, or a resume re-reads the - boundary second and makes no progress. The deep-history backfill: the API has no - merged-date search, and close time is merge time for a merged PR. - `sort=recentclose` needs Forgejo 12 or later; older servers ignore it and answer in - creation order.""" + Within one call, the walk reads the page above again after each new page, and goes + on only when it is unchanged: a PR reopened above moves the first PR of the new page + onto the page above, and the walk then reads that page again, skipping the PRs it + has. A page is read whole, so `max_prs` is checked between pages, and should exceed + the number of PRs closed in one second, or a resume re-reads the boundary second and + makes no progress. The deep-history backfill: the API has no merged-date search, and + close time is merge time for a merged PR. `sort=recentclose` needs Forgejo 12 or + later; older servers ignore it and answer in creation order.""" out: list[MergedPR] = [] + read: set[int] = set() page = max(1, start_page) seek = before is not None + above: list[dict[str, Any]] | None = None # the page above `page`, as the walk read it for _ in range(max_pages): - prs, more = await _get_page( - f"{repo}/pulls", - token, - {"state": "closed", "sort": "recentclose", "limit": _PAGE_SIZE, "page": page}, - ) + prs, more = await _page_by_close(repo, token, page) + if above is not None: + again, again_more = await _page_by_close(repo, token, page - 1) + if [p.get("number") for p in again] != [p.get("number") for p in above]: + page, prs, more = page - 1, again, again_more first = _parse_dt(prs[0].get("closed_at")) if prs else None if seek and before is not None and page > 1 and (first is None or first <= before): page -= 1 @@ -283,15 +292,19 @@ async def merged_prs_back_to( closed = _parse_dt(pr.get("closed_at")) if closed is not None and before is not None and closed > before: continue # read before the resume + if int(pr["number"]) in read: + continue # read already, before the list moved if closed is not None and closed < oldest: return out, 0, before before = closed or before + read.add(int(pr["number"])) merged = _merged_into(pr, base) if merged is None: continue out.append(await _hydrate_pr(repo, token, pr, merged, _parse_dt(pr.get("updated_at")))) if not more: return out, 0, before + above = prs page += 1 if len(out) >= max_prs: return out, page, before diff --git a/server/code/app/bisect_scan.py b/server/code/app/bisect_scan.py index b0c7cb03fef..3c78b0a2c02 100644 --- a/server/code/app/bisect_scan.py +++ b/server/code/app/bisect_scan.py @@ -268,6 +268,7 @@ async def _code_history_rows( return [] cfg = repo_for_namespace(org, ns) repo = cfg.repo if cfg else "" + remote, forge = (cfg.git_remote, cfg.forge) if cfg else ("", "") wanted = set(paths) out: list[dict[str, Any]] = [] for r in found: @@ -282,7 +283,7 @@ async def _code_history_rows( "merged_at": r.get("merged_at"), "matched_paths": matched, "affected_file_paths": files, - "url": pr_web_url(repo, n), + "url": pr_web_url(repo, n, git_remote=remote, forge=forge), "additions": int(r.get("additions") or 0), "deletions": int(r.get("deletions") or 0), } diff --git a/server/code/app/blame.py b/server/code/app/blame.py index 2e2541a4386..e9bf446bbe5 100644 --- a/server/code/app/blame.py +++ b/server/code/app/blame.py @@ -762,6 +762,8 @@ async def handle_code_blame_range(input: Any) -> Any: range_len=end - start + 1, branch_points=points, repo=gh_repo, + git_remote=cfg.git_remote if cfg is not None else "", + forge=cfg.forge if cfg is not None else "", limit=max(input.limit, intro.STAGE_POOL) if introduced else input.limit, ) await fill_merge_shas(git_dir, w.to_sha, candidates) diff --git a/server/code/domain/index/blame_range.py b/server/code/domain/index/blame_range.py index 54dda7144d3..bc2fc27d315 100644 --- a/server/code/domain/index/blame_range.py +++ b/server/code/domain/index/blame_range.py @@ -570,6 +570,8 @@ def merge_legs( range_len: int, branch_points: list[tuple[str, int, str]], repo: str = "", + git_remote: str = "", + forge: str = "", limit: int = 10, ) -> list[Candidate]: """One candidate per PR: blame-attributed PRs first by lines touched, @@ -606,7 +608,7 @@ def merge_legs( merge_commit_sha=sha, merge_sha_source=("stored" if stored else "mirror") if sha else "", kind=kind_of(title), - url=pr_web_url(repo, n), + url=pr_web_url(repo, n, git_remote=git_remote, forge=forge), ) ) out.sort(key=lambda c: (-c.lines_blamed, -unix_of(c.merged_at), -c.pr_number)) diff --git a/server/code/domain/index/remote.py b/server/code/domain/index/remote.py index 09b352dd753..1f89c1fbb9e 100644 --- a/server/code/domain/index/remote.py +++ b/server/code/domain/index/remote.py @@ -164,23 +164,40 @@ def provider_for(remote: str) -> str: return "git" -def forgejo_api_repo(remote: str) -> str: - """`https://[:port]/api/v1/repos//` for a Forgejo remote, HTTPS or - SSH: the API is served over HTTPS on the remote's host. ValueError for a remote that - names no `/`.""" +def _forgejo_repo_url(remote: str) -> tuple[str, str, str]: + """(`https://[:port]`, owner, name) of a Forgejo remote, HTTPS or SSH: the + host serves its API and web pages over HTTPS, on the port of an HTTPS remote. + ValueError for a remote that names no `/`.""" spec = parse_remote(remote) owner, _, name = spec.repo.removeprefix(f"{spec.host}/").partition("/") if not owner or not name or "/" in name: raise ValueError("a Forgejo remote names /") port = urlsplit(spec.url).port if spec.url.startswith("https:") else None - return f"https://{spec.host}{f':{port}' if port else ''}/api/v1/repos/{owner}/{name}" + return f"https://{spec.host}{f':{port}' if port else ''}", owner, name -def pr_web_url(repo: str, number: int) -> str: - """The web page of pull request `number` of `repo` as configured: GitHub's `/pull/N` - for `owner/name`, Forgejo's `/pulls/N` for `host/owner/name`. '' without a - repository or number.""" - if not repo or not number: +def forgejo_api_repo(remote: str) -> str: + """`https://[:port]/api/v1/repos//` for a Forgejo remote, HTTPS or + SSH: the API is served over HTTPS on the remote's host. ValueError for a remote that + names no `/`.""" + origin, owner, name = _forgejo_repo_url(remote) + return f"{origin}/api/v1/repos/{owner}/{name}" + + +def pr_web_url(repo: str, number: int, *, git_remote: str = "", forge: str = "") -> str: + """The web page of pull request `number`: for a Forgejo entry (`forge`), Forgejo's + `/pulls/N` on the host and port of its `git_remote`, the API's own; otherwise from + `repo` as configured, GitHub's `/pull/N` for `owner/name` and `/pulls/N` for + `host/owner/name`. '' without a repository or number.""" + if not number: + return "" + if forge == "forgejo" and git_remote: + try: + origin, owner, name = _forgejo_repo_url(git_remote) + except ValueError: + return "" + return f"{origin}/{owner}/{name}/pulls/{number}" + if not repo: return "" if "." in repo.split("/", 1)[0]: return f"https://{repo}/pulls/{number}" diff --git a/tests/unit/test_code_bisect_generic.py b/tests/unit/test_code_bisect_generic.py index f08b43a83cd..29cb8030815 100644 --- a/tests/unit/test_code_bisect_generic.py +++ b/tests/unit/test_code_bisect_generic.py @@ -125,7 +125,11 @@ async def query_all(self, sql: str, params: dict) -> list[dict]: import server.core.ch as ch monkeypatch.setattr(ch, "get_client", lambda: _Ch()) - monkeypatch.setattr(repos, "repo_for_namespace", lambda org, ns: SimpleNamespace(repo="Acme/w")) + monkeypatch.setattr( + repos, + "repo_for_namespace", + lambda org, ns: SimpleNamespace(repo="Acme/w", git_remote="", forge=""), + ) out = await bisect_scan._code_history_rows("o", "code-x", _plan(dirs=["src/Parsers"]), limit=10) assert seen["dirs"] == ["src/Parsers/"] and seen["before"] - seen["after"] == timedelta(days=90) assert out[0]["matched_paths"] == ["src/Parsers/a.cpp"] diff --git a/tests/unit/test_code_blame_introduced.py b/tests/unit/test_code_blame_introduced.py index 93a006a0635..86d98b4484d 100644 --- a/tests/unit/test_code_blame_introduced.py +++ b/tests/unit/test_code_blame_introduced.py @@ -328,7 +328,7 @@ class _Cfg: def __init__(self, namespace: str, branch: str) -> None: self.org, self.namespace, self.git_branch = ORG, namespace, branch self.git_dir, self.repo = GIT, "ClickHouse/ClickHouse" - self.git_remote = "https://github.com/ClickHouse/ClickHouse.git" + self.git_remote, self.forge = "https://github.com/ClickHouse/ClickHouse.git", "" class _Repo: diff --git a/tests/unit/test_code_blame_range.py b/tests/unit/test_code_blame_range.py index 257c11b8f16..5fb06e3bb84 100644 --- a/tests/unit/test_code_blame_range.py +++ b/tests/unit/test_code_blame_range.py @@ -244,7 +244,7 @@ class _Cfg: def __init__(self, namespace: str, branch: str) -> None: self.org, self.namespace, self.git_branch = ORG, namespace, branch self.git_dir, self.repo = GIT, "ClickHouse/ClickHouse" - self.git_remote = "https://github.com/ClickHouse/ClickHouse.git" + self.git_remote, self.forge = "https://github.com/ClickHouse/ClickHouse.git", "" self.label, self.source = f"{ORG}/{namespace}", "config" diff --git a/tests/unit/test_forgejo_pr_source.py b/tests/unit/test_forgejo_pr_source.py index f5b16597e93..0d4ac3b451e 100644 --- a/tests/unit/test_forgejo_pr_source.py +++ b/tests/unit/test_forgejo_pr_source.py @@ -641,3 +641,76 @@ async def test_a_failure_mid_walk_keeps_what_the_settled_pages_gave() -> None: cursor = max(p.updated_at for p in prs) (more,) = await _passes(_live(rows, 2), cursor, 1) assert more[0] == len(got) + 1 + + +def _closed(number: int, closed: str, *, merged: bool = True) -> dict[str, Any]: + """`_pr(number)` closed at `closed`, merged then unless `merged` is False.""" + pr = _pr(number, "2026-11-20T01:00:00Z") + return {**pr, "closed_at": closed, "merged": merged, "merged_at": closed if merged else None} + + +@pytest.mark.asyncio +async def test_a_reopen_within_a_backfill_call_does_not_drop_the_pr_that_moved_up() -> None: + # Two PRs a page, newest close first: 4, 3 (closed unmerged), 2, 1. Reopening 3 + # right after page 1 is read moves 2 up onto page 1, so a walk that trusted its + # pages would read only 1 on page 2, return 4 and 1, and call the backfill done. + rows = [ + _closed(4, "2026-11-20T00:40:00Z"), + _closed(3, "2026-11-20T00:30:00Z", merged=False), + _closed(2, "2026-11-20T00:20:00Z"), + _closed(1, "2026-11-20T00:10:00Z"), + ] + client = _live(rows, 2, after={(1, 1): lambda: rows.pop(1)}) + with patch.object(forgejo, "get_client", return_value=client): + prs, nxt, _before = await forgejo.merged_prs_back_to( + API, "tok", datetime(2026, 11, 1), base="next" + ) + assert [p.number for p in prs] == [4, 2, 1] and nxt == 0 + + +@pytest.mark.asyncio +async def test_a_pr_closed_during_a_backfill_call_repeats_no_pr() -> None: + # A PR closed after page 1 is read lands at the top and pushes 2 down onto page 2: + # the walk reads page 1 again, and returns each PR once. + rows = [ + _closed(3, "2026-11-20T00:30:00Z"), + _closed(2, "2026-11-20T00:20:00Z"), + _closed(1, "2026-11-20T00:10:00Z"), + ] + newer = _closed(5, "2026-11-20T00:50:00Z") + client = _live(rows, 2, after={(1, 1): lambda: rows.insert(0, newer)}) + with patch.object(forgejo, "get_client", return_value=client): + prs, nxt, _before = await forgejo.merged_prs_back_to( + API, "tok", datetime(2026, 11, 1), base="next" + ) + assert [p.number for p in prs] == [3, 2, 1] and nxt == 0 + + +def test_a_pr_link_keeps_the_port_of_the_remote() -> None: + # A host served on 8443: the API URL and the PR link both keep the port, and the + # link reaches the evidence the blame op returns. + from server.code.domain.index import blame_range as br + + cfg = repo_config( + repo="forgejo.example.org/acme/widgets", + git_remote="https://forgejo.example.org:8443/acme/widgets.git", + forge="forgejo", + ) + link = "https://forgejo.example.org:8443/acme/widgets/pulls/7" + assert forgejo_api_repo(cfg.git_remote).startswith("https://forgejo.example.org:8443/") + assert pr_web_url(cfg.repo, 7, git_remote=cfg.git_remote, forge=cfg.forge) == link + (candidate,) = br.merge_legs( + br.Attribution(), + [{"pr_number": 7, "title": "Fix"}], + range_len=1, + branch_points=[], + repo=cfg.repo, + git_remote=cfg.git_remote, + forge=cfg.forge, + ) + assert candidate.url == link + # An SSH remote's port is its SSH port: the link is the API's, on HTTPS's own. + ssh = "ssh://git@forgejo.example.org:2222/acme/widgets.git" + assert pr_web_url(cfg.repo, 7, git_remote=ssh, forge="forgejo") == ( + "https://forgejo.example.org/acme/widgets/pulls/7" + ) From baba5d83958082e6c8260fc638b77e10e7463769 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Mon, 30 Nov 2026 11:41:17 +0000 Subject: [PATCH 6/9] Document the limit of the backfill's page-above check The check compares the page above with its first read. A PR reopened above it and another closed between the two reads of one step put that page back as it was, so the PR at the edge can still be missed, as can a shift of more than a page between two requests. A finished walk starts over at page 1 on the next run and reads it. Signed-off-by: Kaloyan Naumov --- server/clients/forgejo.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index f0cfdb430a5..98cb1973fe2 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -267,7 +267,12 @@ async def merged_prs_back_to( Within one call, the walk reads the page above again after each new page, and goes on only when it is unchanged: a PR reopened above moves the first PR of the new page onto the page above, and the walk then reads that page again, skipping the PRs it - has. A page is read whole, so `max_prs` is checked between pages, and should exceed + has. The check compares the page above with its first read, so a PR reopened above + it and another closed between the two reads of one step, which put that page back + as it was, can still hide the PR at the edge, as can a shift of more than a page + between two requests; a finished walk starts over at page 1 on the next run and + reads it. + A page is read whole, so `max_prs` is checked between pages, and should exceed the number of PRs closed in one second, or a resume re-reads the boundary second and makes no progress. The deep-history backfill: the API has no merged-date search, and close time is merge time for a merged PR. `sort=recentclose` needs Forgejo 12 or From da4507b75c956186f1b284e433a7ee63eb14010f Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 11:51:13 +0000 Subject: [PATCH 7/9] Mark the Forgejo page re-read count as not a setting test_no_new_tunable_constant flagged server/clients/forgejo.py::_ATTEMPTS, a numeric constant named like a retry count. It bounds the re-reads of one page while the closed-PR list moves under the walk, a consistency retry rather than an operator knob. The CLI's _LIST_ATTEMPTS in server/cli/okf.py is the same shape and carries the same marker, so this follows it instead of adding a setting. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/clients/forgejo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 98cb1973fe2..2b0e9662b3f 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -35,7 +35,7 @@ # Forgejo caps a page at its own MAX_RESPONSE_ITEMS (50 by default), so a larger value # would change nothing. _PAGE_SIZE = 50 # not a setting: the server's own cap -_ATTEMPTS = 3 # reads of one page, while the list moves under the walk +_ATTEMPTS = 3 # not a setting: a consistency retry while the list moves under the walk def _headers(token: str) -> dict[str, str]: From 4a90139d555b8d1b924d95a599bd329fb8df52ef Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Tue, 1 Dec 2026 21:11:12 +0000 Subject: [PATCH 8/9] Verify a Forgejo host against LOOM_CODE_GIT_CA_FILE The Forgejo REST client went through the shared httpx client, which trusts only the default roots. A Forgejo host under a private authority, which git already reaches through LOOM_CODE_GIT_CA_FILE, failed every list and files request with CERTIFICATE_VERIFY_FAILED, so the worker and backfill-prs wrote no PR history. The client now takes its trust from the same setting: get_ca_client builds a pooled client whose SSL context loads that bundle in place of the default roots, as git's http.sslCAInfo does, and an unset bundle keeps the shared client. A bundle that cannot be read is a GitHubError, so the worker's stop-and-keep-the- cursor path handles it. No new setting; the setting's description and the operations page now name the Forgejo client. The new test serves a Forgejo list over TLS from a generated authority: it is read with that bundle, refused with no bundle or another authority's, and an unreadable bundle is a GitHubError. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 5 +- docs/reference/configuration.md | 2 +- loom.example.yaml | 6 +- schemas/loom-settings.schema.json | 2 +- server/clients/_http.py | 23 ++++++- server/clients/forgejo.py | 13 +++- server/settings/catalog.py | 3 +- tests/unit/test_forgejo_ca_file.py | 82 ++++++++++++++++++++++++ 8 files changed, 126 insertions(+), 10 deletions(-) create mode 100644 tests/unit/test_forgejo_ca_file.py diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 9b5334af87e..211590c2f74 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -151,7 +151,10 @@ applies to every git a repository job runs, the compiler tier's dependency fetch submodule updates included, not only the entry's remote, so include the public roots when any of those reach a public host. Repository jobs read no system or global git config and inherit no `GIT_SSL_CAINFO` or `SSL_CERT_FILE`, so this setting is how a -bundle reaches them. Loom does not check the path when it loads the setting: name an +bundle reaches them. The Forgejo REST client behind a Forgejo entry's PR history +verifies the host against the same bundle, in place of its default roots, whether the +entry's `git_remote` is HTTPS or SSH, so the bundle vouches for that host too. Loom +does not check the path when it loads the setting: name an absolute path to a file the job can see. The sandbox mounts `/etc/ssl`, `/etc/ca-certificates` and `/usr` read-only, so `/etc/ssl` is the place to put the bundle; a link works when its target is inside one of those trees too. A relative path, diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index c9861fcc318..3930d86200a 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -362,7 +362,7 @@ Resource limits (rlimits) for each process of a sandboxed repository job (clone, | `LOOM_CODE_GIT_LEDGER_MERGE_BATCH` | `int` | `40` | | Missing ledger merge shas fetched per entry per pass (40 take about 8.5 s). | | `LOOM_CODE_GIT_FETCH_PR_HEADS` | `bool` | `True` | | The mirror carries `refs/pull/N/head` for every PR the ledger holds OPEN (refetched when the tip moves, never pruned), so pre-merge reads diff the PR's own head. Only open heads: fetching every PR head is too costly. Per-entry `git_fetch_pr_heads` overrides. Off = the overlay reports `head_not_in_mirror`. | | `LOOM_CODE_GIT_PR_HEAD_BATCH` | `int` | `200` | | Max PR heads fetched per shared mirror per ingest pass. | -| `LOOM_CODE_GIT_CA_FILE` | `str` | `''` | | PEM bundle git verifies https remotes with, in place of its default roots (a server under a private authority); under /etc/ssl, which the job sandbox mounts. code_git_proxy_ca_file takes its place through the proxy. Empty = default roots. | +| `LOOM_CODE_GIT_CA_FILE` | `str` | `''` | | PEM bundle git verifies https remotes with, in place of its default roots (a server under a private authority); under /etc/ssl, which the job sandbox mounts. The Forgejo REST client verifies a Forgejo host against it too. code_git_proxy_ca_file takes its place through the proxy. Empty = default roots. | ### Git through a forward proxy diff --git a/loom.example.yaml b/loom.example.yaml index 628605172ee..9ced0ab7db1 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1296,9 +1296,9 @@ settings: # code_git_pr_head_batch: 200 # PEM bundle git verifies https remotes with, in place of its default roots (a server - # under a private authority); under /etc/ssl, which the job sandbox mounts. - # code_git_proxy_ca_file takes its place through the proxy. Empty = default roots. - # [restart] + # under a private authority); under /etc/ssl, which the job sandbox mounts. The + # Forgejo REST client verifies a Forgejo host against it too. code_git_proxy_ca_file + # takes its place through the proxy. Empty = default roots. [restart] # code_git_ca_file: "" # --- git through a forward proxy --- diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 75e39cd40e8..1476b044043 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1203,7 +1203,7 @@ "code_git_ca_file": { "default": "", "type": "string", - "description": "PEM bundle git verifies https remotes with, in place of its default roots (a server under a private authority); under /etc/ssl, which the job sandbox mounts. code_git_proxy_ca_file takes its place through the proxy. Empty = default roots." + "description": "PEM bundle git verifies https remotes with, in place of its default roots (a server under a private authority); under /etc/ssl, which the job sandbox mounts. The Forgejo REST client verifies a Forgejo host against it too. code_git_proxy_ca_file takes its place through the proxy. Empty = default roots." }, "code_git_dir": { "default": "", diff --git a/server/clients/_http.py b/server/clients/_http.py index 387d67833ca..8929a8d1fe2 100644 --- a/server/clients/_http.py +++ b/server/clients/_http.py @@ -21,6 +21,7 @@ from __future__ import annotations +import ssl import threading from typing import Any @@ -33,6 +34,7 @@ _lock = threading.Lock() _client: httpx.AsyncClient | None = None _model_client: httpx.AsyncClient | None = None +_ca_clients: dict[str, httpx.AsyncClient] = {} # Provider credentials that ride a header other than Authorization. _KEY_HEADERS = ("x-api-key", "x-goog-api-key", "api-key") @@ -133,6 +135,22 @@ def get_client() -> httpx.AsyncClient: return _client +def get_ca_client(ca_file: str) -> httpx.AsyncClient: + """Return the shared client for a server under a private certificate authority: + it verifies against the PEM bundle `ca_file` in place of the default roots, the way + git does with `http.sslCAInfo`. An empty `ca_file` is `get_client()`. An unreadable + bundle raises `OSError` (`ssl.SSLError` for a malformed PEM) and leaves no client behind.""" + if not ca_file: + return get_client() + with _lock: + client = _ca_clients.get(ca_file) + if client is None: + client = _ca_clients[ca_file] = _build( + verify=ssl.create_default_context(cafile=ca_file) + ) + return client + + def get_model_client() -> httpx.AsyncClient: """Return the shared client for model calls, its gateway hook in place.""" global _model_client @@ -147,9 +165,10 @@ def get_model_client() -> httpx.AsyncClient: async def aclose() -> None: - """Drain both connection pools. Idempotent; safe at shutdown.""" + """Drain every connection pool. Idempotent; safe at shutdown.""" global _client, _model_client - clients = [c for c in (_client, _model_client) if c is not None] + clients = [c for c in (_client, _model_client, *_ca_clients.values()) if c is not None] _client = _model_client = None + _ca_clients.clear() for c in clients: await c.aclose() diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 2b0e9662b3f..4144553c926 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -23,7 +23,7 @@ import httpx -from server.clients._http import get_client +from server.clients._http import get_ca_client from server.clients.github import ( GitHubError, MergedPR, @@ -31,6 +31,7 @@ pr_assignees, pr_base_ref, ) +from server.settings import settings # Forgejo caps a page at its own MAX_RESPONSE_ITEMS (50 by default), so a larger value # would change nothing. @@ -38,6 +39,12 @@ _ATTEMPTS = 3 # not a setting: a consistency retry while the list moves under the walk +def get_client() -> httpx.AsyncClient: + """The client for the Forgejo host: it verifies against `LOOM_CODE_GIT_CA_FILE`, the + bundle git trusts the same host by, and against the default roots when that is unset.""" + return get_ca_client(settings.code_git_ca_file) + + def _headers(token: str) -> dict[str, str]: h = {"Accept": "application/json", "User-Agent": "loom-code-intel/1.0"} if token: @@ -58,6 +65,10 @@ async def _get_page( resp = await get_client().get(url, headers=_headers(token), params=params) except httpx.RequestError as e: raise GitHubError(f"GET {url} -> {type(e).__name__}") from e + except OSError as e: # the CA bundle cannot be read + raise GitHubError( + f"LOOM_CODE_GIT_CA_FILE {settings.code_git_ca_file} cannot be read: {e.strerror or e}" + ) from e if resp.status_code == 429: raise RateLimited(f"rate limited; retry after {resp.headers.get('Retry-After', '?')}s") if resp.status_code >= 400: diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 3169eb78d88..1ea721a241f 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1103,7 +1103,8 @@ class CodeSettings(BaseModel): # Max PR heads fetched per shared mirror per ingest pass. code_git_pr_head_batch: int = 200 # PEM bundle git verifies https remotes with, in place of its default roots (a server - # under a private authority); under /etc/ssl, which the job sandbox mounts. + # under a private authority); under /etc/ssl, which the job sandbox mounts. The + # Forgejo REST client verifies a Forgejo host against it too. # code_git_proxy_ca_file takes its place through the proxy. Empty = default roots. code_git_ca_file: str = "" # The code index's network git (clone, fetch, ls-remote, submodule update) through diff --git a/tests/unit/test_forgejo_ca_file.py b/tests/unit/test_forgejo_ca_file.py new file mode 100644 index 00000000000..9be7405d7f0 --- /dev/null +++ b/tests/unit/test_forgejo_ca_file.py @@ -0,0 +1,82 @@ +"""A Forgejo host under a private certificate authority: its REST requests verify the +server against the bundle `LOOM_CODE_GIT_CA_FILE` names, the one git uses for the same +host, and against the default roots when none is set.""" + +from __future__ import annotations + +import asyncio +import re +import ssl +from collections.abc import AsyncIterator +from pathlib import Path + +import pytest + +from server.clients import _http, forgejo +from server.clients.github import GitHubError +from server.settings import settings +from tests.unit.test_code_git_proxy_wire import _terminating_as + +_BODY = b"[]" + + +@pytest.fixture(autouse=True) +async def _fresh_pools() -> AsyncIterator[None]: + await _http.aclose() + yield + await _http.aclose() + + +async def _forgejo(tls: ssl.SSLContext) -> asyncio.Server: + """A TLS server on a free loopback port answering every request with an empty list.""" + + async def answer(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None: + try: + await reader.readuntil(b"\r\n\r\n") + head = ( + f"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {len(_BODY)}" + ) + writer.write(f"{head}\r\nConnection: close\r\n\r\n".encode() + _BODY) + await writer.drain() + except (OSError, asyncio.IncompleteReadError): + pass # the client hung up: it does not trust the certificate it was shown + finally: + writer.close() + + return await asyncio.start_server(answer, "127.0.0.1", 0, ssl=tls) + + +def _pulls(server: asyncio.Server) -> str: + return f"https://127.0.0.1:{server.sockets[0].getsockname()[1]}/api/v1/repos/acme/widgets/pulls" + + +async def test_a_forgejo_request_verifies_against_the_configured_ca( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + tls, authority, _ = _terminating_as("127.0.0.1", tmp_path) + monkeypatch.setattr(settings, "code_git_ca_file", str(authority)) + server = await _forgejo(tls) + async with server: + assert await forgejo._get_page(_pulls(server), "", {}) == ([], False) + + +@pytest.mark.parametrize("which", ["unset", "another authority"]) +async def test_a_certificate_the_bundle_does_not_vouch_for_is_refused( + which: str, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + tls, _, other = _terminating_as("127.0.0.1", tmp_path) + monkeypatch.setattr(settings, "code_git_ca_file", str(other) if which != "unset" else "") + server = await _forgejo(tls) + async with server: + with pytest.raises(GitHubError, match="ConnectError"): + await forgejo._get_page(_pulls(server), "", {}) + + +async def test_an_unreadable_bundle_is_a_github_error( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + missing = str(tmp_path / "missing.pem") + monkeypatch.setattr(settings, "code_git_ca_file", missing) + message = f"LOOM_CODE_GIT_CA_FILE {missing} cannot be read: No such file or directory" + with pytest.raises(GitHubError, match=re.escape(message)): + await forgejo._get_page("https://127.0.0.1:1/api/v1/repos/a/b/pulls", "", {}) From fd1d10f7f1abb56a79c6dfe34cd817aa33af602a Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Wed, 2 Dec 2026 00:47:17 +0000 Subject: [PATCH 9/9] An unreadable Forgejo CA bundle raises a message without the path The GitHubError raised when LOOM_CODE_GIT_CA_FILE cannot be read carried the configured path and the OS error text, and the history worker records that message in its result. It now names only the setting; the path and the OS error go to a warning on loom.clients.forgejo. The exception-text ratchet fails on the previous head and passes with this change. Co-Authored-By: Claude Sonnet 5.5 Signed-off-by: Kaloyan Naumov --- server/clients/forgejo.py | 8 +++++--- tests/unit/test_forgejo_ca_file.py | 17 +++++++++++------ 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/server/clients/forgejo.py b/server/clients/forgejo.py index 4144553c926..83ad73ac02a 100644 --- a/server/clients/forgejo.py +++ b/server/clients/forgejo.py @@ -18,6 +18,7 @@ from __future__ import annotations +import logging from datetime import UTC, datetime from typing import Any @@ -33,6 +34,8 @@ ) from server.settings import settings +logger = logging.getLogger("loom.clients.forgejo") + # Forgejo caps a page at its own MAX_RESPONSE_ITEMS (50 by default), so a larger value # would change nothing. _PAGE_SIZE = 50 # not a setting: the server's own cap @@ -66,9 +69,8 @@ async def _get_page( except httpx.RequestError as e: raise GitHubError(f"GET {url} -> {type(e).__name__}") from e except OSError as e: # the CA bundle cannot be read - raise GitHubError( - f"LOOM_CODE_GIT_CA_FILE {settings.code_git_ca_file} cannot be read: {e.strerror or e}" - ) from e + logger.warning("LOOM_CODE_GIT_CA_FILE %s cannot be read: %s", settings.code_git_ca_file, e) + raise GitHubError("LOOM_CODE_GIT_CA_FILE cannot be read") from e if resp.status_code == 429: raise RateLimited(f"rate limited; retry after {resp.headers.get('Retry-After', '?')}s") if resp.status_code >= 400: diff --git a/tests/unit/test_forgejo_ca_file.py b/tests/unit/test_forgejo_ca_file.py index 9be7405d7f0..35d59ea22f0 100644 --- a/tests/unit/test_forgejo_ca_file.py +++ b/tests/unit/test_forgejo_ca_file.py @@ -5,7 +5,7 @@ from __future__ import annotations import asyncio -import re +import logging import ssl from collections.abc import AsyncIterator from pathlib import Path @@ -72,11 +72,16 @@ async def test_a_certificate_the_bundle_does_not_vouch_for_is_refused( await forgejo._get_page(_pulls(server), "", {}) -async def test_an_unreadable_bundle_is_a_github_error( - monkeypatch: pytest.MonkeyPatch, tmp_path: Path +async def test_an_unreadable_bundle_is_a_github_error_that_names_only_the_setting( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: missing = str(tmp_path / "missing.pem") monkeypatch.setattr(settings, "code_git_ca_file", missing) - message = f"LOOM_CODE_GIT_CA_FILE {missing} cannot be read: No such file or directory" - with pytest.raises(GitHubError, match=re.escape(message)): - await forgejo._get_page("https://127.0.0.1:1/api/v1/repos/a/b/pulls", "", {}) + with caplog.at_level(logging.WARNING, logger="loom.clients.forgejo"): + with pytest.raises(GitHubError) as raised: + await forgejo._get_page("https://127.0.0.1:1/api/v1/repos/a/b/pulls", "", {}) + assert str(raised.value) == "LOOM_CODE_GIT_CA_FILE cannot be read" + [record] = [r for r in caplog.records if r.name == "loom.clients.forgejo"] + assert record.levelno == logging.WARNING + assert missing in record.getMessage() + assert "No such file or directory" in record.getMessage()