diff --git a/docs/architecture/rolling-upgrades.md b/docs/architecture/rolling-upgrades.md index 88cc314cef..def3d88b90 100644 --- a/docs/architecture/rolling-upgrades.md +++ b/docs/architecture/rolling-upgrades.md @@ -960,6 +960,15 @@ See the [participant lifecycle baseline](cells.md#participant-lifecycle-baseline the saga on those in `code_chunks` and `code_summaries`, and it is repeated. No gate holds the rollout. +66. **A definition renamed as it moves to another file or scope** + (`server/code/domain/successor.py::elsewhere`): N's link recheck follows it; N-1's + reads the link `missing`, as before. One host rechecks a repository at a time, so a + range is read by one build. A `missing` link is never handed to a definition added + since, so a link N-1 read `missing` during the rollout stays `missing` under N + until its own name returns. The link rows are unchanged; `wide_ranges` is one more + number in the `memory_code_links` pass outcome, which every build serves as stored. No gate holds the + rollout. + ## What checks them `scripts/gates/mixed_version.py` (`make test-mixed-version`, the `mixed-version` CI job, diff --git a/docs/concepts/memory.md b/docs/concepts/memory.md index 19494eb8cc..42d6e2dd28 100644 --- a/docs/concepts/memory.md +++ b/docs/concepts/memory.md @@ -465,12 +465,34 @@ A memory's detail in the dashboard lists these links with their state ([clip](../assets/screenshots/clip-memory-linked-code.webm)). A link follows its definition through file moves, renames (with an edit, when the new -name is related to the old), and its class's rename within the file. A namesake in -another class or namespace never inherits a link, and a `missing` link comes back only -when its own name does. A definition moved to another file under its own name with an edit is followed -there when its text is close to the one the link last read. A new definition left where -it was stops that search only when it may be the old one under a new name: an export -list or an unrelated function added beside it does not. A name gone from its file is +name is related to the old), and its class's rename within the file. A definition +renamed as it moves to another file, class or namespace is looked for among the +definitions the changed files did not have before: the only one with its tokens under +another name reads `moved`; failing that, the only one of its own name with a close text +reads `changed`, unless a definition of that name that stayed in the changed files is +close as well. A member reads `changed` there unless its class came with it unchanged. A +definition under 30 tokens is told by neither its text nor its own name, which any class +may define: it is followed there only under a name of the same words (`_read_rows` or +`read_rows_v2` for `read_rows`) and with its scope, from module level to module level +or, once no member of its class is left in its file, into the class that is that one +renamed or keeps its members. Two definitions that may be it, +or one that another removed definition may have become, leave the link `unresolved`. A +range that changed more than 32 files under the entry's `path_prefixes` is not searched +this way, and a warning in the server log names it; nor is a range whose diff cannot be +read. Over such a range a live link is read as if nothing was renamed. An `unresolved` +link is looked for from the commit its code was last read at, so its range grows with +every commit. While that range is searched, the link is followed once one definition +that may be it is left. Over a range that is not searched it stays `unresolved`, and no +later commit narrows that range. The `memory_code_links` worker's pass outcome counts in +`wide_ranges` the ranges its own pass followed, not those a `code.refresh` call followed +first. A +namesake that was already there never inherits a link, and a `missing` link comes back +only when its own name does. A definition moved to another file under its own name with +an edit is followed there when its text is close to the one the link last read. A new +definition left where it was stops that search only when it may be the old one under a +new name: an export list or an unrelated function added beside it does not. The search +for a definition renamed as it moved is not made past a new definition left there, +unless that one is another definition renamed alone. A name gone from its file is looked for in the files changed since its last check as the mirror holds them, beside the index, so a definition moved by a commit the index has not taken in whole (past `code_ingest_max_files_per_commit`) is diff --git a/docs/use-cases/memory-linked-to-code.md b/docs/use-cases/memory-linked-to-code.md index c67655eea6..97c80400af 100644 --- a/docs/use-cases/memory-linked-to-code.md +++ b/docs/use-cases/memory-linked-to-code.md @@ -33,8 +33,11 @@ reported commit](#check-a-lesson-after-a-code-edit). - **Links that follow refactors.** On every indexed commit, each link reads `fresh`, `moved`, `changed` (naming the commit that changed it), `unresolved` or `missing`. A link records the definition's tokens, so whitespace, comments and most formatter changes leave - it `fresh`. A link to a file follows the lines that hold a name the memory cites, and - is replaced by a link to a definition the memory names once the file defines it. + it `fresh`. A definition renamed as it moves to another file or class is followed + when one new definition there is it: `moved` with the same tokens, `changed` with an + edit or outside its class. A link to a file follows the lines that hold a name the + memory cites, and is replaced by a link to a definition the memory names once the + file defines it. [Link states](../concepts/memory.md#memories-linked-to-code) - **The current name beside a memory written against the old one.** A rename leaves the memory's text as it was written. These reads name where the code is now: diff --git a/server/code/domain/successor.py b/server/code/domain/successor.py index 5a9a2f3fa7..7a32edebda 100644 --- a/server/code/domain/successor.py +++ b/server/code/domain/successor.py @@ -8,6 +8,12 @@ answer is uncertain, never a removal. When no declaration of them has a text close to it, under any name, it is not among them (`unmatched`): it may still have moved to another file. + +Where that search finds nothing, the definition may have been renamed as it moved to +another file or scope (`elsewhere`): among the definitions the changed files did not have +before, the one with its exact shape, or the one of its own name with a close text. A +small definition is told by neither: it is followed there only with its scope, under a +name of its own words. """ from __future__ import annotations @@ -139,6 +145,154 @@ def successor(was: Definition, before: Side, now: Side) -> Successor: return Successor(None, uncertain=bool(pool) or contested, unmatched=unmatched) +def elsewhere( + was: Definition, + before: Side, + new: Sequence[Side], + gone: Sequence[Side], + kept: Sequence[Side] = (), +) -> Successor: + """What `was` (in `before`) became in another file or scope, where the search of its + own found nothing. `new` holds, file by file, the definitions a file did not define + before; `gone` those whose name left their file, `was` among them: one new definition + is the successor of one of them at most; `kept` those the changed files still define + under a name they had. + + The one with its exact shape is it renamed alone; else the one of its own name with + a close text is it edited, when no definition of that name that stayed is close too + (`_same_name`). A small definition is followed only with its scope and under a name + of its own words (`_may_be`). A member is carried unless its class came with it + unchanged. Several that may be it, or one another removed definition may have + become, are uncertain.""" + small = len(_TOKEN.findall(before.text(was))) < _SMALL + vacated = small and _vacated(_scope_of(was), before, gone) + had = {side.path: side for side in kept} + arrived = [ + (d, side) + for side in new + for d in side.defs + if not small or _may_be(was, before, d, side, had.get(side.path), vacated) + ] + rivals = [ + (r, side) + for side in gone + for r in side.defs + if (side.path, r.qualified_name) != (before.path, was.qualified_name) + ] + found = _same_shape(was, before, arrived, [r for r, _ in rivals]) + if found is not None: + return found + stayed = [(d, side) for side in kept for d in side.defs] + return _same_name(was, before, arrived, rivals, stayed) + + +def _may_be( + was: Definition, before: Side, d: Definition, now: Side, had: Side | None, vacated: bool +) -> bool: + """Whether a small `was` may be `d` in another file or scope. Under `_SMALL` tokens + a text is mostly its signature, and its own name is one any class may define + (`__iter__`, `close`): it goes only with its scope, module level to module level or + into the successor of its class. A class has one only once no member of it is left + in its file (`vacated`): that class renamed alone, or the one keeping its members, + weighed with those it already had (`had`: what `now`'s file kept), so a class that + took two methods in is not it. And only under a name of its own words (`_read_rows`, + `read_rows_v2`): one shared word is no kinship among every changed file, where two + stubs have one shape (`class ReadError(Exception): pass`, `RetryError`).""" + a, b = _words(was.name), _words(d.name) + if not a or _unversioned(a) != _unversioned(b): + return False + scope, target = _scope_of(was), _scope_of(d) + if not scope or not target: + return scope == target + if not vacated: + return False + if _renamed_alone(scope, target, before, now): + return True + old, kept = _layout(before)[0][scope], _layout(now)[0][target] + own = _layout(had)[0][target] if had is not None else set() + shared = len(old & kept) + return shared >= _MIN_SHARED and shared / len(old | kept | own) >= _KEPT_MEMBERS + + +def _vacated(scope: str, before: Side, gone: Sequence[Side]) -> bool: + """No member of `scope` is left in `before`'s file: each is among `gone`. Its own + name may stay, as an alias of the class it became.""" + left = {_unnumbered(r) for side in gone if side.path == before.path for r in side.defs} + names = {_unnumbered(d) for d in before.defs} + return all(n in left for n in names if n.startswith(scope + ".")) + + +def _same_shape( + was: Definition, + before: Side, + arrived: list[tuple[Definition, Side]], + rivals: list[Definition], +) -> Successor | None: + """`was` renamed alone into one of `arrived`: the only one with its exact shape. + None when no such definition arrived.""" + shape, name = was.shape.exact, _bare(was) + if not shape: + return None + same = [(d, side) for d, side in arrived if d.shape.exact == shape] + rivals = [r for r in rivals if r.shape.exact == shape] + # a removed definition and a new one of this shape under one name are each other's + paired = ({_bare(d) for d, _ in same} & {_bare(r) for r in rivals}) - {name} + same = [(d, side) for d, side in same if _bare(d) not in paired] + rivals = [r for r in rivals if _bare(r) not in paired] + if own := [(d, side) for d, side in same if _bare(d) == name]: + # under its own name: only another removed definition of that name contests it + same, rivals = own, [r for r in rivals if _bare(r) == name] + if len(same) == 1 and not rivals: + d, side = same[0] + carried = _left_its_class(was, before, d, side) + return Successor(d, exact=not carried, carried=carried) + return Successor(None, uncertain=True) if same else None + + +def _same_name( + was: Definition, + before: Side, + arrived: list[tuple[Definition, Side]], + rivals: list[tuple[Definition, Side]], + stayed: list[tuple[Definition, Side]], +) -> Successor: + """`was` edited as it moved to another scope: the only one of `arrived` with its + bare name and a close text. Not when a removed namesake is close to that one as + well, nor when a namesake that `stayed` is close to `was`: a name sibling classes + share (`get`, `__call__`) has close texts under names that never moved, and one of + those, which never inherits a link, may be what `was` became.""" + name, text = _bare(was), before.text(was) + + def like(found: list[tuple[Definition, Side]]) -> list[tuple[Definition, Side, float | None]]: + return [(d, s, _similar(text, was, s.text(d), d)) for d, s in found if _bare(d) == name] + + scores = like(arrived) + close = [(d, side) for d, side, score in scores if score is not None and score >= _CLOSE] + unknown = any(score is None for _, _, score in scores) + if len(close) == 1 and not unknown: + d, side = close[0] + contested = any( + _bare(r) == name and _maybe_close(r, d, then, side) for r, then in rivals + ) or any(score is None or score >= _CLOSE for _, _, score in like(stayed)) + if not contested: + return Successor(d, carried=_left_its_class(was, before, d, side)) + return Successor(None, uncertain=bool(close) or unknown) + + +def _left_its_class(was: Definition, before: Side, d: Definition, now: Side) -> bool: + """`d` is not among what surrounded `was`: one of them is a member, and `was`'s class + is not `d`'s with nothing but its name changed.""" + scope, target = _scope_of(was), _scope_of(d) + if not scope and not target: + return False + return not (scope and target and _renamed_alone(scope, target, before, now)) + + +def _bare(d: Definition) -> str: + """`d`'s own name, the index's ordinal dropped.""" + return unnumbered(bare_name(d.qualified_name)) + + def _renamed_alone(scope: str, target: str, before: Side, now: Side) -> bool: """Whether class `scope` became `target` with nothing but its name changed: the same rename shape.""" diff --git a/server/memory/app/code_link_pass.py b/server/memory/app/code_link_pass.py index a2773aac45..e9100c400f 100644 --- a/server/memory/app/code_link_pass.py +++ b/server/memory/app/code_link_pass.py @@ -14,8 +14,10 @@ from server.code.domain.anchor import ( Definition, Link, + local_name, + unnumbered, ) -from server.code.domain.successor import Successor +from server.code.domain.successor import Side, Successor from server.memory.store.code_links import LinkRow from server.memory.store.key_write_lock import KeyWriteLocks from server.settings import settings @@ -34,6 +36,8 @@ class PassResult: unlinked: int = 0 rechecked: int = 0 suggested: int = 0 + # ranges that changed too many files to look in for a definition renamed as it moved + wide_ranges: int = 0 errors: list[str] = field(default_factory=list) def as_dict(self) -> dict[str, Any]: @@ -43,6 +47,7 @@ def as_dict(self) -> dict[str, Any]: "unlinked": self.unlinked, "rechecked": self.rechecked, "suggested": self.suggested, + "wide_ranges": self.wide_ranges, "errors": len(self.errors), } @@ -68,6 +73,18 @@ class Range: paths: dict[str, str] +@dataclass(frozen=True) +class Turnover: + """The definitions a range brought in, took out and left, file by file: `new` the + files at its head, each with the definitions whose name it did not define at the + base, and `kept` with those whose name it did; `gone` the files at the base, each + with the definitions whose name it no longer defines.""" + + new: list[Side] + gone: list[Side] + kept: list[Side] + + # parsed files a pass keeps: a full recheck reads every linked file of a repository _FILES_CACHED = 512 @@ -99,8 +116,11 @@ def __init__(self, org: str, cns: str) -> None: self.org, self.cns = org, cns self._parsed: Recent[tuple[str, str], code.FileAt | None] = Recent(_FILES_CACHED) self._read: dict[tuple[Any, ...], Any] = {} - # ("here" | "elsewhere", …): the same-file search and the one in another module + # ("here" | "elsewhere" | "renamed", …): the same-file search, the one for its + # name in another module and the one for it under another name self.successors: dict[tuple[str, ...], Successor] = {} + # ranges `turnover` did not read: they changed more files than its limit + self.wide_ranges = 0 async def _once[T](self, key: tuple[Any, ...], read: Callable[[], Awaitable[T]]) -> T: if key not in self._read: @@ -246,6 +266,72 @@ async def touched(self, base: str, head: str) -> set[str] | None: ("touched", base, head), lambda: code.touched_paths(self.org, self.cns, base, head) ) + async def turnover(self, base: str, head: str, *, limit: int) -> Turnover | None: + """The definitions `base..head` brought in and took out of the files it changed, + those the ingest would not index left out, a renamed file read as one. None when + the range cannot be read (a force-push, a diff git fails on), or changed more + than `limit` files under the entry's prefixes: counted in `wide_ranges`.""" + + async def read() -> Turnover | None: + changed = await self.range(base, head) + scope = await self._once( + ("scope", head), lambda: code.ingest_scope(self.org, self.cns, head) + ) + if changed is None or scope is None: + return None + # by prefix first: the denylist is matched only on a range within the bound + paths = {old: now for old, now in changed.paths.items() if scope.under(now or old)} + if len(paths) > limit: + self.wide_ranges += 1 + # a warning: `code.refresh` rechecks too and keeps no count + log.warning( + "memory links: no renamed definition searched for across files: %d " + "files changed in %s..%s of %s", + len(paths), + base[:12], + head[:12], + self.cns, + ) + return None + found = Turnover([], [], []) + for old, now in sorted(paths.items()): + if not scope.takes(now or old): + continue + try: + await self._file_turnover(scope, base, old, head, now, found) + except code.ParseFailed: + pass # the index holds nothing of a file that does not parse + return found + + return await self._once(("turnover", base, head), read) + + async def _file_turnover( + self, scope: code.IngestScope, base: str, old: str, head: str, now: str, found: Turnover + ) -> None: + """Add to `found` what the file `old` at `base`, `now` at `head` ('' = deleted), + gained, lost and kept, by the name inside its module. Its text at `base` is + fingerprinted only when it lost a name. A file still there that the ingest does + not index adds nothing: none of its names is known to have left it.""" + + def local(qualified_name: str, path: str) -> str: + return unnumbered(local_name(qualified_name, path)) + + names = await self._indexed_names(scope, head, now) if now else set() + if names is None: + return + before = {local(name, old) for name in await self.names(base, old) or ()} + after = {local(name, now) for name in names} + here = await self.at(head, now) if after else None + there = await self.at(base, old) if before - after else None + if here is not None: + new = [d for d in here.defs if local(d.qualified_name, now) not in before] + kept = [d for d in here.defs if local(d.qualified_name, now) in before] + found.new.append(Side(now, new, here.lines)) + found.kept.append(Side(now, kept, here.lines)) + if there is not None: + gone = [d for d in there.defs if local(d.qualified_name, old) not in after] + found.gone.append(Side(old, gone, there.lines)) + async def is_ancestor(self, ancestor: str, descendant: str) -> bool: """Whether `ancestor` is in `descendant`'s history.""" return await self._once( diff --git a/server/memory/app/code_link_recheck.py b/server/memory/app/code_link_recheck.py index cab5bcefe5..7ecc5f9430 100644 --- a/server/memory/app/code_link_recheck.py +++ b/server/memory/app/code_link_recheck.py @@ -25,7 +25,7 @@ ) from server.code.domain.declaration import fingerprint_version from server.code.domain.index.repos import repo_for_namespace -from server.code.domain.successor import Side, Successor, close_to, successor +from server.code.domain.successor import Side, Successor, close_to, elsewhere, successor from server.core.datetimes import naive_utc_now from server.memory.app import code_link_pass as link_pass from server.memory.app import code_link_policy as policy @@ -145,6 +145,7 @@ async def _recheck_repository( checked = cut_at await _follow(org, cns, checked, head, files, result) await code.set_checked_head(org, cns, head) + result.wide_ranges += files.wide_ranges await policy.apply_policies(org, cns, head, files, budget, result) @@ -161,7 +162,9 @@ def _progress(org: str, cns: str) -> link_pass.Cursor[dict[str, str]]: _LOST_SEARCHED_DAYS = 30 -# files of namesakes a lost link is weighed against: past it, the answer is unsure +# files of namesakes a lost link is weighed against: past it, the answer is unsure; and +# files a range may change for a renamed definition to be looked for in them: past it, a +# live link is read as if nothing was renamed and an unresolved one stays unresolved _MAX_ELSEWHERE = 32 @@ -368,19 +371,22 @@ async def _recheck( if new is None and r.before.state != "missing": renamed = Successor(None, uncertain=True) # cannot tell: a live link is unsure far = new or [] - # moved to another module with an edit: never for a link already missing, nor - # one the same-file search left unsure, unless the new definitions there were - # each compared with it and none is close + # found under no name it had: looked for where it may have moved, never for a + # link already missing, nor one the same-file search left unsure, unless the new + # definitions there were each compared with it and none is close unsure = renamed.uncertain - moved_and_edited = ( - bool(far) + sought = ( + r.lost and renamed.definition is None and (not unsure or renamed.unmatched) and r.before.state != "missing" and locate(r.before, r.now, r.defs, elsewhere=far) is None ) - if moved_and_edited: + if sought and far: # to another module with an edit renamed = await _moved_and_edited(files, r.before, r.row, far, head) + # or under another name, where the same-file search found no new definition + if sought and not unsure and not mirror_unsure and renamed == Successor(None): + renamed = await _renamed_elsewhere(files, r, head) after = recheck( r.before, path_now=r.now, @@ -549,6 +555,40 @@ async def _moved_and_edited( return files.successors[key] +async def _renamed_elsewhere(files: link_pass.RepoReads, r: _Read, head: str) -> Successor: + """What the lost link's definition became in another file or scope + (`successor.elsewhere`), among the definitions new since `_searched_from` in the + files changed since. Nothing, as before this search, when the range brought no + definition in, changed more than `_MAX_ELSEWHERE` files or cannot be read, or the + link's last-read text cannot. A link already unresolved is unsure over a range not + searched: its range starts at its own commit and only grows, and the candidates + that left it unresolved may still be there.""" + checked, path = r.row["checked_commit"], r.before.read_path + base = _searched_from(r.before, r.row, r.range) + key = ("renamed", checked, path, r.before.qualified_name, base, head) + if (known := files.successors.get(key)) is not None: + return known + turnover = await files.turnover(base, head, limit=_MAX_ELSEWHERE) + if turnover is None: + return Successor(None, uncertain=r.before.state == "unresolved") + if not any(side.defs for side in turnover.new): + return Successor(None) + try: + old = await files.at(checked, path) if checked and await files.has(checked) else None + except code.ParseFailed: + old = None + was = [d for d in old.defs if d.qualified_name == r.before.qualified_name] if old else [] + if old is None or not was: + return Successor(None) + # comparing texts is CPU work: off the loop, once per definition and pass + then = Side(path, old.defs, old.lines) + found = await asyncio.to_thread( + elsewhere, was[0], then, turnover.new, turnover.gone, turnover.kept + ) + files.successors[key] = found + return found + + async def _renamed( files: link_pass.RepoReads, before: Link, a: LinkRow, now: str, head: str ) -> Successor: diff --git a/tests/integration/test_memory_code_links.py b/tests/integration/test_memory_code_links.py index 995f65d59b..f2a767d8f7 100644 --- a/tests/integration/test_memory_code_links.py +++ b/tests/integration/test_memory_code_links.py @@ -799,6 +799,47 @@ async def test_a_function_moved_with_an_edit_is_followed_past_a_new_export_list( assert [(x["path"], x["state"]) for x in await _links(gone)] == [("src/mv/c.py", "unresolved")] +_LONG_ROWS = ( + "def fetch_rows(conn, n, start=0):\n rows = []\n for i in range(start, n):\n" + " row = conn.read(i)\n if row:\n rows.append(row)\n" + " return rows\n" +) + + +async def test_a_definition_renamed_as_it_moves_to_another_file_is_followed(env) -> None: + repo = env + keep = "def keep():\n return 0\n" + c1 = repo.commit({"src/widgets/io.py": keep + "\n\n" + _LONG_ROWS}) + await _index(TRUNK, repo, c1, ["src/widgets/io.py"]) + mid = await _remember(MEM, "fetch-rows", "`fetch_rows` drops empty rows") + await _pass() + # one commit takes it out of io.py and brings it into a new file under another name + moved = { + "src/widgets/io.py": keep, + "src/widgets/rows.py": _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + c2 = repo.commit(moved) + await _index(TRUNK, repo, c2, list(moved)) + result = await _pass() + assert result.wide_ranges == 0 + (link,) = await _links(mid) + assert (link["path"], link["symbol"], link["state"]) == ( + "src/widgets/rows.py", + "src.widgets.rows::warm_up", + "moved", + ) + # served, on the definition it is now, with its text as written + assert (await _search(MEM, "fetch_rows drops empty rows")).get("fetch-rows") == "moved" + lessons = await _lessons(TRUNK, "warm_up") + assert [(x["memory_key"], x["code_state"]) for x in lessons] == [("fetch-rows", "moved")] + assert (await _row(mid)).value == "`fetch_rows` drops empty rows" + # a later commit that removes it brings nothing in: the code is gone + c3 = repo.commit({"src/widgets/rows.py": None}) + await _index(TRUNK, repo, c3, ["src/widgets/rows.py"]) + await _pass() + assert [x["state"] for x in await _links(mid)] == ["missing"] + + async def test_a_file_link_follows_its_cited_lines_and_the_definition_its_memory_names( env, ) -> None: @@ -3595,6 +3636,33 @@ async def test_a_removed_method_never_moves_to_a_namesake_in_another_class(env) assert await _lessons(TRUNK, "Writer.read_rows") == [] +async def test_a_method_moved_to_another_class_with_its_text_reads_changed(env) -> None: + # thirty tokens or more: its text tells it from any other method of that name, and + # what surrounds it is no longer what the memory saw + method = ( + " def read_rows(self, conn, start=0):\n rows = []\n" + " for i in range(start, self.limit):\n row = conn.read(i)\n" + " if row:\n rows.append(row)\n return rows\n" + ) + other = " def other(self):\n return 1\n" + c1 = env.commit({"src/rw.py": "class Reader:\n limit = 3\n\n" + method + "\n" + other}) + await _index(TRUNK, env, c1, ["src/rw.py"]) + mid = await _remember(MEM, "rw", "`Reader.read_rows` reads three rows", files=["src/rw.py"]) + await _pass() + moved = ( + "class Reader:\n limit = 3\n\n" + other + "\n\nclass Writer:\n limit = 4\n\n" + method + ) + c2 = await _relink_once(env, "src/rw.py", moved) + (link,) = await _links(mid) + assert (link["symbol"], link["state"], link["changed_since"]) == ( + "src.rw::Writer::read_rows", + "changed", + c2, + ) + lessons = await _lessons(TRUNK, "Writer.read_rows") + assert [(x["memory_key"], x["code_state"]) for x in lessons] == [("rw", "changed")] + + @pytest.mark.parametrize("path", ["io.cpp", "io/reader.cpp"]) async def test_a_namespace_named_like_its_file_is_part_of_the_name(env, path) -> None: before = ( diff --git a/tests/unit/test_code_anchor.py b/tests/unit/test_code_anchor.py index e973c50b19..cb00e25e70 100644 --- a/tests/unit/test_code_anchor.py +++ b/tests/unit/test_code_anchor.py @@ -177,6 +177,32 @@ def test_recheck_follows_a_rename_the_caller_found_by_shape() -> None: ) +def test_recheck_follows_a_rename_the_caller_found_in_another_file() -> None: + link = Link( + path="src/a.py", qualified_name="src.a.fetch_rows", body_hash="h1", checked_hash="h1" + ) + there = _d("src/b.py", "src.b.load_rows", "h2", line=7) + kept = [_d("src/a.py", "src.a.other", "h9")] + # its own file kept, or deleted with it + for path_now, here in (("src/a.py", kept), ("", [])): + after = recheck(link, path_now=path_now, here=here, renamed=there, head="c2") + assert (after.path, after.qualified_name, after.state) == ( + "src/b.py", + "src.b.load_rows", + "moved", + ) + assert (after.body_hash, after.start_line, after.checked_path) == ("h2", 7, "") + # it left its class on the way: changed whatever its text, its baseline kept + carried = recheck(link, path_now="src/a.py", here=kept, renamed=there, carried=True, head="c2") + assert (carried.path, carried.state, carried.body_hash, carried.changed_since) == ( + "src/b.py", + "changed", + "h1", + "c2", + ) + assert carried.carried + + def test_a_fingerprint_covers_every_overload_in_order_and_every_character() -> None: assert fingerprint(["a", "b"]) != fingerprint(["a", "c"]) != fingerprint(["b", "a"]) inside = "def f(x):\n if x:\n return 1\n return 2" diff --git a/tests/unit/test_code_successor.py b/tests/unit/test_code_successor.py index 145f6e6797..f506629ad0 100644 --- a/tests/unit/test_code_successor.py +++ b/tests/unit/test_code_successor.py @@ -7,8 +7,8 @@ import pytest from server.code.app.memory_links import file_definitions -from server.code.domain.anchor import Link, locate, recheck -from server.code.domain.successor import _MAX_LINES, Side, successor +from server.code.domain.anchor import Link, local_name, locate, recheck, unnumbered +from server.code.domain.successor import _MAX_LINES, Side, elsewhere, successor from tests.unit.step_count import steps as count @@ -97,6 +97,10 @@ def test_a_method_of_a_removed_class_never_moves_to_a_namesake_in_another() -> N ) after = "class Writer:\n def flush(self):\n pass\n\n def fetch_rows(self):\n return 1\n" assert _after(("reader.py", before), ("reader.py", after)).state == "missing" + # nor by the search across scopes: a method this small is any class's + assert _elsewhere({"reader.py": before}, {"reader.py": after}, "Reader.fetch_rows").state == ( + "missing" + ) _KEPT = "def other():\n return 0\n" @@ -634,3 +638,300 @@ def program(cls: str, comment: str = "") -> str: before, after = program("Reader"), program("Loader", " # closes it\n") got = _after(("reader.py", before), ("reader.py", after), name) assert (got.state, got.qualified_name) == ("moved", f"reader::Loader::{name}") + + +# ---- renamed as it moved to another file or scope ----------------------------------- + + +def _turnover( + before: dict[str, str], after: dict[str, str] +) -> tuple[list[Side], list[Side], list[Side]]: + """What the files gained, lost and kept by the name inside their module, as the + recheck reads a range: each file's new definitions, its removed ones, and those it + still has under a name it had.""" + + def local(side: Side) -> dict[str, list]: + names: dict[str, list] = {} + for d in side.defs: + names.setdefault(unnumbered(local_name(d.qualified_name, side.path)), []).append(d) + return names + + new, gone, kept = [], [], [] + for path in sorted(before.keys() | after.keys()): + old = _side(path, before.get(path, "")) + now = _side(path, after.get(path, "")) + was, here = local(old), local(now) + new.append(Side(path, [d for n in here.keys() - was.keys() for d in here[n]], now.lines)) + kept.append(Side(path, [d for n in here.keys() & was.keys() for d in here[n]], now.lines)) + gone.append(Side(path, [d for n in was.keys() - here.keys() for d in was[n]], old.lines)) + return new, gone, kept + + +def _elsewhere(before: dict[str, str], after: dict[str, str], name: str = "fetch_rows") -> Link: + """The link on `name` in a.py (or the only file of `before`) once the files are as + `after`, where its own file no longer defines it.""" + path = "a.py" if "a.py" in before else next(iter(before)) + old = _side(path, before[path]) + was = next(d for d in old.defs if local_name(d.qualified_name, path) == name or d.name == name) + link = Link(path, was.qualified_name, was.body_hash, checked_hash=was.body_hash) + here = _side(path, after[path]).defs if path in after else [] + s = elsewhere(was, old, *_turnover(before, after)) + return recheck( + link, + path_now=path if path in after else "", + here=here, + renamed=s.definition, + renamed_exactly=s.exact, + uncertain=s.uncertain, + carried=s.carried, + head="c2", + ) + + +_KEEP = "def keep():\n return 0\n" +_SMALL_ROWS = "def fetch_rows(n):\n return list(range(n))\n" +_ROWS = ( + "def fetch_rows(n, start=0):\n out = []\n for i in range(start, n):\n" + " if i % 2:\n out.append(i)\n else:\n out.append(-i)\n" + " return sorted(out)\n" +) +_METHOD = ( + " def fetch_rows(self, n, start=0):\n for i in range(start, n):\n" + " if i % 2:\n self.rows.append(i)\n else:\n" + " self.rows.append(-i)\n return sorted(self.rows)\n" +) +_READER_CLOSES = ( + "class Reader:\n def __init__(self):\n self.rows = []\n\n" + " def close(self):\n pass\n" +) +_READER = _READER_CLOSES + "\n" + _METHOD +_OTHER_ROWS = "class Other:\n" + _METHOD + + +@pytest.mark.parametrize("gone", [_KEEP, None], ids=["file-kept", "file-deleted"]) +def test_a_function_renamed_as_it_moved_to_another_file_is_moved(gone: str | None) -> None: + after = {"b.py": _ROWS.replace("fetch_rows", "warm_up")} | ({"a.py": gone} if gone else {}) + got = _elsewhere({"a.py": _KEEP + "\n\n" + _ROWS}, after) + assert (got.state, got.path, got.qualified_name) == ("moved", "b.py", "b::warm_up") + assert got.body_hash == got.checked_hash # only its name changed: the new baseline + + +@pytest.mark.parametrize( + ("name", "state"), + [ + ("_fetch_rows", "moved"), + ("fetch_rows_v2", "moved"), + ("load_rows", "missing"), + ("warm_up", "missing"), + ], +) +def test_a_small_function_renamed_as_it_moved_keeps_the_words_of_its_name( + name: str, state: str +) -> None: + # under thirty tokens two definitions look alike by their shape alone, and among every + # changed file one shared word is no kinship + after = {"a.py": _KEEP, "b.py": _SMALL_ROWS.replace("fetch_rows", name)} + assert _elsewhere({"a.py": _KEEP + "\n\n" + _SMALL_ROWS}, after).state == state + + +def test_a_removed_stub_is_not_handed_to_a_new_stub_sharing_a_word_of_its_name() -> None: + # two exception stubs have one shape whatever they are for + stub = "class ReadError(Exception):\n pass\n" + before = {"errors.py": _KEEP + "\n\n" + stub} + after = {"errors.py": _KEEP, "retry.py": stub.replace("ReadError", "RetryError")} + got = _elsewhere(before, after, "ReadError") + assert (got.state, got.path) == ("missing", "errors.py") + # the same stub made private as it moved is still the one the memory names + after = {"errors.py": _KEEP, "retry.py": stub.replace("ReadError", "_ReadError")} + got = _elsewhere(before, after, "ReadError") + assert (got.state, got.qualified_name) == ("moved", "retry::_ReadError") + + +@pytest.mark.parametrize("name", ["Reader", "Reader.fetch_rows", "Reader.close"]) +def test_a_class_renamed_as_it_moved_takes_its_members(name: str) -> None: + after = {"a.py": _KEEP, "b.py": _READER.replace("Reader", "Loader")} + got = _elsewhere({"a.py": _KEEP + "\n\n" + _READER}, after, name) + assert (got.state, got.qualified_name) == ( + "moved", + "b::" + name.replace("Reader", "Loader").replace(".", "::"), + ) + + +def test_a_method_that_left_its_class_for_another_file_reads_changed() -> None: + # the same text in another class: what surrounds it is not what the memory saw + got = _elsewhere( + {"a.py": _READER}, {"a.py": _READER_CLOSES, "b.py": _OTHER_ROWS}, "Reader.fetch_rows" + ) + assert (got.state, got.qualified_name) == ("changed", "b::Other::fetch_rows") + assert got.carried + + +def test_a_method_that_became_a_function_reads_changed() -> None: + function = "\n".join(line[4:] for line in _METHOD.splitlines()) + "\n" + got = _elsewhere( + {"a.py": _READER}, {"a.py": _READER_CLOSES + "\n\n" + function}, "Reader.fetch_rows" + ) + assert (got.state, got.qualified_name) == ("changed", "a::fetch_rows") + + +@pytest.mark.parametrize( + ("theirs", "state"), + [ + (_OTHER_ROWS.replace("append(-i)", "append(-i * 2)"), "changed"), # close + ("class Other:\n def fetch_rows(self):\n return {'unrelated': 1}\n", "missing"), + ], + ids=["close", "not-close"], +) +def test_its_own_name_in_another_class_elsewhere_is_it_only_with_a_close_text( + theirs: str, state: str +) -> None: + got = _elsewhere( + {"a.py": _READER}, {"a.py": _READER_CLOSES, "b.py": theirs}, "Reader.fetch_rows" + ) + assert got.state == state + assert (got.path == "b.py") == (state == "changed") + + +_DICT = ( + "class {0}:\n def __init__(self):\n self.data = {{}}\n\n" + " def __iter__(self):\n return {1}\n\n" + " def __len__(self):\n return len(self.data)\n" +) + + +_FOLDED = _DICT.format("Folded", "iter(self.data.keys())") + + +@pytest.mark.parametrize( + ("kept", "theirs", "state"), + [ + # the class came with it, edited: two of its three members, and this one + (_KEEP, _FOLDED, "changed"), + # another class's: one member name in common says nothing + ( + _KEEP, + "class Folded:\n def __iter__(self):\n return iter(self.data)\n", + "missing", + ), + # its own class is still there, less this method: the new class is another one + ( + _DICT.format("Multi", "0").replace(" def __iter__(self):\n return 0\n\n", ""), + _FOLDED, + "missing", + ), + ], + ids=["its-class-came-along", "unrelated-class", "its-class-stayed"], +) +def test_a_small_method_goes_to_its_name_in_another_class_only_with_its_class( + kept: str, theirs: str, state: str +) -> None: + # `__iter__` is any class's, and a text this short is mostly its signature + before = {"a.py": _KEEP + "\n\n" + _DICT.format("Multi", "iter(self.data)")} + got = _elsewhere(before, {"a.py": kept, "b.py": theirs}, "Multi.__iter__") + assert got.state == state + + +_CLEAR = " def clear(self):\n self.data.clear()\n" +_OWN = ( + " def get(self, key):\n return self.data[key]\n\n" + " def put(self, key, value):\n self.data[key] = value\n\n" + " def pop(self, key):\n return self.data.pop(key)\n\n" + " def keys(self):\n return list(self.data)\n\n" +) + _CLEAR + + +@pytest.mark.parametrize( + ("own", "state"), + [ + # five members of its own beside the four it took in: mostly another class + (_OWN, "missing"), + # one of its own: it keeps the removed class's + (_CLEAR, "changed"), + ], + ids=["mostly-its-own", "mostly-the-removed-class"], +) +def test_a_class_that_was_already_there_is_weighed_with_the_members_it_had( + own: str, state: str +) -> None: + # Store was in b.py and takes Multi's members in as Multi goes + multi = _KEEP + "\n\n" + _DICT.format("Multi", "iter(self.data)") + after = {"a.py": _KEEP, "b.py": _DICT.format("Store", "iter(self.data)") + "\n" + own} + before = {"a.py": multi, "b.py": "class Store:\n" + own} + assert _elsewhere(before, after, "Multi.__iter__").state == state + # as the same class is when the range brings it in whole + assert _elsewhere({"a.py": multi}, after, "Multi.__iter__").state == state + + +def test_a_small_method_follows_its_class_renamed_with_an_alias_left_behind() -> None: + # the old name stays as an alias of the class: no member is left under it + before = {"a.py": _DICT.format("Multi", "iter(self.data)")} + after = {"a.py": _DICT.format("Folded", "iter(self.data)") + "\n\nMulti = Folded\n"} + got = _elsewhere(before, after, "Multi.__iter__") + assert (got.state, got.qualified_name) == ("moved", "a::Folded::__iter__") + + +def test_a_small_method_never_becomes_a_function_of_its_name() -> None: + before = {"a.py": _DICT.format("Multi", "iter(self.data)")} + after = {"a.py": _KEEP, "b.py": "def __iter__(self):\n return iter(self.data)\n"} + assert _elsewhere(before, after, "Multi.__iter__").state == "missing" + + +def test_a_close_namesake_that_stayed_leaves_an_edited_move_unresolved() -> None: + # sibling classes share the method. Client keeps its name and takes the text of the + # removed Sync, while Client's old text arrives as Async: the new one is not the + # only close one, and the one that stayed never inherits a link + sync, other = _METHOD, _METHOD.replace("sorted(self.rows)", "list(self.rows)") + before = {"a.py": "class Sync:\n" + sync, "b.py": "class Client:\n" + other} + after = {"b.py": "class Client:\n" + sync + "\n\nclass Async:\n" + other} + got = _elsewhere(before, after, "Sync.fetch_rows") + assert (got.state, got.path) == ("unresolved", "a.py") + # with no namesake kept beside it, the new one is followed + alone = {"b.py": "class Async:\n" + other} + got = _elsewhere({"a.py": "class Sync:\n" + sync}, alone, "Sync.fetch_rows") + assert (got.state, got.qualified_name) == ("changed", "b::Async::fetch_rows") + + +def test_a_namesake_that_stayed_never_makes_removed_code_unresolved() -> None: + # nothing new is close to it: the code is gone, however alike its sibling is + before = {"a.py": "class Sync:\n" + _METHOD, "b.py": "class Client:\n" + _METHOD} + after = {"a.py": _KEEP, "b.py": "class Client:\n" + _METHOD + "\n\nX = 1\n"} + assert _elsewhere(before, after, "Sync.fetch_rows").state == "missing" + + +def test_two_new_definitions_of_its_shape_leave_it_unresolved() -> None: + after = { + "a.py": _KEEP, + "b.py": _ROWS.replace("fetch_rows", "load_rows"), + "c.py": _ROWS.replace("fetch_rows", "read_rows"), + } + got = _elsewhere({"a.py": _KEEP + "\n\n" + _ROWS}, after) + assert (got.state, got.path) == ("unresolved", "a.py") + + +def test_two_close_definitions_of_its_name_leave_it_unresolved() -> None: + edited = _OTHER_ROWS.replace("append(-i)", "append(-i * 2)") + after = {"a.py": _READER_CLOSES, "b.py": edited, "c.py": edited.replace("Other", "Third")} + assert _elsewhere({"a.py": _READER}, after, "Reader.fetch_rows").state == "unresolved" + + +def test_a_new_definition_another_removed_one_may_have_become_is_not_followed() -> None: + # c.py lost a definition of the same shape: b.py's may be either's + before = {"a.py": _KEEP + "\n\n" + _ROWS, "c.py": _ROWS.replace("fetch_rows", "scan_rows")} + after = {"a.py": _KEEP, "c.py": _KEEP, "b.py": _ROWS.replace("fetch_rows", "load_rows")} + assert _elsewhere(before, after).state == "unresolved" + + +def test_removed_twins_each_follow_the_new_definition_of_their_own_name() -> None: + # two classes with the same methods move at once: each method goes with its name + twins = _READER + "\n\n" + _READER.replace("Reader", "Writer").replace("fetch_rows", "put_rows") + moved = twins.replace("Reader", "Loader").replace("Writer", "Saver") + before, after = {"a.py": _KEEP + "\n\n" + twins}, {"a.py": _KEEP, "b.py": moved} + got = _elsewhere(before, after, "Writer.put_rows") + assert (got.state, got.qualified_name) == ("moved", "b::Saver::put_rows") + # the same `close` in both: which class's it is cannot be told by the method alone + assert _elsewhere(before, after, "Writer.close").state == "unresolved" + + +def test_a_removed_definition_with_nothing_new_like_it_is_missing() -> None: + after = {"a.py": _KEEP, "b.py": "def unrelated(n):\n return {'n': n}\n"} + assert _elsewhere({"a.py": _KEEP + "\n\n" + _ROWS}, after).state == "missing" diff --git a/tests/unit/test_memory_code_links.py b/tests/unit/test_memory_code_links.py index 78d824d354..a9c97a48eb 100644 --- a/tests/unit/test_memory_code_links.py +++ b/tests/unit/test_memory_code_links.py @@ -7,6 +7,7 @@ import contextlib import errno import json +import logging import re import subprocess from collections.abc import Callable @@ -32,8 +33,10 @@ # the policy's own texts and judge, which the `world` fixture stubs _TEXTS, _JUDGE = code_link_policy._texts, code_link_policy._judge -# the mirror search, which an autouse fixture stubs +# the mirror search and the read of a range's new and removed definitions, which autouse +# fixtures stub _REAL_CONTAINING = code_link_pass.RepoReads.containing +_REAL_TURNOVER = code_link_pass.RepoReads.turnover @pytest.fixture(autouse=True) @@ -71,6 +74,16 @@ async def containing(self, base, head, literal, *, limit): monkeypatch.setattr(code_link_pass.RepoReads, "containing", containing) +@pytest.fixture(autouse=True) +def _ranges_rename_nothing_across_files(monkeypatch): + # likewise: a lost name is looked for under another name only where a test says so. + # Searched, with nothing brought in: a range not searched keeps an unresolved link + async def turnover(self, base, head, *, limit): + return code_link_pass.Turnover([], [], []) + + monkeypatch.setattr(code_link_pass.RepoReads, "turnover", turnover) + + def _full(link: dict[str, Any]) -> dict[str, Any]: """A link row with every column: `link` over the table's defaults.""" return code_links.store.LINK_COLS | {"fingerprint_version": fingerprint_version()} | link @@ -5336,6 +5349,391 @@ async def no_fingerprints(commit, path, qualified_name): assert [m.link.state for m in moves] == ["unresolved"] +# ---- a definition renamed as it moved to another file or scope ----------------------- + +_LONG_ROWS = ( + "def fetch_rows(n, start=0):\n out = []\n for i in range(start, n):\n" + " if i % 2:\n out.append(i)\n else:\n out.append(-i)\n" + " return sorted(out)\n" +) +_KEEP = "def keep():\n return 0\n" + + +def _renaming_world( + monkeypatch, commits: dict[tuple[str, str], str], *, renames: dict[str, str] | None = None +) -> tuple[Any, dict[str, Any]]: + """A repository whose history is `commits` ((commit, path) -> text, the commits in + name order, `renames` old path -> new) read through the real `RepoReads.turnover`, + with nothing in the index; and the fresh link on pkg/a.py's `fetch_rows` read at c0.""" + monkeypatch.setattr(code_link_pass.RepoReads, "turnover", _REAL_TURNOVER) + files = code_link_pass.RepoReads("o", "code-a") + renames = renames or {} + + async def at(commit, path): + src = commits.get((commit, path)) + return _file(path, src) if src is not None else None + + async def range_of(base, head): + paths = {p for c, p in commits if c in (base, head)} - set(renames.values()) + changed = {p for p in paths if commits.get((base, p)) != commits.get((head, p))} + kept = {p: renames.get(p, p if (head, p) in commits else "") for p in changed} + return code_link_pass.Range(base, kept) + + async def is_ancestor(ancestor, descendant): + return ancestor <= descendant + + async def nothing(org, cns, **kw): + return [] + + async def ingest_scope(org, cns, commit): + return SimpleNamespace(under=lambda path: True, takes=lambda path: True) + + async def indexed_names(scope, commit, path): + return await files.names(commit, path) + + _reads(monkeypatch, files, at) + monkeypatch.setattr(files, "range", range_of) + monkeypatch.setattr(files, "is_ancestor", is_ancestor) + monkeypatch.setattr(code_links.code, "candidates", nothing) + monkeypatch.setattr(code_links.code, "ingest_scope", ingest_scope) + monkeypatch.setattr(code_links.code, "indexed_names", indexed_names) + (d,) = [ + x for x in _file("pkg/a.py", commits[("c0", "pkg/a.py")]).defs if x.name == "fetch_rows" + ] + row = _full( + { + "org": "o", + "code_namespace": "code-a", + "path": "pkg/a.py", + "qualified_name": d.qualified_name, + "anchored_path": "pkg/a.py", + "anchored_name": d.qualified_name, + "anchored_commit": "c0", + "body_hash": d.body_hash, + "checked_hash": d.body_hash, + "state": "fresh", + "changed_since": "", + "checked_commit": "c0", + "memory_id": "m1", + "version": 1, + } + ) + return files, row + + +async def _followed(files: Any, row: dict[str, Any], base: str = "c0", head: str = "c1") -> list: + changed = await files.range(base, head) + moves = await code_link_recheck._recheck("o", "code-a", [row], changed, head, files) + return [(m.link.state, m.link.path, m.link.qualified_name) for m in moves] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("kept", [True, False], ids=["file-kept", "file-deleted"]) +async def test_a_definition_renamed_as_it_moved_to_another_file_is_followed( + monkeypatch, kept: bool +) -> None: + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } | ({("c1", "pkg/a.py"): _KEEP} if kept else {}) + files, row = _renaming_world(monkeypatch, commits) + assert await _followed(files, row) == [("moved", "pkg/b.py", "pkg.b::warm_up")] + assert files.wide_ranges == 0 + + +@pytest.mark.asyncio +async def test_a_definition_renamed_as_it_moved_into_a_renamed_file_is_followed( + monkeypatch, +) -> None: + # c.py became b.py and took the definition under a new name: nothing b.py had as + # c.py is new, the definition is + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c0", "pkg/c.py"): "def other():\n return 1\n", + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): "def other():\n return 1\n\n\n" + + _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, row = _renaming_world(monkeypatch, commits, renames={"pkg/c.py": "pkg/b.py"}) + assert await _followed(files, row) == [("moved", "pkg/b.py", "pkg.b::warm_up")] + + +@pytest.mark.asyncio +async def test_a_name_the_other_file_already_defined_is_not_the_renamed_one(monkeypatch) -> None: + # warm_up was in b.py before fetch_rows went: another definition, however alike + theirs = _LONG_ROWS.replace("fetch_rows", "warm_up") + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c0", "pkg/b.py"): theirs, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): theirs + "\n\nX = 1\n", + } + files, row = _renaming_world(monkeypatch, commits) + assert await _followed(files, row) == [("missing", "pkg/a.py", "pkg.a::fetch_rows")] + + +@pytest.mark.asyncio +async def test_a_missing_link_is_not_handed_to_a_definition_renamed_elsewhere(monkeypatch) -> None: + # deleted at c1 and read missing then; a definition of its shape added at c2 is new code + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c2", "pkg/a.py"): _KEEP + "\n\nX = 1\n", + ("c2", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, row = _renaming_world(monkeypatch, commits) + lost = row | {"state": "missing", "changed_since": "c1"} + assert await _followed(files, lost, "c1", "c2") == [] + + +@pytest.mark.asyncio +async def test_a_range_past_the_file_cap_is_not_searched_and_is_counted( + monkeypatch, caplog +) -> None: + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, row = _renaming_world(monkeypatch, commits) + monkeypatch.setattr(code_link_recheck, "_MAX_ELSEWHERE", 1) # a.py and b.py changed + with caplog.at_level(logging.WARNING, logger=code_link_pass.log.name): + assert await _followed(files, row) == [("missing", "pkg/a.py", "pkg.a::fetch_rows")] + # once a range, however many links are lost over it + assert await files.turnover("c0", "c1", limit=1) is None + assert files.wide_ranges == 1 + # a warning, the only trace when `code.refresh` rechecks: it keeps no pass outcome + assert [(r.levelname, r.getMessage()) for r in caplog.records] == [ + ( + "WARNING", + "memory links: no renamed definition searched for across files: 2 files " + "changed in c0..c1 of code-a", + ) + ] + + +@pytest.mark.asyncio +async def test_the_file_cap_counts_only_paths_under_the_prefixes(monkeypatch) -> None: + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + ("c1", "docs/x.py"): "X = 1\n", + ("c1", "tools/y.py"): "Y = 1\n", + } + files, row = _renaming_world(monkeypatch, commits) + + async def ingest_scope(org, cns, commit): + return SimpleNamespace(under=lambda p: p.startswith("pkg/"), takes=lambda p: True) + + monkeypatch.setattr(code_links.code, "ingest_scope", ingest_scope) + monkeypatch.setattr(code_link_recheck, "_MAX_ELSEWHERE", 2) # four changed, two under it + assert await _followed(files, row) == [("moved", "pkg/b.py", "pkg.b::warm_up")] + assert files.wide_ranges == 0 + + +@pytest.mark.asyncio +async def test_a_range_git_cannot_read_is_not_searched(monkeypatch) -> None: + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, _ = _renaming_world(monkeypatch, commits) + + async def unread(base, head): + return None # a force-push + + monkeypatch.setattr(files, "range", unread) + assert await files.turnover("c0", "c1", limit=32) is None + assert files.wide_ranges == 0 + + +def _two_that_may_be_it(c2: dict[str, str]) -> dict[tuple[str, str], str]: + """A history where c1 moves `fetch_rows` out of pkg/a.py and b.py and c.py each gain + its text under another name; `c2` is what c2 holds beside pkg/a.py.""" + two = { + "pkg/b.py": _LONG_ROWS.replace("fetch_rows", "warm_up"), + "pkg/c.py": _LONG_ROWS.replace("fetch_rows", "cool_down"), + } + commits = {("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS} + commits |= {("c1", path): src for path, src in ({"pkg/a.py": _KEEP} | two).items()} + return commits | {("c2", path): src for path, src in ({"pkg/a.py": _KEEP} | c2).items()} + + +@pytest.mark.asyncio +@pytest.mark.parametrize("unread", [False, True], ids=["too-wide", "unreadable"]) +async def test_an_unresolved_link_stays_unresolved_over_a_range_not_searched( + monkeypatch, unread: bool +) -> None: + # an unresolved link is looked for from its own commit, c0, so its range only grows: + # c2 changes 33 other files, or c0..c2 cannot be read, and both candidates are there + two = {p: src for (c, p), src in _two_that_may_be_it({}).items() if c == "c1"} + others = {} if unread else {f"pkg/n{i}.py": f"N{i} = 1\n" for i in range(33)} + files, row = _renaming_world(monkeypatch, _two_that_may_be_it(two | others)) + assert await _followed(files, row) == [("unresolved", "pkg/a.py", "pkg.a::fetch_rows")] + range_of = files.range + + async def since_c1(base, head): + return None if unread and base == "c0" else await range_of(base, head) + + monkeypatch.setattr(files, "range", since_c1) + lost = row | {"state": "unresolved", "changed_since": "c1"} + assert await _followed(files, lost, "c1", "c2") == [] + assert files.wide_ranges == (0 if unread else 1) + + +@pytest.mark.asyncio +async def test_an_unresolved_link_is_followed_once_one_candidate_is_left(monkeypatch) -> None: + # c2 removes c.py: of the two that might be it at c1, b.py's is the only one left + commits = _two_that_may_be_it({"pkg/b.py": _LONG_ROWS.replace("fetch_rows", "warm_up")}) + files, row = _renaming_world(monkeypatch, commits) + assert await _followed(files, row) == [("unresolved", "pkg/a.py", "pkg.a::fetch_rows")] + lost = row | {"state": "unresolved", "changed_since": "c1"} + assert await _followed(files, lost, "c1", "c2") == [("moved", "pkg/b.py", "pkg.b::warm_up")] + + +@pytest.mark.asyncio +async def test_a_changed_file_that_does_not_parse_adds_no_definition(monkeypatch) -> None: + # z.py does not parse: the index holds nothing of it, and b.py's definition is + # followed as if z.py were not there + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + ("c1", "pkg/z.py"): "def broken(:\n", + } + files, row = _renaming_world(monkeypatch, commits) + names = files.names + + async def unparsed(commit, path): + if path == "pkg/z.py": + raise code_links.code.ParseFailed(path, "syntax") + return await names(commit, path) + + monkeypatch.setattr(files, "names", unparsed) + assert await _followed(files, row) == [("moved", "pkg/b.py", "pkg.b::warm_up")] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("at_head", ["not-indexed", "unparsed", "deleted"]) +async def test_a_file_loses_its_definitions_only_when_it_is_deleted( + monkeypatch, at_head: str +) -> None: + # z.py had a definition of the removed one's shape. Deleted with z.py, it may be what + # b.py's is; in a z.py still there that the ingest does not index, it is not known + # to have left, and b.py's is followed + twin = _LONG_ROWS.replace("fetch_rows", "drain_rows") + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c0", "pkg/z.py"): twin, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } | ({} if at_head == "deleted" else {("c1", "pkg/z.py"): twin + "\n\nX = 1\n"}) + files, row = _renaming_world(monkeypatch, commits) + indexed = code_links.code.indexed_names + + async def indexed_names(scope, commit, path): + if (commit, path) == ("c1", "pkg/z.py"): + if at_head == "unparsed": + raise code_links.code.ParseFailed(path, "syntax") + return None # over the byte cap, or binary + return await indexed(scope, commit, path) + + monkeypatch.setattr(code_links.code, "indexed_names", indexed_names) + followed = ("moved", "pkg/b.py", "pkg.b::warm_up") + unsure = ("unresolved", "pkg/a.py", "pkg.a::fetch_rows") + assert await _followed(files, row) == [unsure if at_head == "deleted" else followed] + + +@pytest.mark.asyncio +async def test_a_file_the_ingest_refuses_adds_no_renamed_definition(monkeypatch) -> None: + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "gen/b.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, row = _renaming_world(monkeypatch, commits) + + async def ingest_scope(org, cns, commit): + refused = lambda path: not path.startswith("gen/") # noqa: E731 + return SimpleNamespace(under=lambda path: True, takes=refused) + + monkeypatch.setattr(code_links.code, "ingest_scope", ingest_scope) + assert await _followed(files, row) == [("missing", "pkg/a.py", "pkg.a::fetch_rows")] + + +@pytest.mark.asyncio +async def test_a_namesake_elsewhere_is_weighed_before_a_definition_under_another_name( + monkeypatch, +) -> None: + # b.py takes it under its own name with an edit, c.py gains an exact copy under + # another: the name is followed, as before the search across names + edited = _LONG_ROWS.replace("out.append(-i)", "out.append(-i * 2)") + commits = { + ("c0", "pkg/a.py"): _KEEP + "\n\n" + _LONG_ROWS, + ("c1", "pkg/a.py"): _KEEP, + ("c1", "pkg/b.py"): edited, + ("c1", "pkg/c.py"): _LONG_ROWS.replace("fetch_rows", "warm_up"), + } + files, row = _renaming_world(monkeypatch, commits) + _history(monkeypatch, files, commits) + + async def candidates(org, cns, *, names=None, qualified_names=None): + return [Definition("pkg/b.py", "pkg.b::fetch_rows", "fetch_rows")] + + monkeypatch.setattr(code_links.code, "candidates", candidates) + assert await _followed(files, row) == [("changed", "pkg/b.py", "pkg.b::fetch_rows")] + + +@pytest.mark.asyncio +async def test_a_close_namesake_the_changed_files_kept_leaves_the_link_unresolved( + monkeypatch, +) -> None: + # b.py's Client keeps its name and takes the removed text, and its old text arrives + # as Async: the new definition is not the only close one of that name + method = _LONG_ROWS.replace("def fetch_rows(n,", "def fetch_rows(self, n,").replace( + "\n", "\n " + ) + sync = "class Sync:\n " + method.rstrip() + "\n" + other = method.replace("sorted(out)", "list(out)").rstrip() + "\n" + commits = { + ("c0", "pkg/a.py"): sync, + ("c0", "pkg/b.py"): "class Client:\n " + other, + ("c1", "pkg/b.py"): sync.replace("Sync", "Client") + "\n\nclass Async:\n " + other, + } + files, row = _renaming_world(monkeypatch, commits) + assert await _followed(files, row) == [("unresolved", "pkg/a.py", row["qualified_name"])] + turnover = await files.turnover("c0", "c1", limit=32) + assert [[x.qualified_name for x in side.defs] for side in turnover.kept] == [ + ["pkg.b::Client", "pkg.b::Client::fetch_rows"] + ] + + +@pytest.mark.asyncio +async def test_the_recheck_reports_the_ranges_it_did_not_search(monkeypatch) -> None: + files = code_link_pass.RepoReads("o", "code-a") + files.wide_ranges = 2 + + async def nothing(*a, **k): + return None + + async def head(org, cns): + return "c1" + + monkeypatch.setattr(code_link_pass, "RepoReads", lambda org, cns: files) + monkeypatch.setattr(code_link_recheck.code, "indexed_head", head) + monkeypatch.setattr(code_link_recheck.code, "checked_head", head) + for name in ("_recheck_pending", "_retry_unparsed"): + monkeypatch.setattr(code_link_recheck, name, nothing) + monkeypatch.setattr(code_link_recheck.rehash, "refingerprint", nothing) + monkeypatch.setattr(code_link_recheck.policy, "apply_policies", nothing) + result = code_link_pass.PassResult() + await code_link_recheck._recheck_repository( + "o", "code-a", code_link_pass.Budget(judgements=0), result + ) + assert result.as_dict()["wide_ranges"] == 2 + + # ---- a memory whose code moved is served with where the code is now -----------------