Skip to content

Content hashes

Alpha-invariant content hashes of checked declarations, the shared digest and canonical serialization every content identity is built from, and subterm hashing modulo alpha-equivalence. What a hash covers is defined in Content identity.

content_hash

Content identity of checked QIEC declarations.

Every declaration of a checked QiecModule has a content hash: a BLAKE3 digest of its core form, which is its stable wire encoding (the language qiec-json admits) after alpha-normalization. The core form keeps everything that determines what a declaration means and drops everything that only names or locates it:

  • Local binders become de Bruijn levels. A value binder (a computation or handler parameter, a bind, let, comprehension, or case-branch binder) records only its type, and each occurrence of the local records the level of its binder. Checked QIEC never rebinds a local within a body, so a level is unambiguous.
  • Names become ordinals. A static binder name (a telescope binder) and every name the core resolves by spelling (a site label, a plate axis, a program parameter, an index-sort constructor, the owner and member path of a learned parameter's name) becomes the ordinal of its first occurrence. Static names bound inside the declaration take ordinals in one space; names free in the declaration take ordinals in a second space, which is the declaration's free-name interface.
  • References become hashes. A reference to another declaration of the module (a computation, a family or one of its constructors, an effect or one of its operations, a handler, a custom distribution family) becomes that declaration's hash together with the substitution of the caller's ordinals for the callee's free names, so the correspondence of names across declarations is part of the caller's identity while their spelling is not.
  • Generative identities become ordinals. An effect instance is generative: two instances of one interface are distinct even though their declarations agree. Instance identities are therefore free names, not content.
  • Structure declarations are declarations. Each StructureDecl (an object, a program, a deduction, a relation, a loss, ...) is hashed like any other declaration: the names its term binds become ordinals, a reference to another structure becomes that structure's hash, and every other string and number is content. A structure the core also elaborates (a program, whose parameters, steps, and returns are its entry) is hashed by a reference to that elaboration and its remaining fields, so how the elaborated fields are spelled does not enter its hash.
  • Names, comments, and positions are metadata. Declaration names, display names that duplicate an identity, source protocols, and file positions are dropped. Comments and layout never reach QIEC.

Mutually recursive declarations are hashed as one strongly connected component. Its members are ordered canonically: first by the hash each member has with references into the component erased, then by iterated refinement over the component's reference structure, with any remaining symmetry broken by trying each candidate and keeping the least serialization. Member n of a component with hash h has the hash h.n.

Every digest is domain-separated by CONTENT_HASH_FORMAT and the kernel ABI QIEC_ABI, never by the source format, so a change of source syntax that elaborates to the same core leaves every hash unchanged.

alpha_hash and alpha_hashes hash individual terms modulo alpha-equivalence with the algorithm of Maziarz, Ellis, Lawrence, Fitzgibbon, and Peyton Jones (2021), so a normalizer can memoize by subterm; HashConsTable shares alpha-equivalent subterms.

CONTENT_HASH_FORMAT module-attribute

CONTENT_HASH_FORMAT = 'qiec-core-hash/v1'

The domain tag every content digest is computed under, beside the kernel ABI.

CoreJson

CoreJson = None | bool | int | float | str | list[CoreJson] | dict[str, CoreJson]

A core form: JSON data as json.dumps serializes it.

QiecDatum

QiecDatum = None | bool | int | float | str | bytes | Enum | StableId | Model | tuple[QiecDatum, ...] | Mapping[str, QiecDatum]

A value of the stable QIEC graph: a record, an identifier, an enum, a scalar, or a tuple or string-keyed mapping of those.

DeclarationKind

DeclarationKind = Literal['family', 'effect', 'handler', 'computation', 'entry', 'distribution', 'instance', 'index-sort', 'object', 'morphism', 'define', 'export', 'program', 'deduction', 'syntax', 'encoder', 'decoder', 'loss', 'category', 'rule', 'schema', 'bundle', 'contraction', 'composition', 'judgment', 'relation', 'relation-composition', 'relation-transform', 'string-graph', 'theory', 'view', 'model', 'semiring']

What a hashed declaration is: a kernel declaration, or a structure declaration of one of the kinds in STRUCTURE_KINDS.

ContentHashError

Bases: ValueError

A value has no core form, so it cannot be content addressed.

DeclarationHash didactic-model

DeclarationHash(*, kind: DeclarationKind, name: str, hash: str, component: str, member: int, size: int, names: tuple[str, ...] = ())

Bases: Model

The content identity of one declaration of a module.

PARAMETER DESCRIPTION
kind

What the declaration is.

TYPE: DeclarationKind

name

Its name in the module. A name is metadata: it does not enter the hash.

TYPE: str

hash

The declaration's content hash: the hash of its component when the component has one member, else <component>.<member>.

TYPE: str

component

The hash of the strongly connected component holding the declaration.

TYPE: str

member

The declaration's position among the component's canonically ordered members.

TYPE: int

size

How many declarations the component has.

TYPE: int

names

The declaration's free names in ordinal order: the spellings the core resolves by name that the declaration does not bind (site labels, program parameters, plate axes, returned names). They are metadata of the hash but the observable vocabulary of the declaration, which is why a stored run is keyed by them as well as by the hash.

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

ModuleHashes didactic-model

ModuleHashes(*, module: str, declarations: tuple[DeclarationHash, ...] = ())

Bases: Model

The content identities of a checked module.

PARAMETER DESCRIPTION
module

The module digest: the digest of the multiset of its declarations' kinds and hashes. It is invariant under renaming and reordering, like every declaration hash.

TYPE: str

declarations

One identity per declaration, in module order.

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

declaration

declaration(kind: DeclarationKind, name: str) -> DeclarationHash

Look up one declaration's identity.

PARAMETER DESCRIPTION
kind

The declaration's kind.

TYPE: DeclarationKind

name

The declaration's name.

TYPE: str

RETURNS DESCRIPTION
DeclarationHash

The identity.

RAISES DESCRIPTION
KeyError

If the module declares no such declaration.

Source code in src/quivers/qiec/content_hash.py
def declaration(self, kind: DeclarationKind, name: str) -> DeclarationHash:
    """Look up one declaration's identity.

    Parameters
    ----------
    kind : DeclarationKind
        The declaration's kind.
    name : str
        The declaration's name.

    Returns
    -------
    DeclarationHash
        The identity.

    Raises
    ------
    KeyError
        If the module declares no such declaration.
    """
    for declaration in self.declarations:
        if declaration.kind == kind and declaration.name == name:
            return declaration
    raise KeyError(f"no {kind} named {name!r} in the module")

hashes

hashes(kind: DeclarationKind) -> dict[str, str]

The hash of every declaration of one kind, by name.

PARAMETER DESCRIPTION
kind

The kind to select.

TYPE: DeclarationKind

RETURNS DESCRIPTION
dict[str, str]

Each declaration's name mapped to its hash.

Source code in src/quivers/qiec/content_hash.py
def hashes(self, kind: DeclarationKind) -> dict[str, str]:
    """The hash of every declaration of one kind, by name.

    Parameters
    ----------
    kind : DeclarationKind
        The kind to select.

    Returns
    -------
    dict[str, str]
        Each declaration's name mapped to its hash.
    """
    return {
        declaration.name: declaration.hash
        for declaration in self.declarations
        if declaration.kind == kind
    }

ModuleContent

ModuleContent(module: QiecModule)

The hashed declarations of one checked module.

Hashing a module walks every component once; this object keeps the result, so a caller that needs the module's hashes, a declaration's normal form, and the hash of a value that refers to the module pays for one walk.

PARAMETER DESCRIPTION
module

The checked module, as the lowering returns it.

TYPE: QiecModule

RAISES DESCRIPTION
ContentHashError

If the module holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def __init__(self, module: QiecModule) -> None:
    self._hasher = _ModuleHasher(module)
    self._hasher.run()
    identities: list[DeclarationHash] = []
    for index, declaration in enumerate(self._hasher.declarations):
        unit = self._hasher.units[index]
        member = unit.members.index(index)
        identities.append(
            DeclarationHash(
                kind=declaration.kind,
                name=declaration.name,
                hash=unit.hash
                if len(unit.members) == 1
                else f"{unit.hash}.{member}",
                component=unit.hash,
                member=member,
                size=len(unit.members),
                names=tuple(key[1] for key in unit.free if key[0] == "name"),
            )
        )
    digest = tagged_digest(
        "module",
        cast(
            CoreJson,
            sorted([identity.kind, identity.hash] for identity in identities),
        ),
    )
    self.hashes = ModuleHashes(module=digest, declarations=tuple(identities))
    """The module digest and one identity per declaration."""

hashes instance-attribute

hashes = ModuleHashes(module=digest, declarations=tuple(identities))

The module digest and one identity per declaration.

normal_form

normal_form(kind: DeclarationKind, name: str) -> str

The canonical serialization a declaration's component is hashed from.

PARAMETER DESCRIPTION
kind

The declaration's kind.

TYPE: DeclarationKind

name

The declaration's name.

TYPE: str

RETURNS DESCRIPTION
str

The JSON text of the component's core forms in canonical member order, which is what its hash digests. Useful for seeing why two declarations hash apart.

RAISES DESCRIPTION
KeyError

If the module has no such declaration.

Source code in src/quivers/qiec/content_hash.py
def normal_form(self, kind: DeclarationKind, name: str) -> str:
    """The canonical serialization a declaration's component is hashed from.

    Parameters
    ----------
    kind : DeclarationKind
        The declaration's kind.
    name : str
        The declaration's name.

    Returns
    -------
    str
        The JSON text of the component's core forms in canonical member
        order, which is what its hash digests. Useful for seeing why two
        declarations hash apart.

    Raises
    ------
    KeyError
        If the module has no such declaration.
    """
    for index, declaration in enumerate(self._hasher.declarations):
        if declaration.kind == kind and declaration.name == name:
            text, _ = self._hasher._serialize(
                list(self._hasher.units[index].members)
            )
            return text
    raise KeyError(f"no {kind} named {name!r} in the module")

value_hash

value_hash(kind: str, value: QiecDatum) -> str

The content hash of a value that refers to the module's declarations.

PARAMETER DESCRIPTION
kind

What the value is; it separates the digest's domain.

TYPE: str

value

The value, such as the interpretation bindings that accompany a checked entry.

TYPE: QiecDatum

RETURNS DESCRIPTION
str

The digest of the value's core form, in which references to the module's declarations are their hashes, exactly as inside a declaration.

RAISES DESCRIPTION
ContentHashError

If the value has no core form.

Source code in src/quivers/qiec/content_hash.py
def value_hash(self, kind: str, value: QiecDatum) -> str:
    """The content hash of a value that refers to the module's declarations.

    Parameters
    ----------
    kind : str
        What the value is; it separates the digest's domain.
    value : QiecDatum
        The value, such as the interpretation bindings that accompany a
        checked entry.

    Returns
    -------
    str
        The digest of the value's core form, in which references to the
        module's declarations are their hashes, exactly as inside a
        declaration.

    Raises
    ------
    ContentHashError
        If the value has no core form.
    """
    encoder = _Encoder(
        self._hasher.declarations,
        self._hasher.targets,
        self._hasher.distributions,
        self._hasher.units,
        None,
        frozenset(),
        self._hasher.elaborations,
        self._hasher.core_names,
    )
    form = encoder.standalone(value)
    return tagged_digest(
        kind,
        [
            form,
            [
                list(key)
                for key in sorted(encoder.free, key=encoder.free.__getitem__)
            ],
        ],
    )

SubtermHash didactic-model

SubtermHash(*, path: tuple[str | int, ...], hash: str)

Bases: Model

The alpha-invariant hash of one subterm.

PARAMETER DESCRIPTION
path

The field names and tuple positions leading from the root to the subterm.

TYPE: tuple[str | int, ...]

hash

The subterm's hash modulo alpha-equivalence. Two subterms share it exactly when they are alpha-equivalent as open terms with the same free locals.

TYPE: str

HashConsTable

HashConsTable()

A table sharing alpha-equivalent terms.

intern returns, for each record term, the first alpha-equivalent term the table has seen, so a normalizer that interns the terms it builds shares their alpha-equivalent pieces, and can memoize a result by alpha_hash and reuse it for every term alpha-equivalent to the one it computed it for.

Source code in src/quivers/qiec/content_hash.py
def __init__(self) -> None:
    self._representatives: dict[str, dx.Model] = {}

__len__

__len__() -> int

The number of distinct terms interned.

RETURNS DESCRIPTION
int

How many alpha-equivalence classes the table holds.

Source code in src/quivers/qiec/content_hash.py
def __len__(self) -> int:
    """The number of distinct terms interned.

    Returns
    -------
    int
        How many alpha-equivalence classes the table holds.
    """
    return len(self._representatives)

intern

intern(term: T) -> T

The table's representative of a term.

PARAMETER DESCRIPTION
term

A record term.

TYPE: T

RETURNS DESCRIPTION
T

The first term the table saw with the same alpha hash, which is term itself when it is new. Alpha-equivalent records are of one class, so the representative has the term's type.

RAISES DESCRIPTION
ContentHashError

If the term holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def intern[T: dx.Model](self, term: T) -> T:
    """The table's representative of a term.

    Parameters
    ----------
    term : T
        A record term.

    Returns
    -------
    T
        The first term the table saw with the same alpha hash, which is
        ``term`` itself when it is new. Alpha-equivalent records are of
        one class, so the representative has the term's type.

    Raises
    ------
    ContentHashError
        If the term holds a value with no core form.
    """
    digest = alpha_hash(term)
    return cast(T, self._representatives.setdefault(digest, term))

content_digest

content_digest(data: bytes) -> str

The BLAKE3 digest every content identity is built from.

PARAMETER DESCRIPTION
data

The bytes to digest.

TYPE: bytes

RETURNS DESCRIPTION
str

The 64-character lowercase hexadecimal BLAKE3 digest, the hash function panproto addresses its objects with.

Source code in src/quivers/qiec/content_hash.py
def content_digest(data: bytes) -> str:
    """The BLAKE3 digest every content identity is built from.

    Parameters
    ----------
    data : bytes
        The bytes to digest.

    Returns
    -------
    str
        The 64-character lowercase hexadecimal BLAKE3 digest, the hash
        function panproto addresses its objects with.
    """
    return blake3.blake3(data).hexdigest()

canonical_json

canonical_json(form: CoreJson) -> str

Serialize a core form deterministically.

PARAMETER DESCRIPTION
form

The form to serialize.

TYPE: CoreJson

RETURNS DESCRIPTION
str

Compact, key-sorted JSON. Floats use the shortest representation that reads back to the same double, so the text is the same on every run and every platform.

RAISES DESCRIPTION
ContentHashError

If the form contains a non-finite float, which has no JSON form.

Source code in src/quivers/qiec/content_hash.py
def canonical_json(form: CoreJson) -> str:
    """Serialize a core form deterministically.

    Parameters
    ----------
    form : CoreJson
        The form to serialize.

    Returns
    -------
    str
        Compact, key-sorted JSON. Floats use the shortest representation that
        reads back to the same double, so the text is the same on every run
        and every platform.

    Raises
    ------
    ContentHashError
        If the form contains a non-finite float, which has no JSON form.
    """
    try:
        return json.dumps(
            form,
            ensure_ascii=False,
            allow_nan=False,
            separators=(",", ":"),
            sort_keys=True,
        )
    except ValueError as error:
        raise ContentHashError(str(error)) from error

tagged_digest

tagged_digest(kind: str, form: CoreJson) -> str

Digest a core form under the content-hash domain.

PARAMETER DESCRIPTION
kind

What the form is ("unit", "module", "subterm", ...). It is part of the digested bytes, so forms of different kinds never share a digest.

TYPE: str

form

The form.

TYPE: CoreJson

RETURNS DESCRIPTION
str

The digest of CONTENT_HASH_FORMAT, QIEC_ABI, kind, and the canonical serialization of form, separated by NUL bytes.

RAISES DESCRIPTION
ContentHashError

If the form cannot be serialized.

Source code in src/quivers/qiec/content_hash.py
def tagged_digest(kind: str, form: CoreJson) -> str:
    """Digest a core form under the content-hash domain.

    Parameters
    ----------
    kind : str
        What the form is (``"unit"``, ``"module"``, ``"subterm"``, ...). It is
        part of the digested bytes, so forms of different kinds never share a
        digest.
    form : CoreJson
        The form.

    Returns
    -------
    str
        The digest of ``CONTENT_HASH_FORMAT``, ``QIEC_ABI``, ``kind``, and the
        canonical serialization of ``form``, separated by NUL bytes.

    Raises
    ------
    ContentHashError
        If the form cannot be serialized.
    """
    return content_digest(
        b"\x00".join(
            (
                CONTENT_HASH_FORMAT.encode(),
                QIEC_ABI.encode(),
                kind.encode(),
                canonical_json(form).encode("utf-8"),
            )
        )
    )

canonical_order

canonical_order(members: list[int], colors: Mapping[int, str], successors: Mapping[int, tuple[int, ...]], serialize: Callable[[list[int]], str]) -> list[int]

Order the members of a recursive component canonically.

PARAMETER DESCRIPTION
members

The members, in any order.

TYPE: list[int]

colors

Each member's digest with its references into the component erased.

TYPE: Mapping[int, str]

successors

Each member's references into the component, in occurrence order.

TYPE: Mapping[int, tuple[int, ...]]

serialize

The component's serialization in a given member order.

TYPE: Callable[[list[int]], str]

RETURNS DESCRIPTION
list[int]

The members ordered by their colors refined over the component's references until no class splits. Members the refinement cannot tell apart are individualized in turn, each choice refined again, and the order whose serialization is least is kept. The result is a canonical labeling: it depends only on the component's structure, never on the order the members were given in.

Source code in src/quivers/qiec/content_hash.py
def canonical_order(
    members: list[int],
    colors: Mapping[int, str],
    successors: Mapping[int, tuple[int, ...]],
    serialize: Callable[[list[int]], str],
) -> list[int]:
    """Order the members of a recursive component canonically.

    Parameters
    ----------
    members : list[int]
        The members, in any order.
    colors : Mapping[int, str]
        Each member's digest with its references into the component erased.
    successors : Mapping[int, tuple[int, ...]]
        Each member's references into the component, in occurrence order.
    serialize : Callable[[list[int]], str]
        The component's serialization in a given member order.

    Returns
    -------
    list[int]
        The members ordered by their colors refined over the component's
        references until no class splits. Members the refinement cannot tell
        apart are individualized in turn, each choice refined again, and the
        order whose serialization is least is kept. The result is a canonical
        labeling: it depends only on the component's structure, never on the
        order the members were given in.
    """
    return _individualize(
        members, _refine(dict(colors), successors), successors, serialize
    )

module_hashes

module_hashes(module: QiecModule) -> ModuleHashes

Content identities of every declaration of a checked module.

PARAMETER DESCRIPTION
module

The checked module, as the lowering returns it.

TYPE: QiecModule

RETURNS DESCRIPTION
ModuleHashes

The module digest and one identity per declaration.

RAISES DESCRIPTION
ContentHashError

If the module holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def module_hashes(module: QiecModule) -> ModuleHashes:
    """Content identities of every declaration of a checked module.

    Parameters
    ----------
    module : QiecModule
        The checked module, as the lowering returns it.

    Returns
    -------
    ModuleHashes
        The module digest and one identity per declaration.

    Raises
    ------
    ContentHashError
        If the module holds a value with no core form.
    """
    return ModuleContent(module).hashes

normal_form

normal_form(module: QiecModule, kind: DeclarationKind, name: str) -> str

The canonical serialization a declaration's component is hashed from.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

kind

The declaration's kind.

TYPE: DeclarationKind

name

The declaration's name.

TYPE: str

RETURNS DESCRIPTION
str

The JSON text of the component's core forms in canonical member order, which is what module_hashes digests.

RAISES DESCRIPTION
KeyError

If the module has no such declaration.

ContentHashError

If the module holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def normal_form(module: QiecModule, kind: DeclarationKind, name: str) -> str:
    """The canonical serialization a declaration's component is hashed from.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    kind : DeclarationKind
        The declaration's kind.
    name : str
        The declaration's name.

    Returns
    -------
    str
        The JSON text of the component's core forms in canonical member
        order, which is what `module_hashes` digests.

    Raises
    ------
    KeyError
        If the module has no such declaration.
    ContentHashError
        If the module holds a value with no core form.
    """
    return ModuleContent(module).normal_form(kind, name)

alpha_hash

alpha_hash(term: QiecDatum) -> str

Hash a term modulo alpha-equivalence.

PARAMETER DESCRIPTION
term

A value, computation, or any record of the stable QIEC graph.

TYPE: QiecDatum

RETURNS DESCRIPTION
str

A digest shared by exactly the terms alpha-equivalent to term as open terms: bound locals are compared by binding structure, free locals by name, and everything else by content.

RAISES DESCRIPTION
ContentHashError

If the term holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def alpha_hash(term: QiecDatum) -> str:
    """Hash a term modulo alpha-equivalence.

    Parameters
    ----------
    term : QiecDatum
        A value, computation, or any record of the stable QIEC graph.

    Returns
    -------
    str
        A digest shared by exactly the terms alpha-equivalent to ``term`` as
        open terms: bound locals are compared by binding structure, free
        locals by name, and everything else by content.

    Raises
    ------
    ContentHashError
        If the term holds a value with no core form.
    """
    return _AlphaHasher(None).summary(term, ()).hash()

alpha_hashes

alpha_hashes(term: QiecDatum) -> tuple[SubtermHash, ...]

Hash every record subterm of a term modulo alpha-equivalence.

PARAMETER DESCRIPTION
term

The term.

TYPE: QiecDatum

RETURNS DESCRIPTION
tuple[SubtermHash, ...]

The hash of every record inside term (term included), children before parents, all from one bottom-up pass.

RAISES DESCRIPTION
ContentHashError

If the term holds a value with no core form.

Source code in src/quivers/qiec/content_hash.py
def alpha_hashes(term: QiecDatum) -> tuple[SubtermHash, ...]:
    """Hash every record subterm of a term modulo alpha-equivalence.

    Parameters
    ----------
    term : QiecDatum
        The term.

    Returns
    -------
    tuple[SubtermHash, ...]
        The hash of every record inside ``term`` (``term`` included), children
        before parents, all from one bottom-up pass.

    Raises
    ------
    ContentHashError
        If the term holds a value with no core form.
    """
    found: list[SubtermHash] = []
    _AlphaHasher(
        lambda path, digest: found.append(SubtermHash(path=path, hash=digest))
    ).summary(term, ())
    return tuple(found)