Skip to content

Dependency lenses

lenses

Dependency lenses: how a package's interface change maps its dependents.

When a package moves from one version to another, every dependent module and every stored run record that names one of its symbols must follow. A DependencyLens describes the move in panproto's terms [@foster2007combinators; @litt2020cambria]:

  • each interface is an inventory, a panproto schema (in the json-schema protocol) with one vertex per symbol, and a dependent's usage is an instance of it: each symbol the dependent names, with the places it names it;
  • a rename is a symbol whose identity (quivers.packages.interface) the new interface keeps under a new path; the renames form a theory morphism phi from the old inventory's theory to the new one's;
  • the residual chain is diff_to_protolens of the old inventory and the new inventory spelled in old names, so it holds exactly the symbols that were removed (with no image under phi) and the ones that were added;
  • the chain is lifted along phi (lift_protolens) and applied to the usages of every dependent at once (apply_to_fleet). Getting a usage through the lens drops exactly the places that name a removed symbol: the lens's complement lists every place no lens reaches, so nothing is dropped silently.

A place the lens keeps is renamed to the image of its symbol under phi.

INVENTORY_PROTOCOL module-attribute

INVENTORY_PROTOCOL = 'json-schema'

The panproto protocol inventories and usages are written in.

LensError

Bases: ValueError

A lens that cannot be built or applied.

Its message says what failed.

Rename didactic-model

Rename(*, old: str, new: str, kind: str)

Bases: Model

A symbol the new interface keeps under another path.

ATTRIBUTE DESCRIPTION
old

Its old path.

TYPE: str

new

Its new path.

TYPE: str

kind

Its kind.

TYPE: str

Use didactic-model

Use(*, symbol: str, place: str)

Bases: Model

One place a dependent names a symbol.

ATTRIBUTE DESCRIPTION
symbol

The symbol's old path.

TYPE: str

place

Where (a key the dependent understands: a byte span of a module, or a site key of a run record).

TYPE: str

Unmigratable didactic-model

Unmigratable(*, use: Use, reason: str)

Bases: Model

A place no lens reaches.

ATTRIBUTE DESCRIPTION
use

The place.

TYPE: Use

reason

Why: the symbol was removed with no replacement, or the dependent's usage did not satisfy the lens.

TYPE: str

RenamedUse didactic-model

RenamedUse(*, use: Use, new: str)

Bases: Model

A kept place and its symbol's new path.

ATTRIBUTE DESCRIPTION
use

The place.

TYPE: Use

new

The symbol's path in the new interface.

TYPE: str

MemberOutcome didactic-model

MemberOutcome(*, member: str, renames: tuple[RenamedUse, ...] = (), unmigratable: tuple[Unmigratable, ...] = ())

Bases: Model

What a lens does to one dependent.

ATTRIBUTE DESCRIPTION
member

The dependent.

TYPE: str

renames

Each kept place with its symbol's new path.

TYPE: tuple[RenamedUse, ...]

unmigratable

Each place no lens reaches.

TYPE: tuple[Unmigratable, ...]

DependencyLens didactic-model

DependencyLens(*, package: str, old_version: Version, new_version: Version, renames: tuple[Rename, ...] = (), removed: tuple[str, ...] = (), added: tuple[str, ...] = (), old_paths: tuple[str, ...] = (), chain: str = '', morphism: str = '')

Bases: Model

The lens from one version of a package's interface to another.

ATTRIBUTE DESCRIPTION
package

The package.

TYPE: str

old_version, new_version

The versions.

TYPE: Version

renames

The symbols kept under new paths, by old path.

TYPE: tuple[Rename, ...]

removed

The old paths with no image.

TYPE: tuple[str, ...]

added

The new paths no old symbol maps to.

TYPE: tuple[str, ...]

old_paths

Every old path.

TYPE: tuple[str, ...]

chain

The residual protolens chain, as panproto's JSON.

TYPE: str

morphism

The renaming theory morphism, as panproto's JSON.

TYPE: str

between classmethod

The lens from an old interface to a new one.

PARAMETER DESCRIPTION
old

The interfaces.

TYPE: PackageInterface

new

The interfaces.

TYPE: PackageInterface

RETURNS DESCRIPTION
DependencyLens

The renames, the residual chain, and the renaming morphism.

