Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ LOOM_CODE_REPOS_JSON='[
| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------- |
| `namespace`, `org` | where the index lives |
| `repo` | `owner/name` on GitHub |
| `git_dir`, `git_remote` | the bare clone and its remote; branches of one repository share one clone |
| `git_dir`, `git_remote` | the bare clone and its remote; entries that share a clone name the same remote |
| `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 |
| `exclude` | globs never indexed (list or comma-separated) |
Expand Down Expand Up @@ -219,8 +219,17 @@ and a `.loomignore` file at the indexed commit are honoured as excludes. A depen
vendored as a git submodule is not in the bare mirror; give it its own entry and name it
in `depends_on`. The gauge `loom.code.repos_config_errors` reports entries the server
could not use (invalid JSON, a nameless entry, a namespace with `.` or `/`, a duplicate
namespace); 0 means the value parsed clean. Validate the JSON before a restart
with `docker compose --env-file .env -f dev/docker-compose.cloud.yml config`.
namespace, a clone an earlier entry holds with another remote); 0 means the value parsed
clean. While it is not 0 the mirror sweep removes nothing on any host, so the mirrors,
checkouts and lock files of removed repositories stay until the error is fixed. Entries
that share a `git_dir` share its clone only when their `git_remote` values, after the
defaults, are the same string: branches of one repository use one spelling of the
remote, and a fork beside its upstream sets its own `git_dir`. Name one clone with one
spelling of its `git_dir` in every entry that shares it. On a case-insensitive volume,
two `git_dir` values that differ only in case are one directory; the check sees that
once the directory exists, and before the first clone both spellings pass. Use clone
paths that differ by more than capitalization. Validate the JSON before a restart with
`docker compose --env-file .env -f dev/docker-compose.cloud.yml config`.

Who can read an index is governed by the namespace's join policy and grants
([tokens and grants](../guides/tokens-and-grants.md)). `LOOM_CODE_ORG_READABLE=true`
Expand Down
50 changes: 48 additions & 2 deletions server/code/domain/index/repos.py
Original file line number Diff line number Diff line change
Expand Up @@ -380,8 +380,9 @@ def configured_repos() -> list[RepoConfig]:


def known_repo_count() -> int:
"""How many entries this process knows are configured (no I/O): the operator's, and
the self-service registry's once it is read. Zero means no repository job is owed
"""How many entries this process knows are configured (no store read; a `realpath`
and a stat of each entry's clone dir): the operator's, and the self-service
registry's once it is read. Zero means no repository job is owed
(`sandbox.job_owed`)."""
return len(_operator_entries() if registry_unread() else configured_repos())

Expand Down Expand Up @@ -536,6 +537,9 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC
base = _scalar_repo(config)
repos: list[RepoConfig] = []
seen: set[str] = set()
# A fork and its upstream derive the same clone dir; in one clone each fetch would
# move the other's branch refs.
clone_holders: dict[str | tuple[int, int], tuple[str, str]] = {}
for i, e in enumerate(entries):
if not isinstance(e, dict) or not e.get("namespace"):
errors[f"entry:{i}"] = f"code repo entry missing 'namespace', skipped: {e!r}"
Expand Down Expand Up @@ -579,6 +583,8 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC
proxy_identity = _entry_git_proxy_identity(e, ns, errors)
if proxy_identity is None:
continue
if _clone_taken(clone_holders, git_dir, git_remote, ns, errors):
continue
repos.append(
RepoConfig(
org=org,
Expand Down Expand Up @@ -629,6 +635,46 @@ def _configured_from_env(config: Settings, errors: dict[str, str]) -> list[RepoC
return repos


def _clone_keys(git_dir: str) -> list[str | tuple[int, int]]:
"""The keys one clone dir is held under: its canonical path, and its
`(st_dev, st_ino)` once it exists, so two spellings of one directory (a case alias
on a case-insensitive volume, a symlink, a bind mount) share a key. A directory
that cannot be read keeps the path key alone."""
keys: list[str | tuple[int, int]] = [os.path.realpath(git_dir)]
try:
st = os.stat(git_dir)
except OSError:
return keys
Comment thread
zlareb1 marked this conversation as resolved.
Resolved
keys.append((st.st_dev, st.st_ino))
return keys


def _clone_taken(
holders: dict[str | tuple[int, int], tuple[str, str]],
git_dir: str,
git_remote: str,
ns: str,
errors: dict[str, str],
) -> bool:
"""Whether an earlier entry holds `git_dir` with another `git_remote` (both after
`_entry_clone_fields` applies the defaults); records the entry's config error when
one does. The first entry claims a clone; branches share it by spelling the remote
the same way. Only this check treats two spellings of a directory as one (the same
canonical path, or the same directory by identity once it exists); the mirror
sweep, its lock files and `trunk_entry` compare `git_dir` as written."""
keys = _clone_keys(git_dir)
held_remote, held_ns = next((holders[k] for k in keys if k in holders), (git_remote, ns))
if held_remote == git_remote:
for k in keys:
holders.setdefault(k, (held_remote, held_ns))
return False
errors[f"git_dir:{ns}"] = (
f"code repo {ns} skipped: its clone {git_dir} is held by {held_ns} with another "
"git_remote; use one spelling of the remote, or set a separate git_dir"
)
return True


def _entry_clone_fields(
e: dict[str, Any],
ns: str,
Expand Down
177 changes: 177 additions & 0 deletions tests/unit/test_repos_clone_dir_collision.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
"""Two entries on one clone dir share the bare clone only when their `git_remote`
values, after the defaults, are the same: a fork and its upstream derive the same
clone dir, and one clone would let each fetch move the other's refs."""

from __future__ import annotations

import json
import os

import pytest

import server.code.domain.index.repos as repos


@pytest.fixture
def cfg(monkeypatch: pytest.MonkeyPatch, scalar_code_repo):
from server.settings import settings

def _set(entries):
monkeypatch.setattr(settings, "code_repos_json", json.dumps(entries))
repos._config_errors.clear()
repos._config_errors_logged.clear()
return {r.namespace: r for r in repos.configured_repos()}

return _set


def test_a_fork_and_its_upstream_do_not_share_a_clone(cfg) -> None:
got = cfg(
[
{
"namespace": "code-widgets-fork",
"repo": "git.example.com/acme/widgets",
"git_remote": "https://git.example.com/acme/widgets.git",
},
{"namespace": "code-widgets-upstream", "repo": "widgets-org/widgets"},
]
)
assert "code-widgets-fork" in got
assert "code-widgets-upstream" not in got
msg = repos._config_errors["git_dir:code-widgets-upstream"]
assert "code-widgets-fork" in msg
assert "use one spelling of the remote, or set a separate git_dir" in msg


def test_branches_with_one_spelling_of_the_remote_share_their_clone(cfg) -> None:
got = cfg(
[
{"namespace": "code-widgets", "repo": "acme/widgets", "git_branch": "main"},
{
"namespace": "code-widgets-2-4",
"repo": "acme/widgets",
"git_branch": "release/2.4",
"git_remote": "https://github.com/acme/widgets.git",
},
]
)
assert got["code-widgets"].git_dir == got["code-widgets-2-4"].git_dir
assert repos.config_error_count() == 0


def test_two_spellings_of_one_remote_are_refused(cfg) -> None:
got = cfg(
[
{"namespace": "code-widgets", "repo": "acme/widgets", "git_branch": "main"},
{
"namespace": "code-widgets-2-4",
"repo": "acme/widgets",
"git_branch": "release/2.4",
"git_remote": "git@github.com:acme/widgets.git",
},
]
)
assert "code-widgets" in got
assert "code-widgets-2-4" not in got
msg = repos._config_errors["git_dir:code-widgets-2-4"]
assert "code-widgets" in msg
assert "use one spelling of the remote, or set a separate git_dir" in msg


def test_a_separate_git_dir_lets_both_in(cfg) -> None:
got = cfg(
[
{
"namespace": "code-widgets-fork",
"repo": "git.example.com/acme/widgets",
"git_remote": "https://git.example.com/acme/widgets.git",
},
{
"namespace": "code-widgets-upstream",
"repo": "widgets-org/widgets",
"git_dir": "var/code_repos/widgets-upstream.git",
},
]
)
assert got["code-widgets-fork"].git_dir != got["code-widgets-upstream"].git_dir
assert repos.config_error_count() == 0


def _two_repositories(first_dir: str, second_dir: str) -> list[dict[str, str]]:
return [
{"namespace": "code-widgets-fork", "repo": "acme/widgets", "git_dir": first_dir},
{
"namespace": "code-widgets-upstream",
"repo": "widgets-org/widgets",
"git_dir": second_dir,
},
]


def test_two_spellings_of_one_clone_are_one_clone(
cfg, monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
monkeypatch.chdir(tmp_path)
got = cfg(_two_repositories("var/widgets.git", str(tmp_path / "var" / "widgets.git")))
assert "code-widgets-fork" in got
assert "code-widgets-upstream" not in got
assert "code-widgets-fork" in repos._config_errors["git_dir:code-widgets-upstream"]


def test_a_symlink_to_a_held_clone_is_the_same_clone(
cfg, monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
monkeypatch.chdir(tmp_path)
(tmp_path / "widgets.git").mkdir()
(tmp_path / "alias.git").symlink_to(tmp_path / "widgets.git")
got = cfg(_two_repositories("widgets.git", "alias.git"))
assert "code-widgets-upstream" not in got
assert "git_dir:code-widgets-upstream" in repos._config_errors


def test_a_case_alias_of_a_held_clone_is_the_same_clone(
cfg, monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
# One directory, as on a case-insensitive volume: the lookup of either spelling
# finds `Widget.git`, so `os.stat` reports the same identity for both.
monkeypatch.chdir(tmp_path)
(tmp_path / "Widget.git").mkdir()
real_stat = os.stat

def stat(path, *args, **kwargs):
if os.path.basename(path).lower() == "widget.git":
path = tmp_path / "Widget.git"
return real_stat(path, *args, **kwargs)

monkeypatch.setattr(os, "stat", stat)
got = cfg(_two_repositories("Widget.git", "widget.git"))
assert "code-widgets-fork" in got
assert "code-widgets-upstream" not in got
assert "code-widgets-fork" in repos._config_errors["git_dir:code-widgets-upstream"]


def test_a_missing_spelling_of_a_held_clone_is_the_same_clone(
cfg, monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
# `os.stat` fails on the missing component while the canonical path collapses `..`:
# the entry has no identity yet but still names the held directory.
monkeypatch.chdir(tmp_path)
(tmp_path / "widgets.git").mkdir()
got = cfg(_two_repositories("widgets.git", "missing/../widgets.git"))
assert "code-widgets-fork" in got
assert "code-widgets-upstream" not in got
assert "code-widgets-fork" in repos._config_errors["git_dir:code-widgets-upstream"]


def test_clone_dirs_that_differ_only_in_case_stay_distinct_on_a_case_sensitive_volume(
cfg, monkeypatch: pytest.MonkeyPatch, tmp_path
) -> None:
monkeypatch.chdir(tmp_path)
(tmp_path / "Widget.git").mkdir()
(tmp_path / "widget.git").mkdir(exist_ok=True)
if len(list(tmp_path.iterdir())) != 2:
pytest.skip("the volume is case-insensitive: both spellings are one directory")
got = cfg(_two_repositories("Widget.git", "widget.git"))
assert "code-widgets-fork" in got
assert "code-widgets-upstream" in got
assert repos.config_error_count() == 0
Loading