Skip to content

Migration hash gate

The check that every syntactic migration hop preserves every core hash, run by qvr hash --check-migrations and in CI over the whole corpus.

migration_gate

The gate that every syntactic migration hop preserves every core hash.

A migration hop rewrites source from one grammar revision to the next. A syntactic hop must not change what the source means, and the core hash of a checked declaration (module_hashes) is exactly what it means, with names, comments, and layout factored out. So a syntactic hop must leave the multiset of core hashes of every file it rewrites unchanged. A hop that may change meaning declares so in SEMANTIC_HOPS, and a feature of the release hop in its semantic field.

Only the current grammar's compiler can check source, so the gate checks each hop on the corpus files that are also valid source at the hop's revision: it migrates such a file from that revision to HEAD and requires the result to have the core hashes of the file itself. A hop that rewrites a construct it should have left alone, renames inconsistently, or changes a constant fails, even when every parse gate passes. Each feature of the release hop is checked alone as well, so a failure names the feature responsible.

CORPUS_ROOTS module-attribute

CORPUS_ROOTS: tuple[str, ...] = ('docs/examples/source', 'docs/examples/qiec', 'docs/tutorials/qvr/source', 'tests/benchmarks/models', 'tests/transpile/fixtures', 'regression.qvr')

The .qvr corpus the gate runs over, relative to the repository root.

HopStatus

HopStatus = Literal['preserved', 'identical', 'changed', 'rejected', 'semantic']

What the gate found for one hop and one file:

  • preserved: the hop rewrote the file and every core hash survived;
  • identical: the hop left the bytes unchanged;
  • changed: the hop rewrote the file and some core hash changed, which fails the gate;
  • rejected: the file is not valid source at the hop's revision, or the migrated text does not check at HEAD, so the hop is not tested on it;
  • semantic: the hop declares that it may change meaning.

GateHop didactic-model

GateHop(*, source: str, target: str, feature: str = '', migrate: Callable[[bytes], bytes] = field(opaque=True, extras=OPAQUE_BY_IDENTITY), semantic: str = '')

Bases: ValueModel

One migration step the gate checks.

PARAMETER DESCRIPTION
source

The revision the step starts at.

TYPE: str

target

The revision the hop under test ends at.

TYPE: str

feature

The release-hop feature applied alone, or empty for a whole hop.

TYPE: str DEFAULT: ''

migrate

The rewrite from the hop's source revision all the way to HEAD, so the result can be checked.

TYPE: Callable[[bytes], bytes] DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

semantic

Why the step may change meaning, or empty for a syntactic step.

TYPE: str DEFAULT: ''

label property

label: str

The step's name in reports.

RETURNS DESCRIPTION
str

source -> target, with [feature] for a single feature.

HopOutcome didactic-model

HopOutcome(*, hop: str, file: str, status: HopStatus, detail: str = '')

Bases: Model

The gate's finding for one step and one file.

PARAMETER DESCRIPTION
hop

The step's label.

TYPE: str

file

The file.

TYPE: str

status

What was found.

TYPE: HopStatus

detail

The reason for a rejection, the semantic declaration, or the core hashes that appeared and disappeared.

TYPE: str DEFAULT: ''

InvarianceReport didactic-model

InvarianceReport(*, files: tuple[str, ...] = (), unchecked: tuple[str, ...] = (), outcomes: tuple[HopOutcome, ...] = ())

Bases: Model

Everything the gate found.

PARAMETER DESCRIPTION
files

The corpus files that check at HEAD, which the gate used.

TYPE: tuple[str, ...] DEFAULT: ()

unchecked

The corpus files that do not check at HEAD, each with the reason.

TYPE: tuple[str, ...] DEFAULT: ()

outcomes

One outcome per step and usable file.

TYPE: tuple[HopOutcome, ...] DEFAULT: ()

failures property

failures: tuple[HopOutcome, ...]

The outcomes that fail the gate.

RETURNS DESCRIPTION
tuple[HopOutcome, ...]

Every changed outcome.

ok property

ok: bool

Whether every syntactic step preserved every core hash.

RETURNS DESCRIPTION
bool

True when no outcome is changed.

summary_lines

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

A human-readable report.

RETURNS DESCRIPTION
tuple[str, ...]

One line per step with its counts, then one per failure.

Source code in src/quivers/incremental/migration_gate.py
def summary_lines(self) -> tuple[str, ...]:
    """A human-readable report.

    Returns
    -------
    tuple[str, ...]
        One line per step with its counts, then one per failure.
    """
    counts: dict[str, dict[str, int]] = {}
    for outcome in self.outcomes:
        row = counts.setdefault(outcome.hop, {})
        row[outcome.status] = row.get(outcome.status, 0) + 1
    lines = [f"{len(self.files)} files check at HEAD; {len(self.unchecked)} do not"]
    for hop, row in counts.items():
        cells = ", ".join(
            f"{status} {count}" for status, count in sorted(row.items())
        )
        lines.append(f"{hop}: {cells}")
    for failure in self.failures:
        lines.append(f"FAIL {failure.hop} {failure.file}: {failure.detail}")
    lines.append("ok" if self.ok else f"{len(self.failures)} failure(s)")
    return tuple(lines)

corpus_files

corpus_files(roots: Iterable[str]) -> tuple[Path, ...]

Every .qvr file under some roots.

PARAMETER DESCRIPTION
roots

Files and directories.

TYPE: Iterable[str]

RETURNS DESCRIPTION
tuple[Path, ...]

The files, each directory's sorted.