RAISES DESCRIPTION
LensError

If panproto cannot derive the residual chain.

Source code in src/quivers/packages/lenses.py
@classmethod
def between(cls, old: PackageInterface, new: PackageInterface) -> DependencyLens:
    """The lens from an old interface to a new one.

    Parameters
    ----------
    old, new : PackageInterface
        The interfaces.

    Returns
    -------
    DependencyLens
        The renames, the residual chain, and the renaming morphism.

    Raises
    ------
    LensError
        If panproto cannot derive the residual chain.
    """
    renames, removed, added = _renames(old, new)
    back = {rename.new: rename.old for rename in renames}
    old_paths = [symbol.path for symbol in old.symbols]
    new_in_old = [back.get(symbol.path, symbol.path) for symbol in new.symbols]
    try:
        chain = panproto.diff_to_protolens(
            _inventory(old_paths), _inventory(new_in_old)
        )
    except panproto.LensError as error:
        raise LensError(
            f"panproto cannot derive the interface chain of {old.package}: {error}"
        ) from error
    image = {rename.old: rename.new for rename in renames}
    sort_map = {_ROOT: _ROOT}
    for path in old_paths:
        if path in removed:
            continue
        target = image.get(path, path)
        sort_map[path] = target
        sort_map[path + _USE] = target + _USE
    morphism = panproto.TheoryMorphism(
        f"{old.package}@{old.version.render()}..{new.version.render()}",
        f"{old.package}@{old.version.render()}",
        f"{new.package}@{new.version.render()}",
        sort_map,
    )
    return cls(
        package=old.package,
        old_version=old.version,
        new_version=new.version,
        renames=renames,
        removed=removed,
        added=added,
        old_paths=tuple(sorted(old_paths)),
        chain=chain.to_json(),
        morphism=morphism.to_json(),
    )

image

image(path: str) -> str | None

Where an old symbol is in the new interface.

PARAMETER DESCRIPTION
path

An old symbol path.

TYPE: str

RETURNS DESCRIPTION
str | None

Its new path, or None when it was removed.

Source code in src/quivers/packages/lenses.py
def image(self, path: str) -> str | None:
    """Where an old symbol is in the new interface.

    Parameters
    ----------
    path : str
        An old symbol path.

    Returns
    -------
    str | None
        Its new path, or ``None`` when it was removed.
    """
    if path in self.removed:
        return None
    for rename in self.renames:
        if rename.old == path:
            return rename.new
    return path

is_identity

is_identity() -> bool

Whether the lens renames, removes, and adds nothing.

RETURNS DESCRIPTION
bool

Whether dependents need no change.

Source code in src/quivers/packages/lenses.py
def is_identity(self) -> bool:
    """Whether the lens renames, removes, and adds nothing.

    Returns
    -------
    bool
        Whether dependents need no change.
    """
    return not (self.renames or self.removed or self.added)

apply

apply(fleet: Mapping[str, tuple[Use, ...]]) -> tuple[MemberOutcome, ...]

Apply the lens to the usages of every dependent at once.

The residual chain is fused, lifted along the renaming morphism, and applied to each dependent's usage schema; each usage is read through the lens it instantiates, and the places its complement holds are the ones no lens reaches. With no residual change, the morphism alone maps every place.

PARAMETER DESCRIPTION
fleet

Each dependent's places, by name.

TYPE: Mapping[str, tuple[Use, ...]]

RETURNS DESCRIPTION
tuple[MemberOutcome, ...]

Each dependent's renamed and unmigratable places, by name.

RAISES DESCRIPTION
LensError

If a use names a symbol the old interface does not have.

