Skip to content
Merged
9 changes: 9 additions & 0 deletions docs/architecture/rolling-upgrades.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
34 changes: 28 additions & 6 deletions docs/concepts/memory.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 5 additions & 2 deletions docs/use-cases/memory-linked-to-code.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
149 changes: 149 additions & 0 deletions server/code/domain/successor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -139,6 +145,149 @@ 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)
arrived = [
(d, side)
for side in new
for d in side.defs
if not small or _may_be(was, before, d, side, 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, 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 new one keeping its
members. 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]
shared = len(old & kept)
return shared >= _MIN_SHARED and shared / len(old | kept) >= _KEPT_MEMBERS
Comment thread
zlareb1 marked this conversation as resolved.
Resolved


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."""
Expand Down
87 changes: 85 additions & 2 deletions server/memory/app/code_link_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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]:
Expand All @@ -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),
}

Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -246,6 +266,69 @@ 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."""

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 None
before = {local(name, old) for name in await self.names(base, old) or ()}
after = {local(name, now) for name in names or ()}
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))
Comment thread
zlareb1 marked this conversation as resolved.
Resolved

async def is_ancestor(self, ancestor: str, descendant: str) -> bool:
"""Whether `ancestor` is in `descendant`'s history."""
return await self._once(
Expand Down
Loading
Loading