Source code in src/quivers/incremental/migration_gate.py
def corpus_files(roots: Iterable[str]) -> tuple[Path, ...]:
    """Every ``.qvr`` file under some roots.

    Parameters
    ----------
    roots : Iterable[str]
        Files and directories.

    Returns
    -------
    tuple[Path, ...]
        The files, each directory's sorted.
    """
    found: list[Path] = []
    for root in roots:
        path = Path(root)
        found.extend(sorted(path.rglob("*.qvr")) if path.is_dir() else [path])
    return tuple(found)

default_hops

default_hops(*, chain: Sequence[str] = CHAIN, migrators: Mapping[tuple[str, str], Callable[[bytes], bytes]] = MIGRATORS, semantic: Mapping[tuple[str, str], str] = SEMANTIC_HOPS) -> tuple[GateHop, ...]

The steps the gate checks for a migration chain.

PARAMETER DESCRIPTION
chain

The revisions, oldest first, HEAD last.

TYPE: Sequence[str] DEFAULT: CHAIN

migrators

The hop of each adjacent pair.

TYPE: Mapping[tuple[str, str], Callable[[bytes], bytes]] DEFAULT: MIGRATORS

semantic

The hops that declare they may change meaning.

TYPE: Mapping[tuple[str, str], str] DEFAULT: SEMANTIC_HOPS

RETURNS DESCRIPTION
tuple[GateHop, ...]

One step per hop, migrating from the hop's source revision to HEAD (the release hop applying only its syntactic features, so a semantic feature does not hide every older hop), and one step per feature of the release hop.

Source code in src/quivers/incremental/migration_gate.py
def default_hops(
    *,
    chain: Sequence[str] = CHAIN,
    migrators: Mapping[tuple[str, str], Callable[[bytes], bytes]] = MIGRATORS,
    semantic: Mapping[tuple[str, str], str] = SEMANTIC_HOPS,
) -> tuple[GateHop, ...]:
    """The steps the gate checks for a migration chain.

    Parameters
    ----------
    chain : Sequence[str]
        The revisions, oldest first, ``HEAD`` last.
    migrators : Mapping[tuple[str, str], Callable[[bytes], bytes]]
        The hop of each adjacent pair.
    semantic : Mapping[tuple[str, str], str]
        The hops that declare they may change meaning.

    Returns
    -------
    tuple[GateHop, ...]
        One step per hop, migrating from the hop's source revision to
        ``HEAD`` (the release hop applying only its syntactic features, so a
        semantic feature does not hide every older hop), and one step per
        feature of the release hop.
    """
    release_pair = (_release.SOURCE_REVISION, _release.TARGET_REVISION)
    syntactic_features = tuple(
        item.name for item in _release.FEATURES if not item.semantic
    )
    pairs = list(zip(chain, chain[1:]))
    hops: list[GateHop] = []
    for index, (source, target) in enumerate(pairs):
        steps: list[Callable[[bytes], bytes]] = []
        reason = ""
        for pair in pairs[index:]:
            if pair == release_pair:
                steps.append(_release_features(syntactic_features))
            elif pair in semantic:
                reason = reason or f"{pair[0]} -> {pair[1]}: {semantic[pair]}"
                break
            else:
                steps.append(migrators[pair])
        own = semantic.get((source, target), "")
        if (source, target) == release_pair:
            own = ""
        hops.append(
            GateHop(
                source=source,
                target=target,
                migrate=_compose(steps),
                semantic=own or reason,
            )
        )
    if release_pair in pairs:
        for feature in _release.FEATURES:
            hops.append(
                GateHop(
                    source=release_pair[0],
                    target=release_pair[1],
                    feature=feature.name,
                    migrate=_release_features((feature.name,)),
                    semantic=feature.semantic,
                )
            )
    return tuple(hops)

check_migration_invariance

check_migration_invariance(files: Sequence[Path], *, hops: Sequence[GateHop] | None = None) -> InvarianceReport

Run the gate over corpus files.

PARAMETER DESCRIPTION
files

The corpus files, written in the HEAD surface.

TYPE: Sequence[Path]

hops

The steps to check; default_hops when None.

TYPE: Sequence[GateHop] or None DEFAULT: None

RETURNS DESCRIPTION
InvarianceReport

Every outcome; InvarianceReport.ok is the gate's verdict.

Source code in src/quivers/incremental/migration_gate.py
def check_migration_invariance(
    files: Sequence[Path],
    *,
    hops: Sequence[GateHop] | None = None,
) -> InvarianceReport:
    """Run the gate over corpus files.

    Parameters
    ----------
    files : Sequence[Path]
        The corpus files, written in the ``HEAD`` surface.
    hops : Sequence[GateHop] or None
        The steps to check; `default_hops` when None.

    Returns
    -------
    InvarianceReport
        Every outcome; `InvarianceReport.ok` is the gate's verdict.
    """
    steps = default_hops() if hops is None else tuple(hops)
    usable: list[tuple[str, bytes, tuple[tuple[str, str], ...]]] = []
    unchecked: list[str] = []
    for path in files:
        text = path.read_bytes()
        try:
            usable.append((str(path), text, _core(text, str(path))))
        except (IdentityError, ContentHashError) as error:
            unchecked.append(f"{path}: {error}")
    outcomes: list[HopOutcome] = []
    for hop in steps:
        for name, text, base in usable:
            outcomes.append(_check_one(hop, name, text, base))
    return InvarianceReport(
        files=tuple(name for name, _, _ in usable),
        unchecked=tuple(unchecked),
        outcomes=tuple(outcomes),
    )