Source code in src/quivers/packages/lenses.py
def apply(self, fleet: Mapping[str, tuple[Use, ...]]) -> tuple[MemberOutcome, ...]:
    """Apply the lens to the usages of every dependent at once.

    The residual chain is fused, lifted along the renaming morphism, and
    applied to each dependent's usage schema; each usage is read through
    the lens it instantiates, and the places its complement holds are
    the ones no lens reaches. With no residual change, the morphism
    alone maps every place.

    Parameters
    ----------
    fleet : Mapping[str, tuple[Use, ...]]
        Each dependent's places, by name.

    Returns
    -------
    tuple[MemberOutcome, ...]
        Each dependent's renamed and unmigratable places, by name.

    Raises
    ------
    LensError
        If a use names a symbol the old interface does not have.
    """
    known = set(self.old_paths)
    for member, uses in fleet.items():
        for use in uses:
            if use.symbol not in known:
                raise LensError(
                    f"{member} names {use.symbol}, which {self.package} "
                    f"{self.old_version.render()} does not provide"
                )
    chain = panproto.ProtolensChain.from_json(self.chain)
    kept_by: dict[str, set[str]] = {}
    reasons: dict[str, str] = {}
    if len(chain):
        morphism = panproto.TheoryMorphism.from_json(self.morphism)
        lifted = panproto.lift_protolens(chain.fuse(), morphism)
        protocol = panproto.get_builtin_protocol(INVENTORY_PROTOCOL)
        schemas = {
            member: _inventory([use.symbol for use in uses])
            for member, uses in fleet.items()
        }
        result = panproto.apply_to_fleet(lifted, schemas, protocol)
        for member, lens in result.applied.items():
            uses = fleet[member]
            document: dict[str, list[str]] = {}
            for use in uses:
                document.setdefault(use.symbol, []).append(use.place)
            instance = panproto.Instance.from_json(
                schemas[member], _ROOT, json.dumps(document, sort_keys=True)
            )
            view, _complement = lens.get(instance)
            kept = json.loads(view.to_json())
            kept_by[member] = {
                f"{symbol}\0{place}"
                for symbol, places in kept.items()
                for place in places
            }
        for member, failures in result.skipped.items():
            reasons[member] = "; ".join(failures)
    outcomes: list[MemberOutcome] = []
    for member in sorted(fleet):
        renamed: list[RenamedUse] = []
        dropped: list[Unmigratable] = []
        kept_places = kept_by.get(member)
        for use in fleet[member]:
            target = self.image(use.symbol)
            if member in reasons:
                dropped.append(Unmigratable(use=use, reason=reasons[member]))
                continue
            survives = (
                target is not None
                if kept_places is None
                else f"{use.symbol}\0{use.place}" in kept_places
            )
            if not survives or target is None:
                dropped.append(
                    Unmigratable(
                        use=use,
                        reason=f"{use.symbol} was removed from {self.package} in "
                        f"{self.new_version.render()} and has no replacement",
                    )
                )
                continue
            renamed.append(RenamedUse(use=use, new=target))
        outcomes.append(
            MemberOutcome(
                member=member, renames=tuple(renamed), unmigratable=tuple(dropped)
            )
        )
    return tuple(outcomes)

to_json

to_json() -> str

The lens as the JSON document qvr bump emits.

RETURNS DESCRIPTION
str

Canonical JSON.

Source code in src/quivers/packages/lenses.py
def to_json(self) -> str:
    """The lens as the JSON document `qvr bump` emits.

    Returns
    -------
    str
        Canonical JSON.
    """
    return json.dumps(json.loads(self.model_dump_json()), sort_keys=True, indent=2)

from_json classmethod

from_json(text: str) -> DependencyLens

Read an emitted lens.

PARAMETER DESCRIPTION
text

What to_json wrote.

TYPE: str

RETURNS DESCRIPTION
DependencyLens

The lens.

Source code in src/quivers/packages/lenses.py
@classmethod
def from_json(cls, text: str) -> DependencyLens:
    """Read an emitted lens.

    Parameters
    ----------
    text : str
        What `to_json` wrote.

    Returns
    -------
    DependencyLens
        The lens.
    """
    return cls.model_validate_json(text)

inventory_schema

inventory_schema(interface: PackageInterface) -> Schema

The inventory of an interface: one vertex per symbol.

PARAMETER DESCRIPTION
interface

The interface.

TYPE: PackageInterface

RETURNS DESCRIPTION
Schema

A json-schema schema whose root object has one array property per symbol path, holding the places a dependent names it.

Source code in src/quivers/packages/lenses.py
def inventory_schema(interface: PackageInterface) -> panproto.Schema:
    """The inventory of an interface: one vertex per symbol.

    Parameters
    ----------
    interface : PackageInterface
        The interface.

    Returns
    -------
    panproto.Schema
        A ``json-schema`` schema whose root object has one array property
        per symbol path, holding the places a dependent names it.
    """
    return _inventory([symbol.path for symbol in interface.symbols])

migration

Migrating dependents and stored runs across a dependency's interface change.

qvr migrate --dependency pkg@old..new moves a package's own modules and its stored run records from one version of a dependency to another:

  1. the locked build supplies the old version and the manifest the new one;
  2. the dependency lens (quivers.packages.lenses.DependencyLens) is the one the new version emitted (lenses/ in its source), or is computed from the two versions' interfaces;
  3. every module of the package is a member of the fleet: its usage is each place it names a symbol of the dependency, found by name resolution against the old build. The lens maps each place to the symbol's new path, or reports it as unmigratable, with its location, when the symbol was removed;
  4. a module whose places all map is rewritten by the grammar migration chain's own machinery (quivers.cli.migrations._features.migrate_with): token-local edits of each name's own segment, checked for overlaps, trailing whitespace, and a clean parse of the result. The result is then resolved against the new build, and a module in which a new name would resolve to anything but the renamed symbol is refused;
  5. a run record is migrated by the same lens construction over the sites of its program: the old site table is the record's, the new one is the migrated program's, sites correspond by their rename-stable identities, and a stored site whose identity the new program lacks is reported unmigratable.

A dependency lens renames; it never changes what a declaration means, so a migrated module has the same content hashes against the new dependency as the original against the old one.

DependencyMigrationError

Bases: ValueError

A dependency migration that cannot start.

Its message says why.

SiteReport didactic-model

SiteReport(*, file: str, line: int = 0, column: int = 0, symbol: str, reason: str)

Bases: Model

A place a dependency migration could not migrate.

ATTRIBUTE DESCRIPTION
file

The module file or run record.

TYPE: str

line, column

Where (0 for a run record's site).

TYPE: int

symbol

The dependency's symbol the place names.

TYPE: str

reason

Why no lens reaches it.

TYPE: str

render

render() -> str

The report as one diagnostic line.

RETURNS DESCRIPTION
str

file:line:col: unmigratable: symbol: reason.

Source code in src/quivers/packages/migration.py
def render(self) -> str:
    """The report as one diagnostic line.

    Returns
    -------
    str
        ``file:line:col: unmigratable: symbol: reason``.
    """
    where = self.file if not self.line else f"{self.file}:{self.line}:{self.column}"
    return f"{where}: unmigratable: {self.symbol}: {self.reason}"

MigratedFile didactic-model

MigratedFile(*, path: str, text: str, changed: bool)

Bases: Model

One file a dependency migration rewrites.

ATTRIBUTE DESCRIPTION
path

The file.

TYPE: str

text

Its migrated text.

TYPE: str

changed

Whether the text differs from the file's.

TYPE: bool

DependencyMigration didactic-model

DependencyMigration(*, lens: DependencyLens, files: tuple[MigratedFile, ...] = (), unmigratable: tuple[SiteReport, ...] = ())

Bases: Model

The outcome of migrating a package's dependents of one dependency.

ATTRIBUTE DESCRIPTION
lens

The lens applied.

TYPE: DependencyLens

files

Every module and run record that migrated, by path.

TYPE: tuple[MigratedFile, ...]

unmigratable

Every place no lens reaches, by file and position; a file with such a place is not rewritten.

TYPE: tuple[SiteReport, ...]

write

write() -> tuple[str, ...]

Write every migrated file that changed.

RETURNS DESCRIPTION
tuple[str, ...]

The paths written.

Source code in src/quivers/packages/migration.py
def write(self) -> tuple[str, ...]:
    """Write every migrated file that changed.

    Returns
    -------
    tuple[str, ...]
        The paths written.
    """
    written: list[str] = []
    for migrated in self.files:
        if migrated.changed:
            Path(migrated.path).write_text(migrated.text, encoding="utf-8")
            written.append(migrated.path)
    return tuple(written)

DependencyMigrator

DependencyMigrator(workspace: Workspace, dependency: str, old: Version, new: Version)

Migrate one package's modules and run records across a dependency change.

PARAMETER DESCRIPTION
workspace

The dependent package.

TYPE: Workspace

dependency

The dependency's name.

TYPE: str

old

The version the package is locked to.

TYPE: Version

new

The version its manifest now resolves to.

TYPE: Version

Source code in src/quivers/packages/migration.py
def __init__(
    self, workspace: Workspace, dependency: str, old: Version, new: Version
) -> None:
    self.workspace = workspace
    self.dependency = dependency
    self.old_version = old
    self.new_version = new
    locked = read_lockfile(workspace.root)
    if locked is None:
        raise DependencyMigrationError(
            f"{workspace.root} has no qvr.lock: the lockfile records the version "
            "migrated from; lock the package before changing the dependency"
        )
    self.old_build = workspace.locked_build(locked)
    self.new_build = workspace.resolve()
    self.old_package = self._package(self.old_build, old, "locked build")
    self.new_package = self._package(self.new_build, new, "manifest")
    self.old_interface = package_version_interface(
        Path(self.old_package.directory), workspace.cache
    ).interface
    self.new_interface = package_version_interface(
        Path(self.new_package.directory), workspace.cache
    ).interface
    emitted = read_emitted_lens(
        Path(self.new_package.directory), dependency, old, new
    )
    self.lens = (
        emitted
        if emitted is not None
        else DependencyLens.between(self.old_interface, self.new_interface)
    )

modules

modules() -> tuple[str, ...]

The package's own modules, which the migration covers.

RETURNS DESCRIPTION
tuple[str, ...]

Their paths.

Source code in src/quivers/packages/migration.py
def modules(self) -> tuple[str, ...]:
    """The package's own modules, which the migration covers.

    Returns
    -------
    tuple[str, ...]
        Their paths.
    """
    return self.new_build.root.module_paths()

migrate

migrate(records: Iterable[Path] = ()) -> DependencyMigration

Migrate every module of the package and the given run records.

PARAMETER DESCRIPTION
records

Run records (qvr run --json output) of the package's programs.

TYPE: Iterable[Path] DEFAULT: ()

RETURNS DESCRIPTION
DependencyMigration

The migrated texts and every unmigratable place.

RAISES DESCRIPTION
DependencyMigrationError

If the migration cannot start.

MigrationError

If a rewritten module does not parse.

Source code in src/quivers/packages/migration.py
def migrate(self, records: Iterable[Path] = ()) -> DependencyMigration:
    """Migrate every module of the package and the given run records.

    Parameters
    ----------
    records : Iterable[Path]
        Run records (``qvr run --json`` output) of the package's
        programs.

    Returns
    -------
    DependencyMigration
        The migrated texts and every unmigratable place.

    Raises
    ------
    DependencyMigrationError
        If the migration cannot start.
    MigrationError
        If a rewritten module does not parse.
    """
    origins = _origins(self.old_interface)
    fleet: dict[str, tuple[Use, ...]] = {}
    places: dict[str, dict[str, _Place]] = {}
    sources: dict[str, tuple[str, str]] = {}
    for module in self.modules():
        graph = self.workspace.load(module, self.old_build)
        source = graph.loaded[graph.root].source
        uses, located = _uses(graph, origins)
        fleet[module] = uses
        places[module] = located
        sources[module] = (source.file or source.label, source.text)
    outcomes = self.lens.apply(fleet)
    files: list[MigratedFile] = []
    reports: list[SiteReport] = []
    migrated_texts: dict[str, str] = {}
    for outcome in outcomes:
        path, text = sources[outcome.member]
        if outcome.unmigratable:
            reports.extend(
                self._report(path, places[outcome.member], item)
                for item in outcome.unmigratable
            )
            continue
        new_text = self._rewrite(outcome, places[outcome.member], text)
        migrated_texts[outcome.member] = new_text
        files.append(
            MigratedFile(path=path, text=new_text, changed=new_text != text)
        )
    if not reports:
        self._check_captures(migrated_texts, outcomes)
    for record in records:
        migrated, record_reports = self.migrate_record(record, migrated_texts)
        reports.extend(record_reports)
        if migrated is not None:
            files.append(migrated)
    return DependencyMigration(
        lens=self.lens,
        files=tuple(sorted(files, key=lambda item: item.path)),
        unmigratable=tuple(reports),
    )

migrate_record

migrate_record(record: Path, migrated: Mapping[str, str]) -> tuple[MigratedFile | None, tuple[SiteReport, ...]]

Migrate one run record of one of the package's programs.

PARAMETER DESCRIPTION
record

The record, as qvr run --json writes it.

TYPE: Path

migrated

The package's migrated module texts, by path.

TYPE: Mapping[str, str]

RETURNS DESCRIPTION
tuple[MigratedFile | None, tuple[SiteReport, ...]]

The migrated record (None when a site of it has no counterpart) and the unmigratable sites.

RAISES DESCRIPTION
DependencyMigrationError

If the record is not a run record of one of the package's programs.

Source code in src/quivers/packages/migration.py
def migrate_record(
    self, record: Path, migrated: Mapping[str, str]
) -> tuple[MigratedFile | None, tuple[SiteReport, ...]]:
    """Migrate one run record of one of the package's programs.

    Parameters
    ----------
    record : Path
        The record, as ``qvr run --json`` writes it.
    migrated : Mapping[str, str]
        The package's migrated module texts, by path.

    Returns
    -------
    tuple[MigratedFile | None, tuple[SiteReport, ...]]
        The migrated record (``None`` when a site of it has no
        counterpart) and the unmigratable sites.

    Raises
    ------
    DependencyMigrationError
        If the record is not a run record of one of the package's
        programs.
    """
    loaded: JsonData = json.loads(record.read_text(encoding="utf-8"))
    if not isinstance(loaded, dict):
        raise DependencyMigrationError(f"{record} is not a run record")
    data = loaded
    stored = data.get("sites")
    if not isinstance(stored, dict):
        raise DependencyMigrationError(
            f"{record} is not a run record: it has no site table"
        )
    table = SiteTable.from_data(stored)
    module = self._record_module(record, table)
    if module not in migrated:
        return None, (
            SiteReport(
                file=str(record),
                symbol=table.entry,
                reason=f"its module {module} has unmigratable places",
            ),
        )
    new_table = self._site_table(module, table.entry, migrated)
    old_interface = _site_interface(table, self.old_version)
    new_interface = _site_interface(new_table, self.new_version)
    lens = DependencyLens.between(old_interface, new_interface)
    uses = tuple(Use(symbol=site.key, place=site.key) for site in table.sites)
    (outcome,) = lens.apply({str(record): uses})
    if outcome.unmigratable:
        return None, tuple(
            SiteReport(
                file=str(record),
                symbol=item.use.symbol,
                reason=f"the stored site {item.use.symbol} has no counterpart in "
                f"{table.entry} against {self.dependency} "
                f"{self.new_version.render()}: its declaration changed",
            )
            for item in outcome.unmigratable
        )
    keys = {renamed.use.symbol: renamed.new for renamed in outcome.renames}
    renamed_names = self._renamed_flat_names()
    migrated_data: dict[str, JsonData] = {
        key: _rename_strings(value, renamed_names)
        for key, value in data.items()
        if key not in ("sites", "site_values")
    }
    migrated_data["sites"] = _json_data(new_table.to_data())
    values = data.get("site_values")
    if isinstance(values, dict):
        migrated_data["site_values"] = {
            keys.get(key, key): value for key, value in values.items()
        }
    text = json.dumps(migrated_data, indent=2) + "\n"
    original = record.read_text(encoding="utf-8")
    return MigratedFile(path=str(record), text=text, changed=text != original), ()

file_resolutions

file_resolutions(graph: ModuleGraph) -> tuple[Resolution, ...]

Every name resolution of a graph's root file, module bodies included.

PARAMETER DESCRIPTION
graph

A graph rooted at a file.

TYPE: ModuleGraph

RETURNS DESCRIPTION
tuple[Resolution, ...]

The root module's resolutions, then those of the modules, signatures, and templates declared in it.

Source code in src/quivers/packages/migration.py
def file_resolutions(graph: ModuleGraph) -> tuple[NameResolution, ...]:
    """Every name resolution of a graph's root file, module bodies included.

    Parameters
    ----------
    graph : ModuleGraph
        A graph rooted at a file.

    Returns
    -------
    tuple[NameResolution, ...]
        The root module's resolutions, then those of the modules,
        signatures, and templates declared in it.
    """
    found = list(graph.checked[graph.root].resolutions)
    names = graph.loaded[graph.root].names
    if not names.regions:
        return tuple(found)
    system = ModuleSystem(graph, {})
    for region in names.regions:
        found.extend(
            system.checked(RegionRef(file=graph.root, vid=region.vid)).resolutions
        )
    return tuple(found)