Skip to content

Incremental compilation and caching

quivers.incremental keeps a project's caches in one persistent directory and runs compilation and fitting against it: the store holds content-addressed artifacts with a size limit, the query engine memoizes compiler stages with red-green invalidation, the module build checks a module graph incrementally, the fit cache reuses fits and runs, source identity hashes source text, and the migration gate checks that migrations preserve core hashes. The semantics is stated in Content identity.

incremental

Incremental compilation, persistent caches, and fit caching.

Three layers share one project cache directory:

  • ArtifactStore: a persistent, size-limited, content-addressed store, .qvr/cache at the project root;
  • QueryEngine: memoized compiler queries with red-green invalidation and early cutoff, optionally persisted in the store;
  • FitCache: fits and runs keyed by content hashes, so a refactor that leaves the checked core unchanged reuses an earlier fit.

Every key that depends on the engine includes engine_identity.

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.

CACHE_DIRECTORY_VARIABLE module-attribute

CACHE_DIRECTORY_VARIABLE = 'QVR_CACHE_DIR'

The environment variable that overrides the cache directory.

DEFAULT_MAX_BYTES module-attribute

DEFAULT_MAX_BYTES = 2 * 1024 ** 3

The byte limit of a store that has not been given one: 2 GiB.

CACHE_FORMAT module-attribute

CACHE_FORMAT = 'v1'

The layout version of the store directory; a store of another layout is a sibling directory, never read.

PROJECT_MARKERS module-attribute

PROJECT_MARKERS = ('qvr.toml', '.qvr', '.git')

The entries whose presence marks a directory as a project root, in the order a search checks them in each directory.

ExternalValue

ExternalValue = None | bool | int | float | str | Tensor | Model | ArrayLike | Sequence[ExternalValue] | Mapping[str, ExternalValue]

A value supplied to a fit or run from outside the program: a datum, a site value, a static argument, or a configuration record.

FitKind

FitKind = Literal['fit', 'run']

What a key addresses: a Model.fit result or an invoke_entry run.

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.

QueryAction

QueryAction = Literal['input', 'execute', 'cutoff', 'green', 'load']

What the engine did for one query key:

  • input: an input took a value with a new fingerprint;
  • execute: a query ran and its result changed (or was new);
  • cutoff: a query ran and its result kept its fingerprint, so it was backdated and its dependents stay valid;
  • green: a query was verified without running;
  • load: a query's result was reused from the persistent store after its recorded dependencies were verified, without running.

ArrayLike

Bases: Protocol

A value that exposes an array view, such as a NumPy array.

__array__

__array__() -> ArrayLike

The value as an array.

RETURNS DESCRIPTION
ArrayLike

The array view.

Source code in src/quivers/modeling/model.py
def __array__(self) -> ArrayLike:
    """The value as an array.

    Returns
    -------
    ArrayLike
        The array view.
    """
    ...

CachedRun didactic-model

CachedRun(*, key: str, hit: bool, payload: JsonValue = field(opaque=True, extras=OPAQUE_BY_IDENTITY))

Bases: ValueModel

A run's result, as qvr run --json prints it.

PARAMETER DESCRIPTION
key

The digest of the run's key.

TYPE: str

hit

Whether the payload came from the store.

TYPE: bool

payload

The run's mutable JSON data, compared by identity.

TYPE: JsonValue DEFAULT: field(opaque=True, extras=OPAQUE_BY_IDENTITY)

FitCache

FitCache(store: ArtifactStore, *, engine: str | None = None, factories: Mapping[str, ArtifactFactory] | None = None)

A content-addressed cache of fits and runs in an artifact store.

PARAMETER DESCRIPTION
store

Where artifacts persist.

TYPE: ArtifactStore

engine

The engine identity digest; engine_identity when None. Results are reused only by the same engine.

TYPE: str or None DEFAULT: None

factories

Explicit contracts for configuration values the fitted artifact format does not know, passed to save_fit and load_fit.

TYPE: Mapping[str, ArtifactFactory] or None DEFAULT: None

Source code in src/quivers/incremental/fits.py
def __init__(
    self,
    store: ArtifactStore,
    *,
    engine: str | None = None,
    factories: Mapping[str, ArtifactFactory] | None = None,
) -> None:
    self.store = store
    self.engine = engine_identity() if engine is None else engine
    self.factories = dict(factories or {})
    self.log: list[FitCacheEvent] = []

for_project classmethod

for_project(start: Path | None = None) -> FitCache

The cache of the project a path belongs to.

PARAMETER DESCRIPTION
start

A path inside the project; the working directory when None.

TYPE: Path or None DEFAULT: None

RETURNS DESCRIPTION
FitCache

A cache in the project's artifact store.

RAISES DESCRIPTION
StoreError

If no project root is found.

Source code in src/quivers/incremental/fits.py
@classmethod
def for_project(cls, start: Path | None = None) -> FitCache:
    """The cache of the project a path belongs to.

    Parameters
    ----------
    start : Path or None
        A path inside the project; the working directory when None.

    Returns
    -------
    FitCache
        A cache in the project's artifact store.

    Raises
    ------
    StoreError
        If no project root is found.
    """
    return cls(ArtifactStore.for_project(start))

fit_key

fit_key(model: Model, data: Mapping[str, ExternalValue], *, method: InferenceMethod[ModelFit], parameters: Mapping[str, ExternalValue] | None = None, input: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int = 1, snapshot_policy: SnapshotPolicy = 'clone') -> FitKey

The key of a Model.fit call.

PARAMETER DESCRIPTION
model

The checked model.

TYPE: Model

data

The external data.

TYPE: Mapping[str, ExternalValue]

method

The inference method.

TYPE: InferenceMethod[ModelFit]

parameters

Static specialization arguments.

TYPE: Mapping[str, ExternalValue] or None DEFAULT: None

input

The domain input.

TYPE: Tensor or None DEFAULT: None

seed

The compilation seed.

TYPE: int DEFAULT: 0

sample_prior

The prior-sampling mode.

TYPE: PriorMode DEFAULT: 'no'

num_prior_samples

The prior draw budget.

TYPE: int DEFAULT: 100

prior_seed

The prior stream's seed.

TYPE: int DEFAULT: 1

snapshot_policy

The refit-data ownership.

TYPE: SnapshotPolicy DEFAULT: 'clone'

RETURNS DESCRIPTION
FitKey

The key.

RAISES DESCRIPTION
FitCacheError

If the model uses a custom family catalog, a datum or the method has no portable contract, the method declares no seed, or a datum names no parameter of the entry.

ValueError

If labeled data does not match the axes of its parameter's type.

Source code in src/quivers/incremental/fits.py
def fit_key(
    self,
    model: Model,
    data: Mapping[str, ExternalValue],
    *,
    method: InferenceMethod[ModelFit],
    parameters: Mapping[str, ExternalValue] | None = None,
    input: torch.Tensor | None = None,
    seed: int = 0,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int = 1,
    snapshot_policy: SnapshotPolicy = "clone",
) -> FitKey:
    """The key of a `Model.fit` call.

    Parameters
    ----------
    model : Model
        The checked model.
    data : Mapping[str, ExternalValue]
        The external data.
    method : InferenceMethod[ModelFit]
        The inference method.
    parameters : Mapping[str, ExternalValue] or None
        Static specialization arguments.
    input : torch.Tensor or None
        The domain input.
    seed : int
        The compilation seed.
    sample_prior : PriorMode
        The prior-sampling mode.
    num_prior_samples : int
        The prior draw budget.
    prior_seed : int
        The prior stream's seed.
    snapshot_policy : SnapshotPolicy
        The refit-data ownership.

    Returns
    -------
    FitKey
        The key.

    Raises
    ------
    FitCacheError
        If the model uses a custom family catalog, a datum or the method
        has no portable contract, the method declares no seed, or a datum
        names no parameter of the entry.
    ValueError
        If labeled data does not match the axes of its parameter's type.
    """
    if model.families is not None and len(model.families.definitions) > 0:
        raise FitCacheError(
            "a model with native family implementations has no content "
            "identity: their Python code is not hashed"
        )
    content = ModuleContent(model.checked_module)
    entry = content.hashes.declaration("entry", model.entry)
    companions = content.value_hash(
        "companions",
        (
            model.schema.scoped_interpretations,
            model.schema.closed_interpretations,
            model.schema.packed_interpretations,
        ),
    )
    positions = {
        parameter.name: index
        for index, parameter in enumerate(model.schema.entry.parameters)
    }
    unknown = sorted(set(data) - set(positions))
    if unknown:
        raise FitCacheError(f"data name no parameter of the entry: {unknown}")
    # Labeled data keys the fit by its entries in canonical order.
    data = cast(Mapping[str, ExternalValue], model.aligned_data(data))
    codec = _Codec(self.factories)
    try:
        encoded_method = cast(JsonValue, codec.encode(method))
    except TypeError as error:
        raise FitCacheError(
            f"the inference method has no content identity: {error}"
        ) from error
    if _unseeded(encoded_method):
        raise FitCacheError(
            "the inference method declares no seed, so every run draws "
            "fresh randomness and no stored fit reproduces it"
        )
    configuration = tagged_digest(
        "fit-configuration",
        [
            _encoded_digest(codec, encoded_method),
            value_digest(dict(parameters or {}), self.factories),
            value_digest(input, self.factories),
            sample_prior,
            num_prior_samples,
            snapshot_policy,
        ],
    )
    return FitKey(
        kind="fit",
        entry=entry.hash,
        companions=companions,
        source=program_source_digest(model.source),
        names=entry.names,
        data=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(
                (positions[name], value_digest(value, self.factories))
                for name, value in data.items()
            )
        ),
        fixed_sites=(),
        configuration=configuration,
        seeds=(seed, prior_seed),
        engine=self.engine,
    )

fit

fit(model: Model, data: Mapping[str, ExternalValue], *, method: InferenceMethod[ModelFit], parameters: Mapping[str, ExternalValue] | None = None, input: Tensor | None = None, seed: int = 0, sample_prior: PriorMode = 'no', num_prior_samples: int = 100, prior_seed: int = 1, snapshot_policy: SnapshotPolicy = 'clone') -> ModelFit

Fit a model, reusing a stored fit with the same key.

PARAMETER DESCRIPTION
model

The checked model.

TYPE: Model

data

The external data.

TYPE: Mapping[str, ExternalValue]

method

The inference method.

TYPE: InferenceMethod[ModelFit]

parameters

Static specialization arguments.

TYPE: Mapping[str, ExternalValue] or None DEFAULT: None

input

The domain input.

TYPE: Tensor or None DEFAULT: None

seed

The compilation seed.

TYPE: int DEFAULT: 0

sample_prior

The prior-sampling mode.

TYPE: PriorMode DEFAULT: 'no'

num_prior_samples

The prior draw budget.

TYPE: int DEFAULT: 100

prior_seed

The prior stream's seed.

TYPE: int DEFAULT: 1

snapshot_policy

The refit-data ownership.

TYPE: SnapshotPolicy DEFAULT: 'clone'

RETURNS DESCRIPTION
ModelFit

On a hit, the stored fit reloaded exactly as save_fit wrote it, bound to the source it was fitted from. On a miss, the new fit, after storing it.

RAISES DESCRIPTION
FitCacheError

If the fit has no content identity, or the method does not return a ModelFit.

StoreError

If the stored artifact is corrupt.

Source code in src/quivers/incremental/fits.py
def fit(
    self,
    model: Model,
    data: Mapping[str, ExternalValue],
    *,
    method: InferenceMethod[ModelFit],
    parameters: Mapping[str, ExternalValue] | None = None,
    input: torch.Tensor | None = None,
    seed: int = 0,
    sample_prior: PriorMode = "no",
    num_prior_samples: int = 100,
    prior_seed: int = 1,
    snapshot_policy: SnapshotPolicy = "clone",
) -> ModelFit:
    """Fit a model, reusing a stored fit with the same key.

    Parameters
    ----------
    model : Model
        The checked model.
    data : Mapping[str, ExternalValue]
        The external data.
    method : InferenceMethod[ModelFit]
        The inference method.
    parameters : Mapping[str, ExternalValue] or None
        Static specialization arguments.
    input : torch.Tensor or None
        The domain input.
    seed : int
        The compilation seed.
    sample_prior : PriorMode
        The prior-sampling mode.
    num_prior_samples : int
        The prior draw budget.
    prior_seed : int
        The prior stream's seed.
    snapshot_policy : SnapshotPolicy
        The refit-data ownership.

    Returns
    -------
    ModelFit
        On a hit, the stored fit reloaded exactly as `save_fit` wrote it,
        bound to the source it was fitted from. On a miss, the new fit,
        after storing it.

    Raises
    ------
    FitCacheError
        If the fit has no content identity, or the method does not return
        a `ModelFit`.
    StoreError
        If the stored artifact is corrupt.
    """
    key = self.fit_key(
        model,
        data,
        method=method,
        parameters=parameters,
        input=input,
        seed=seed,
        sample_prior=sample_prior,
        num_prior_samples=num_prior_samples,
        prior_seed=prior_seed,
        snapshot_policy=snapshot_policy,
    ).digest()
    stored = self.store.get("fit", key)
    if stored is not None:
        self.log.append(FitCacheEvent(kind="fit", key=key, hit=True))
        path = self.store.payload_path("fit", key)
        if path is None:
            raise FitCacheError(f"stored fit {key} disappeared while being read")
        loaded = load_fit(path, factories=self.factories)
        if not isinstance(loaded, ModelFit):
            raise FitCacheError(f"stored fit {key} is not a source fit")
        return loaded
    result = model.bind(data, parameters=parameters, input=input, seed=seed).infer(
        method,
        sample_prior=sample_prior,
        num_prior_samples=num_prior_samples,
        prior_seed=prior_seed,
        snapshot_policy=snapshot_policy,
    )
    if not isinstance(result, ModelFit):
        raise FitCacheError(
            "fit caching stores fitted artifacts; the method returned "
            f"{type(result).__name__}, not ModelFit"
        )
    staging = self.store.staging_path("fit")
    try:
        save_fit(result, staging, factories=self.factories)
        self.store.put("fit", key, staging.read_bytes(), label=f"fit {model.entry}")
    finally:
        staging.unlink(missing_ok=True)
    self.log.append(FitCacheEvent(kind="fit", key=key, hit=False))
    return result

run_key

run_key(module: QiecModule, name: str, arguments: Sequence[HostValue] = (), *, data: Mapping[str, HostValue] | None = None, sites: Mapping[str, HostValue] | None = None, static_arguments: Sequence[str] = (), runtime: RuntimeConfiguration | None = None, fuel: int | None = None, seed: int | None = None, numbers: NumberDomain | None = None) -> FitKey

The key of an invoke_entry run.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

name

The entry's name: a program or a computation.

TYPE: str

arguments

Positional value arguments.

TYPE: Sequence[HostValue] DEFAULT: ()

data

A program's parameters by name.

TYPE: Mapping[str, HostValue] or None DEFAULT: None

sites

Conditioned sites by label.

TYPE: Mapping[str, HostValue] or None DEFAULT: None

static_arguments

NAME=TERM static arguments.

TYPE: Sequence[str] DEFAULT: ()

runtime

The runtime providers.

TYPE: RuntimeConfiguration or None DEFAULT: None

fuel

The step budget.

TYPE: int or None DEFAULT: None

seed

The reference generator's seed.

TYPE: int or None DEFAULT: None

numbers

The number domain the reference machine computes in; the default floating domain when None.

TYPE: NumberDomain or None DEFAULT: None

RETURNS DESCRIPTION
FitKey

The key.

RAISES DESCRIPTION
FitCacheError

If the run has no seed, uses programmatic providers, names a datum or site the entry does not have, or passes a value with no portable contract.

KeyError

If the module has no entry or computation of that name.

ExecutionFailure

With code qiec-run-data if labeled data does not match the axes of its parameter's type.

Source code in src/quivers/incremental/fits.py
def run_key(
    self,
    module: QiecModule,
    name: str,
    arguments: Sequence[HostValue] = (),
    *,
    data: Mapping[str, HostValue] | None = None,
    sites: Mapping[str, HostValue] | None = None,
    static_arguments: Sequence[str] = (),
    runtime: RuntimeConfiguration | None = None,
    fuel: int | None = None,
    seed: int | None = None,
    numbers: NumberDomain | None = None,
) -> FitKey:
    """The key of an `invoke_entry` run.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    name : str
        The entry's name: a program or a computation.
    arguments : Sequence[HostValue]
        Positional value arguments.
    data : Mapping[str, HostValue] or None
        A program's parameters by name.
    sites : Mapping[str, HostValue] or None
        Conditioned sites by label.
    static_arguments : Sequence[str]
        ``NAME=TERM`` static arguments.
    runtime : RuntimeConfiguration or None
        The runtime providers.
    fuel : int or None
        The step budget.
    seed : int or None
        The reference generator's seed.
    numbers : NumberDomain or None
        The number domain the reference machine computes in; the
        default floating domain when None.

    Returns
    -------
    FitKey
        The key.

    Raises
    ------
    FitCacheError
        If the run has no seed, uses programmatic providers, names a datum
        or site the entry does not have, or passes a value with no
        portable contract.
    KeyError
        If the module has no entry or computation of that name.
    ExecutionFailure
        With code ``qiec-run-data`` if labeled data does not match the
        axes of its parameter's type.
    """
    if seed is None:
        raise FitCacheError(
            "a run without a seed continues the generator's state, so no "
            "stored run reproduces it; pass a seed to cache it"
        )
    configuration = runtime or RuntimeConfiguration()
    if configuration.providers:
        raise FitCacheError(
            "programmatic runtime providers have no content identity; "
            "select providers by name to cache a run"
        )
    content = ModuleContent(module)
    program = next((entry for entry in module.entries if entry.name == name), None)
    # Labeled data keys the run by its entries in the canonical order its
    # type fixes, so the order its rows were given in never changes the key.
    if program is None:
        arguments = aligned_arguments(module, name, arguments)
    elif data:
        data = aligned_data(module, name, data)
    declaration = content.hashes.declaration(
        "entry" if program is not None else "computation", name
    )
    positions: dict[str, int] = (
        {}
        if program is None
        else {
            parameter.name: index
            for index, parameter in enumerate(program.parameters)
        }
    )
    supplied: list[tuple[int, str]] = [
        (index, value_digest(value)) for index, value in enumerate(arguments)
    ]
    for datum, value in (data or {}).items():
        if datum not in positions:
            raise FitCacheError(f"{name!r} has no parameter {datum!r}")
        supplied.append((positions[datum], value_digest(value)))
    fixed: list[tuple[int, str]] = []
    for label, value in (sites or {}).items():
        if label not in declaration.names:
            raise FitCacheError(f"{name!r} has no site {label!r}")
        fixed.append((declaration.names.index(label), value_digest(value)))
    return FitKey(
        kind="run",
        entry=declaration.hash,
        companions="",
        source="",
        names=declaration.names,
        data=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(supplied)
        ),
        fixed_sites=tuple(
            KeyedDigest(position=position, digest=digest)
            for position, digest in sorted(fixed)
        ),
        configuration=tagged_digest(
            "run-configuration",
            cast(
                CoreJson,
                [
                    json.loads(json.dumps(configuration.to_data(), sort_keys=True)),
                    sorted(static_arguments),
                    fuel,
                    json.loads((numbers or NumberDomain()).model_dump_json()),
                ],
            ),
        ),
        seeds=(seed,),
        engine=self.engine,
    )

run

run(module: QiecModule, name: str, arguments: Sequence[HostValue] = (), *, data: Mapping[str, HostValue] | None = None, sites: Mapping[str, HostValue] | None = None, static_arguments: Sequence[str] = (), runtime: RuntimeConfiguration | None = None, fuel: int | None = None, seed: int | None = None, numbers: NumberDomain | None = None) -> CachedRun

Invoke an entry, reusing a stored run with the same key.

PARAMETER DESCRIPTION
module

The checked module.

TYPE: QiecModule

name

The entry's name.

TYPE: str

arguments

Positional value arguments.

TYPE: Sequence[HostValue] DEFAULT: ()

data

A program's parameters by name.

TYPE: Mapping[str, HostValue] or None DEFAULT: None

sites

Conditioned sites by label.

TYPE: Mapping[str, HostValue] or None DEFAULT: None

static_arguments

NAME=TERM static arguments.

TYPE: Sequence[str] DEFAULT: ()

runtime

The runtime providers.

TYPE: RuntimeConfiguration or None DEFAULT: None

fuel

The step budget.

TYPE: int or None DEFAULT: None

seed

The reference generator's seed; required.

TYPE: int or None DEFAULT: None

numbers

The number domain the reference machine computes in; the default floating domain when None.

TYPE: NumberDomain or None DEFAULT: None

RETURNS DESCRIPTION
CachedRun

The run's JSON payload, from the store on a hit.

RAISES DESCRIPTION
FitCacheError

If the run has no content identity.

ExecutionFailure

If the run fails.

StoreError

If the stored payload is corrupt.

Source code in src/quivers/incremental/fits.py
def run(
    self,
    module: QiecModule,
    name: str,
    arguments: Sequence[HostValue] = (),
    *,
    data: Mapping[str, HostValue] | None = None,
    sites: Mapping[str, HostValue] | None = None,
    static_arguments: Sequence[str] = (),
    runtime: RuntimeConfiguration | None = None,
    fuel: int | None = None,
    seed: int | None = None,
    numbers: NumberDomain | None = None,
) -> CachedRun:
    """Invoke an entry, reusing a stored run with the same key.

    Parameters
    ----------
    module : QiecModule
        The checked module.
    name : str
        The entry's name.
    arguments : Sequence[HostValue]
        Positional value arguments.
    data : Mapping[str, HostValue] or None
        A program's parameters by name.
    sites : Mapping[str, HostValue] or None
        Conditioned sites by label.
    static_arguments : Sequence[str]
        ``NAME=TERM`` static arguments.
    runtime : RuntimeConfiguration or None
        The runtime providers.
    fuel : int or None
        The step budget.
    seed : int or None
        The reference generator's seed; required.
    numbers : NumberDomain or None
        The number domain the reference machine computes in; the
        default floating domain when None.

    Returns
    -------
    CachedRun
        The run's JSON payload, from the store on a hit.

    Raises
    ------
    FitCacheError
        If the run has no content identity.
    ExecutionFailure
        If the run fails.
    StoreError
        If the stored payload is corrupt.
    """
    key = self.run_key(
        module,
        name,
        arguments,
        data=data,
        sites=sites,
        static_arguments=static_arguments,
        runtime=runtime,
        fuel=fuel,
        seed=seed,
        numbers=numbers,
    ).digest()
    stored = self.store.get("run", key)
    if stored is not None:
        self.log.append(FitCacheEvent(kind="run", key=key, hit=True))
        return CachedRun(key=key, hit=True, payload=json.loads(stored))
    result = invoke_entry(
        module,
        name,
        arguments,
        data=data,
        sites=sites,
        static_arguments=static_arguments,
        runtime=runtime,
        fuel=fuel,
        seed=seed,
        numbers=numbers,
    )
    text = json.dumps(result.to_data(), sort_keys=True)
    self.store.put("run", key, text.encode(), label=f"run {name}")
    self.log.append(FitCacheEvent(kind="run", key=key, hit=False))
    return CachedRun(key=key, hit=False, payload=json.loads(text))

FitCacheError

Bases: ValueError

A fit or run has no content identity, so it cannot be cached.

FitCacheEvent didactic-model

FitCacheEvent(*, kind: FitKind, key: str, hit: bool)

Bases: Model

One lookup of a cache.

PARAMETER DESCRIPTION
kind

A fit or a run.

TYPE: FitKind

key

The key's digest.

TYPE: str

hit

Whether the stored artifact was returned.

TYPE: bool

FitKey didactic-model

FitKey(*, kind: FitKind, entry: str, companions: str, source: str, names: tuple[str, ...], data: tuple[KeyedDigest, ...], fixed_sites: tuple[KeyedDigest, ...], configuration: str, seeds: tuple[int, ...], engine: str)

Bases: Model

Everything that determines a fit or run, as digests.

PARAMETER DESCRIPTION
kind

A fit or a run.

TYPE: FitKind

entry

The content hash of the entry point.

TYPE: str

companions

The digest of the checked interpretation bindings the entry runs with, in the module's content context.

TYPE: str

source

For a fit, the digest of the program source's modules (program_source_digest), which covers what the checked core does not record; empty for a run, which the reference machine executes from the checked core alone.

TYPE: str

names

The entry's observable names, in ordinal order.

TYPE: tuple[str, ...]

data

Each supplied parameter's position with the digest of its value.

TYPE: tuple[KeyedDigest, ...]

fixed_sites

Each conditioned site's ordinal among names with the digest of its value.

TYPE: tuple[KeyedDigest, ...]

configuration

The digest of the inference method and the options of the fit or run.

TYPE: str

seeds

The seeds.

TYPE: tuple[int, ...]

engine

The digest of the engine identity.

TYPE: str

digest

digest() -> str

The store key of the fit or run.

RETURNS DESCRIPTION
str

The digest of every component.

Source code in src/quivers/incremental/fits.py
def digest(self) -> str:
    """The store key of the fit or run.

    Returns
    -------
    str
        The digest of every component.
    """
    return tagged_digest(
        "fit-key",
        [
            self.kind,
            self.entry,
            self.companions,
            self.source,
            list(self.names),
            [[item.position, item.digest] for item in self.data],
            [[item.position, item.digest] for item in self.fixed_sites],
            self.configuration,
            list(self.seeds),
            self.engine,
        ],
    )

KeyedDigest didactic-model

KeyedDigest(*, position: int, digest: str)

Bases: Model

The digest of one value at one position of a key.

PARAMETER DESCRIPTION
position

A parameter position or a site ordinal.

TYPE: int

digest

The value's digest.

TYPE: str

IdentityError

Bases: ValueError

A source cannot be identified: it does not parse or does not check.

ProgramIdentity didactic-model

ProgramIdentity(*, core: ModuleHashes, statements: tuple[StatementHash, ...], source: SourceHash, digest: str)

Bases: Model

Every identity of one checked source.

PARAMETER DESCRIPTION
core

The core hashes of its checked declarations.

TYPE: ModuleHashes

statements

The source hash of each top-level statement, in source order.

TYPE: tuple[StatementHash, ...]

source

The hash of the exact bytes.

TYPE: SourceHash

digest

The digest of the core module digest and the multiset of statement hashes under the grammar commit: what a fit of this program is keyed by.

TYPE: str

SourceHash didactic-model

SourceHash(*, grammar: str, digest: str)

Bases: Model

The hash of a source's exact bytes.

PARAMETER DESCRIPTION
grammar

The panproto schema commit of the grammar the source is written in.

TYPE: str

digest

The BLAKE3 digest of the bytes.

TYPE: str

StatementHash didactic-model

StatementHash(*, kind: str, names: tuple[str, ...], hash: str)

Bases: Model

The alpha-normalized source hash of one top-level statement.

PARAMETER DESCRIPTION
kind

The statement's grammar kind (program_decl, object_decl, ...).

TYPE: str

names

The names it declares, in order (metadata).

TYPE: tuple[str, ...]

hash

Its source hash: the component hash when no other statement refers back to it, else <component>.<member>.

TYPE: str

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)

ImportEdges didactic-model

ImportEdges(*, imports: tuple[ResolvedImport, ...] = ())

Bases: Model

The resolved imports of one module.

PARAMETER DESCRIPTION
imports

Each import with the module it names.

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

ModuleBuild

ModuleBuild(loader: ModuleLoader, *, store: ArtifactStore | None = None)

Incremental compilation of the module graphs a loader provides.

PARAMETER DESCRIPTION
loader

Finds a module's source by its path.

TYPE: ModuleLoader

store

Where elaborations persist across processes, or None to keep them in memory.

TYPE: ArtifactStore or None DEFAULT: None

Source code in src/quivers/incremental/pipeline.py
def __init__(
    self, loader: ModuleLoader, *, store: ArtifactStore | None = None
) -> None:
    self.loader = loader
    self.engine = QueryEngine(store=store, namespace="qvr-modules")
    engine = self.engine
    self.sources: Input[ModuleSource] = engine.input("source", _json_fingerprint)
    self.parse: Query[_Tree] = engine.query(
        "parse",
        self._parse,
        lambda tree: content_digest(tree.source),
    )
    self.declared: Query[FileNames] = engine.query(
        "declared", self._declared, _json_fingerprint
    )
    self.imports: Query[ImportEdges] = engine.query(
        "imports", self._imports, _json_fingerprint
    )
    self.names: Query[FileNames] = engine.query(
        "names", self._names, _json_fingerprint
    )
    self.check: Query[CheckedModule] = engine.query(
        "check", self._check, _json_fingerprint
    )
    self.interface: Query[ModuleInterface] = engine.query(
        "interface",
        lambda key: self.check.get(key).interface,
        lambda interface: content_digest(interface.to_artifact()),
    )
    self.private: Query[tuple[str, ...]] = engine.query(
        "private", self._private, _tuple_fingerprint
    )
    self.order: Query[tuple[str, ...]] = engine.query(
        "order", self._order, _tuple_fingerprint
    )
    self.program: Query[FlatProgram] = engine.query(
        "program",
        self._program,
        lambda flat: content_digest(flat.module.model_dump_json().encode("utf-8")),
    )
    self.elaborate: Query[QiecModule] = engine.query(
        "elaborate",
        self._elaborate,
        lambda module: content_digest(dumps(module).encode("utf-8")),
        codec=QueryCodec(
            lambda module: dumps(module).encode("utf-8"),
            _decode_module,
            "qiec-json",
        ),
    )
    self.hashes: Query[ModuleHashes] = engine.query(
        "hashes",
        lambda key: module_hashes(self.elaborate.get(key)),
        _json_fingerprint,
    )
    self.specialize: Query[Specialization] = engine.query(
        "specialize",
        self._specialize,
        lambda item: content_digest(
            dumps((item.computation, item.arguments, item.type)).encode("utf-8")
        ),
    )

load

load(module: str) -> None

Set the source of a module and of everything it imports.

PARAMETER DESCRIPTION
module

The module's dotted path.

TYPE: str

RAISES DESCRIPTION
ModuleError

If a module is not found or is provided by two roots.

Source code in src/quivers/incremental/pipeline.py
def load(self, module: str) -> None:
    """Set the source of a module and of everything it imports.

    Parameters
    ----------
    module : str
        The module's dotted path.

    Raises
    ------
    ModuleError
        If a module is not found or is provided by two roots.
    """
    pending = [module]
    while pending:
        key = pending.pop()
        if key not in self.sources.keys():
            self.sources.set(key, self._find(key, None))
        for edge in self.imports.get(key).imports:
            target = module_display(edge.module)
            if target not in self.sources.keys():
                pending.append(target)

reload

reload(module: str) -> bool

Read a module's source again, as after an edit.

PARAMETER DESCRIPTION
module

The module's dotted path.

TYPE: str

RETURNS DESCRIPTION
bool

Whether its source changed.

RAISES DESCRIPTION
ModuleError

If the module is no longer found.

Source code in src/quivers/incremental/pipeline.py
def reload(self, module: str) -> bool:
    """Read a module's source again, as after an edit.

    Parameters
    ----------
    module : str
        The module's dotted path.

    Returns
    -------
    bool
        Whether its source changed.

    Raises
    ------
    ModuleError
        If the module is no longer found.
    """
    changed = self.sources.set(module, self._find(module, None))
    self.load(module)
    return changed

executed

executed(query: str, *, since: int = 0) -> tuple[str, ...]

The keys a query ran for, in order.

PARAMETER DESCRIPTION
query

The query name.

TYPE: str

since

Skip the first since log entries.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
tuple[str, ...]

The keys of its execute and cutoff steps: every time its function actually ran.

Source code in src/quivers/incremental/pipeline.py
def executed(self, query: str, *, since: int = 0) -> tuple[str, ...]:
    """The keys a query ran for, in order.

    Parameters
    ----------
    query : str
        The query name.
    since : int
        Skip the first ``since`` log entries.

    Returns
    -------
    tuple[str, ...]
        The keys of its ``execute`` and ``cutoff`` steps: every time its
        function actually ran.
    """
    return tuple(
        event.key
        for event in self.engine.events(since=since)
        if event.query == query and event.action in {"execute", "cutoff"}
    )

Specialization didactic-model

Specialization(*, computation: str, arguments: tuple[StaticArgument, ...] = field(opaque=True, extras=OPAQUE_BY_VALUE), type: ComputationType = field(opaque=True, extras=OPAQUE_BY_VALUE))

Bases: ValueModel

A computation instantiated at closed static arguments.

PARAMETER DESCRIPTION
computation

The computation's name.

TYPE: str

arguments

The checked static arguments, in telescope order.

TYPE: tuple[StaticArgument, ...] DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

type

The computation's type with its telescope instantiated.

TYPE: ComputationType DEFAULT: field(opaque=True, extras=OPAQUE_BY_VALUE)

Input

Input(engine: QueryEngine, name: str, fingerprint: Callable[[V], str])

Bases: QueryTable

A table of values set from outside the engine.

PARAMETER DESCRIPTION
engine

The owning engine.

TYPE: QueryEngine

name

The input's name.

TYPE: str

fingerprint

The digest of a value; a value with the old digest is no change.

TYPE: Callable[[V], str]

Source code in src/quivers/incremental/queries.py
def __init__(
    self, engine: QueryEngine, name: str, fingerprint: Callable[[V], str]
) -> None:
    super().__init__(engine, name)
    self._fingerprint = fingerprint
    self._memos: dict[str, _Memo[V]] = {}

set

set(key: str, value: V) -> bool

Set one key's value.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

value

The new value.

TYPE: V

RETURNS DESCRIPTION
bool

Whether the value changed: a value with the old fingerprint starts no new revision and invalidates nothing.

Source code in src/quivers/incremental/queries.py
def set(self, key: str, value: V) -> bool:
    """Set one key's value.

    Parameters
    ----------
    key : str
        The key.
    value : V
        The new value.

    Returns
    -------
    bool
        Whether the value changed: a value with the old fingerprint
        starts no new revision and invalidates nothing.
    """
    fingerprint = self._fingerprint(value)
    memo = self._memos.get(key)
    if memo is not None and memo.fingerprint == fingerprint:
        memo.value = value
        return False
    revision = self.engine.advance()
    self._memos[key] = _Memo(value, fingerprint, revision, revision, ())
    self.engine.record("input", self.name, key)
    return True

keys

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

Every key that has a value.

RETURNS DESCRIPTION
tuple[str, ...]

The keys, sorted.

Source code in src/quivers/incremental/queries.py
def keys(self) -> tuple[str, ...]:
    """Every key that has a value.

    Returns
    -------
    tuple[str, ...]
        The keys, sorted.
    """
    return tuple(sorted(self._memos))

get

get(key: str) -> V

Read one key, recording the read as a dependency.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
V

The value.

RAISES DESCRIPTION
QueryError

If the key has never been set.

Source code in src/quivers/incremental/queries.py
def get(self, key: str) -> V:
    """Read one key, recording the read as a dependency.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    V
        The value.

    Raises
    ------
    QueryError
        If the key has never been set.
    """
    self.engine.read(self, key)
    return self._memo(key).value

refresh

refresh(key: str) -> tuple[int, str]

An input is always current.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
tuple[int, str]

The revision the value was set at and its fingerprint.

RAISES DESCRIPTION
QueryError

If the key has never been set.

Source code in src/quivers/incremental/queries.py
def refresh(self, key: str) -> tuple[int, str]:
    """An input is always current.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    tuple[int, str]
        The revision the value was set at and its fingerprint.

    Raises
    ------
    QueryError
        If the key has never been set.
    """
    memo = self._memo(key)
    return memo.changed_at, memo.fingerprint

Query

Query(engine: QueryEngine, name: str, compute: Callable[[str], V], fingerprint: Callable[[V], str], codec: QueryCodec[V] | None)

Bases: QueryTable

A memoized function of a key.

PARAMETER DESCRIPTION
engine

The owning engine.

TYPE: QueryEngine

name

The query's name.

TYPE: str

compute

The function. It reads inputs and queries through their get methods, which records them as its dependencies.

TYPE: Callable[[str], V]

fingerprint

The digest of a result. Two results with one fingerprint are interchangeable for every reader, so the fingerprint must cover everything a reader of the result can observe.

TYPE: Callable[[V], str]

codec

How results persist in the engine's store, or None to keep them in memory only.

TYPE: QueryCodec[V] or None

Source code in src/quivers/incremental/queries.py
def __init__(
    self,
    engine: QueryEngine,
    name: str,
    compute: Callable[[str], V],
    fingerprint: Callable[[V], str],
    codec: QueryCodec[V] | None,
) -> None:
    super().__init__(engine, name)
    self._compute = compute
    self._fingerprint = fingerprint
    self._codec = codec
    self._memos: dict[str, _Memo[V]] = {}

get

get(key: str) -> V

Answer the query, recording the read as a dependency.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
V

The current result.

RAISES DESCRIPTION
QueryError

If answering it needs its own answer, or reads an unset input.

Source code in src/quivers/incremental/queries.py
def get(self, key: str) -> V:
    """Answer the query, recording the read as a dependency.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    V
        The current result.

    Raises
    ------
    QueryError
        If answering it needs its own answer, or reads an unset input.
    """
    self.engine.read(self, key)
    return self._ensure(key).value

fingerprint

fingerprint(key: str) -> str

The fingerprint of the current result.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
str

The digest, computing the result if needed (without recording a dependency).

Source code in src/quivers/incremental/queries.py
def fingerprint(self, key: str) -> str:
    """The fingerprint of the current result.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    str
        The digest, computing the result if needed (without recording a
        dependency).
    """
    return self._ensure(key).fingerprint

refresh

refresh(key: str) -> tuple[int, str]

Bring one key up to date.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
tuple[int, str]

The revision its result last changed at and its fingerprint.

Source code in src/quivers/incremental/queries.py
def refresh(self, key: str) -> tuple[int, str]:
    """Bring one key up to date.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    tuple[int, str]
        The revision its result last changed at and its fingerprint.
    """
    memo = self._ensure(key)
    return memo.changed_at, memo.fingerprint

QueryCodec

QueryCodec(encode: Callable[[V], bytes], decode: Callable[[bytes], V], version: str)

How a query's results are written to and read from the store.

PARAMETER DESCRIPTION
encode

Serialize a result.

TYPE: Callable[[V], bytes]

decode

Read a serialized result back.

TYPE: Callable[[bytes], V]

version

The codec's format version. It is part of every stored record's address, so a change of format never reads an old record.

TYPE: str

Source code in src/quivers/incremental/queries.py
def __init__(
    self,
    encode: Callable[[V], bytes],
    decode: Callable[[bytes], V],
    version: str,
) -> None:
    self.encode = encode
    self.decode = decode
    self.version = version

QueryEngine

QueryEngine(*, store: ArtifactStore | None = None, namespace: str = 'qvr')

The tables, revision, active frames, and log of one incremental build.

PARAMETER DESCRIPTION
store

Where queries with a codec persist their results, or None to keep everything in memory.

TYPE: ArtifactStore or None DEFAULT: None

namespace

Separates this engine's persisted records from those of engines built with other query definitions (another engine version, say).

TYPE: str DEFAULT: 'qvr'

Source code in src/quivers/incremental/queries.py
def __init__(
    self, *, store: ArtifactStore | None = None, namespace: str = "qvr"
) -> None:
    self.store = store
    self.namespace = namespace
    self.revision = 0
    self.log: list[QueryEvent] = []
    """Every step the engine has taken, in order: each input set, each
    query run, cut off, or reused, and each result loaded from the
    store, with its key (see `QueryEvent`)."""
    self._tables: dict[str, QueryTable] = {}
    self._frames: list[list[tuple[QueryTable, str]]] = []
    self._active: list[tuple[str, str]] = []

log instance-attribute

log: list[QueryEvent] = []

Every step the engine has taken, in order: each input set, each query run, cut off, or reused, and each result loaded from the store, with its key (see QueryEvent).

input

input(name: str, fingerprint: Callable[[V], str]) -> Input[V]

Declare an input table.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

fingerprint

The digest of a value.

TYPE: Callable[[V], str]

RETURNS DESCRIPTION
Input[V]

The table.

RAISES DESCRIPTION
QueryError

If the name is taken.

Source code in src/quivers/incremental/queries.py
def input[V](self, name: str, fingerprint: Callable[[V], str]) -> Input[V]:
    """Declare an input table.

    Parameters
    ----------
    name : str
        Its name.
    fingerprint : Callable[[V], str]
        The digest of a value.

    Returns
    -------
    Input[V]
        The table.

    Raises
    ------
    QueryError
        If the name is taken.
    """
    table: Input[V] = Input(self, name, fingerprint)
    self._register(table)
    return table

query

query(name: str, compute: Callable[[str], V], fingerprint: Callable[[V], str], *, codec: QueryCodec[V] | None = None) -> Query[V]

Declare a query.

PARAMETER DESCRIPTION
name

Its name.

TYPE: str

compute

The function of a key.

TYPE: Callable[[str], V]

fingerprint

The digest of a result.

TYPE: Callable[[V], str]

codec

How results persist, or None for memory only.

TYPE: QueryCodec[V] or None DEFAULT: None

RETURNS DESCRIPTION
Query[V]

The query.

RAISES DESCRIPTION
QueryError

If the name is taken.

Source code in src/quivers/incremental/queries.py
def query[V](
    self,
    name: str,
    compute: Callable[[str], V],
    fingerprint: Callable[[V], str],
    *,
    codec: QueryCodec[V] | None = None,
) -> Query[V]:
    """Declare a query.

    Parameters
    ----------
    name : str
        Its name.
    compute : Callable[[str], V]
        The function of a key.
    fingerprint : Callable[[V], str]
        The digest of a result.
    codec : QueryCodec[V] or None
        How results persist, or None for memory only.

    Returns
    -------
    Query[V]
        The query.

    Raises
    ------
    QueryError
        If the name is taken.
    """
    table: Query[V] = Query(self, name, compute, fingerprint, codec)
    self._register(table)
    return table

table

table(name: str) -> QueryTable

A table by name.

PARAMETER DESCRIPTION
name

The name.

TYPE: str

RETURNS DESCRIPTION
QueryTable

The table.

RAISES DESCRIPTION
QueryError

If there is no such table, which happens when a persisted record names a query this engine does not define.

Source code in src/quivers/incremental/queries.py
def table(self, name: str) -> QueryTable:
    """A table by name.

    Parameters
    ----------
    name : str
        The name.

    Returns
    -------
    QueryTable
        The table.

    Raises
    ------
    QueryError
        If there is no such table, which happens when a persisted record
        names a query this engine does not define.
    """
    table = self._tables.get(name)
    if table is None:
        raise QueryError(f"no query or input named {name!r}")
    return table

advance

advance() -> int

Start a new revision.

RETURNS DESCRIPTION
int

The new revision.

Source code in src/quivers/incremental/queries.py
def advance(self) -> int:
    """Start a new revision.

    Returns
    -------
    int
        The new revision.
    """
    self.revision += 1
    return self.revision

record

record(action: QueryAction, query: str, key: str) -> None

Append a step to the log.

PARAMETER DESCRIPTION
action

What happened.

TYPE: QueryAction

query

The table.

TYPE: str

key

The key.

TYPE: str

Source code in src/quivers/incremental/queries.py
def record(self, action: QueryAction, query: str, key: str) -> None:
    """Append a step to the log.

    Parameters
    ----------
    action : QueryAction
        What happened.
    query : str
        The table.
    key : str
        The key.
    """
    self.log.append(
        QueryEvent(revision=self.revision, action=action, query=query, key=key)
    )

read

read(table: QueryTable, key: str) -> None

Record a read as a dependency of the running query, if any.

PARAMETER DESCRIPTION
table

The table read.

TYPE: QueryTable

key

The key read.

TYPE: str

Source code in src/quivers/incremental/queries.py
def read(self, table: QueryTable, key: str) -> None:
    """Record a read as a dependency of the running query, if any.

    Parameters
    ----------
    table : QueryTable
        The table read.
    key : str
        The key read.
    """
    if self._frames:
        frame = self._frames[-1]
        if (table, key) not in frame:
            frame.append((table, key))

run

run(table: QueryTable, key: str, compute: Callable[[], V]) -> tuple[V, tuple[tuple[QueryTable, str], ...]]

Run a query body, collecting what it reads.

PARAMETER DESCRIPTION
table

The query.

TYPE: QueryTable

key

Its key.

TYPE: str

compute

The body.

TYPE: Callable[[], V]

RETURNS DESCRIPTION
tuple[V, tuple[tuple[QueryTable, str], ...]]

The result and its dependencies in reading order.

RAISES DESCRIPTION
QueryError

If the query is already running, which is a dependency cycle.

Source code in src/quivers/incremental/queries.py
def run[V](
    self, table: QueryTable, key: str, compute: Callable[[], V]
) -> tuple[V, tuple[tuple[QueryTable, str], ...]]:
    """Run a query body, collecting what it reads.

    Parameters
    ----------
    table : QueryTable
        The query.
    key : str
        Its key.
    compute : Callable[[], V]
        The body.

    Returns
    -------
    tuple[V, tuple[tuple[QueryTable, str], ...]]
        The result and its dependencies in reading order.

    Raises
    ------
    QueryError
        If the query is already running, which is a dependency cycle.
    """
    node = (table.name, key)
    if node in self._active:
        cycle = " -> ".join(
            f"{name}[{item!r}]" for name, item in (*self._active, node)
        )
        raise QueryError(f"query cycle: {cycle}")
    self._active.append(node)
    self._frames.append([])
    try:
        value = compute()
    finally:
        reads = self._frames.pop()
        self._active.pop()
    return value, tuple(reads)

events

events(action: QueryAction | None = None, *, since: int = 0) -> tuple[QueryEvent, ...]

The logged steps, optionally of one action and from one point.

PARAMETER DESCRIPTION
action

Only steps of this action, or all when None.

TYPE: QueryAction or None DEFAULT: None

since

Skip the first since entries of the log.

TYPE: int DEFAULT: 0

RETURNS DESCRIPTION
tuple[QueryEvent, ...]

The steps in order.

Source code in src/quivers/incremental/queries.py
def events(
    self, action: QueryAction | None = None, *, since: int = 0
) -> tuple[QueryEvent, ...]:
    """The logged steps, optionally of one action and from one point.

    Parameters
    ----------
    action : QueryAction or None
        Only steps of this action, or all when None.
    since : int
        Skip the first ``since`` entries of the log.

    Returns
    -------
    tuple[QueryEvent, ...]
        The steps in order.
    """
    return tuple(
        event
        for event in self.log[since:]
        if action is None or event.action == action
    )

QueryError

Bases: RuntimeError

A query cannot be answered: an unset input or a dependency cycle.

QueryEvent didactic-model

QueryEvent(*, revision: int, action: QueryAction, query: str, key: str)

Bases: Model

One step of the engine.

PARAMETER DESCRIPTION
revision

The engine revision the step happened at.

TYPE: int

action

What the engine did.

TYPE: QueryAction

query

The query or input name.

TYPE: str

key

The key within it.

TYPE: str

QueryTable

QueryTable(engine: QueryEngine, name: str)

Bases: ABC

An input or query table of an engine.

PARAMETER DESCRIPTION
engine

The owning engine.

TYPE: QueryEngine

name

The table's name, unique in the engine.

TYPE: str

Source code in src/quivers/incremental/queries.py
def __init__(self, engine: QueryEngine, name: str) -> None:
    self.engine = engine
    self.name = name

refresh abstractmethod

refresh(key: str) -> tuple[int, str]

Bring one key up to date.

PARAMETER DESCRIPTION
key

The key.

TYPE: str

RETURNS DESCRIPTION
tuple[int, str]

The revision its value last changed at and its fingerprint.

Source code in src/quivers/incremental/queries.py
@abstractmethod
def refresh(self, key: str) -> tuple[int, str]:
    """Bring one key up to date.

    Parameters
    ----------
    key : str
        The key.

    Returns
    -------
    tuple[int, str]
        The revision its value last changed at and its fingerprint.
    """

ArtifactStore

ArtifactStore(root: Path)

A content-addressed artifact store rooted at one directory.

PARAMETER DESCRIPTION
root

The store directory. It is created on the first write.

TYPE: Path

Source code in src/quivers/incremental/store.py
def __init__(self, root: Path) -> None:
    self.root = root.expanduser().resolve()

max_bytes property

max_bytes: int

The store's byte limit.

RETURNS DESCRIPTION
int

The limit recorded in the store's configuration, or DEFAULT_MAX_BYTES when none is recorded.

RAISES DESCRIPTION
StoreError

If the configuration file is not a valid limit record.

for_project classmethod

for_project(start: Path | None = None) -> ArtifactStore

The store of the project a path belongs to.

PARAMETER DESCRIPTION
start

A path inside the project; the working directory when None.

TYPE: Path or None DEFAULT: None

RETURNS DESCRIPTION
ArtifactStore

The store at default_cache_directory.

RAISES DESCRIPTION
StoreError

If no project root is found and no override is set.

Source code in src/quivers/incremental/store.py
@classmethod
def for_project(cls, start: Path | None = None) -> ArtifactStore:
    """The store of the project a path belongs to.

    Parameters
    ----------
    start : Path or None
        A path inside the project; the working directory when None.

    Returns
    -------
    ArtifactStore
        The store at `default_cache_directory`.

    Raises
    ------
    StoreError
        If no project root is found and no override is set.
    """
    return cls(default_cache_directory(start))

set_max_bytes

set_max_bytes(limit: int) -> tuple[StoreEntry, ...]

Set the store's byte limit and evict down to it.

PARAMETER DESCRIPTION
limit

The new limit in bytes; must be positive.

TYPE: int

RETURNS DESCRIPTION
tuple[StoreEntry, ...]

The entries evicted to fit the new limit.

RAISES DESCRIPTION
StoreError

If the limit is not positive.

Source code in src/quivers/incremental/store.py
def set_max_bytes(self, limit: int) -> tuple[StoreEntry, ...]:
    """Set the store's byte limit and evict down to it.

    Parameters
    ----------
    limit : int
        The new limit in bytes; must be positive.

    Returns
    -------
    tuple[StoreEntry, ...]
        The entries evicted to fit the new limit.

    Raises
    ------
    StoreError
        If the limit is not positive.
    """
    if limit <= 0:
        raise StoreError("a cache limit must be a positive number of bytes")
    with atomic_output(self.root / "config.json") as staging:
        staging.write_text(json.dumps({"max_bytes": limit}), encoding="utf-8")
    return self.prune(max_bytes=limit)

get

get(namespace: str, key: str) -> bytes | None

Read an entry's payload and mark it used.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

RETURNS DESCRIPTION
bytes or None

The payload, or None when the store has no such entry.

RAISES DESCRIPTION
StoreError

If the address is malformed, or the payload does not match the digest recorded with it. A corrupt entry is reported, never served and never silently replaced.

Source code in src/quivers/incremental/store.py
def get(self, namespace: str, key: str) -> bytes | None:
    """Read an entry's payload and mark it used.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.

    Returns
    -------
    bytes or None
        The payload, or None when the store has no such entry.

    Raises
    ------
    StoreError
        If the address is malformed, or the payload does not match the
        digest recorded with it. A corrupt entry is reported, never served
        and never silently replaced.
    """
    payload_path, metadata_path = self._paths(namespace, key)
    if not metadata_path.exists() or not payload_path.exists():
        return None
    entry = self._read_entry(metadata_path)
    payload = payload_path.read_bytes()
    if content_digest(payload) != entry.digest:
        raise StoreError(
            f"cache entry {namespace}/{key} does not match its recorded "
            "digest; remove it with `qvr cache clear`"
        )
    os.utime(payload_path)
    return payload

payload_path

payload_path(namespace: str, key: str) -> Path | None

The verified payload file of an entry, marked used.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

RETURNS DESCRIPTION
Path or None

The payload file, for a reader that needs a path rather than bytes, or None when the store has no such entry. The file must be read, not modified.

RAISES DESCRIPTION
StoreError

If the address is malformed or the payload does not match its recorded digest.

Source code in src/quivers/incremental/store.py
def payload_path(self, namespace: str, key: str) -> Path | None:
    """The verified payload file of an entry, marked used.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.

    Returns
    -------
    Path or None
        The payload file, for a reader that needs a path rather than
        bytes, or None when the store has no such entry. The file must be
        read, not modified.

    Raises
    ------
    StoreError
        If the address is malformed or the payload does not match its
        recorded digest.
    """
    if self.get(namespace, key) is None:
        return None
    payload_path, _ = self._paths(namespace, key)
    return payload_path

staging_path

staging_path(label: str) -> Path

A fresh file path inside the store for writing an artifact.

PARAMETER DESCRIPTION
label

A short name for the file, used as its prefix.

TYPE: str

RETURNS DESCRIPTION
Path

A path in the store's staging directory that does not exist yet. Staging lives with the store, on the project's disk, so an artifact is never written to a temporary directory.

Source code in src/quivers/incremental/store.py
def staging_path(self, label: str) -> Path:
    """A fresh file path inside the store for writing an artifact.

    Parameters
    ----------
    label : str
        A short name for the file, used as its prefix.

    Returns
    -------
    Path
        A path in the store's staging directory that does not exist yet.
        Staging lives with the store, on the project's disk, so an
        artifact is never written to a temporary directory.
    """
    directory = self.root / "staging"
    directory.mkdir(parents=True, exist_ok=True)
    return directory / f"{label}-{os.getpid()}-{time.monotonic_ns()}"

put

put(namespace: str, key: str, payload: bytes, *, label: str = '') -> StoreEntry

Write an entry, then evict down to the byte limit.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

payload

The artifact.

TYPE: bytes

label

A description shown by qvr cache list.

TYPE: str DEFAULT: ''

RETURNS DESCRIPTION
StoreEntry

The written entry.

RAISES DESCRIPTION
StoreError

If the address is malformed or the payload alone exceeds the store's limit.

Source code in src/quivers/incremental/store.py
def put(
    self, namespace: str, key: str, payload: bytes, *, label: str = ""
) -> StoreEntry:
    """Write an entry, then evict down to the byte limit.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.
    payload : bytes
        The artifact.
    label : str
        A description shown by ``qvr cache list``.

    Returns
    -------
    StoreEntry
        The written entry.

    Raises
    ------
    StoreError
        If the address is malformed or the payload alone exceeds the
        store's limit.
    """
    limit = self.max_bytes
    if len(payload) > limit:
        raise StoreError(
            f"a {len(payload)}-byte {namespace} artifact exceeds the cache "
            f"limit of {limit} bytes; raise it with `qvr cache limit`"
        )
    payload_path, metadata_path = self._paths(namespace, key)
    now = time.time()
    entry = StoreEntry(
        namespace=namespace,
        key=key,
        size=len(payload),
        digest=content_digest(payload),
        created=now,
        accessed=now,
        label=label,
    )
    with atomic_output(payload_path) as staging:
        staging.write_bytes(payload)
    with atomic_output(metadata_path) as staging:
        staging.write_text(
            json.dumps(
                {
                    "namespace": namespace,
                    "key": key,
                    "size": entry.size,
                    "digest": entry.digest,
                    "created": entry.created,
                    "label": label,
                },
                sort_keys=True,
            ),
            encoding="utf-8",
        )
    self.prune(max_bytes=limit, keep=(namespace, key))
    return entry

entries

entries(namespace: str | None = None) -> tuple[StoreEntry, ...]

Every entry, most recently used first.

PARAMETER DESCRIPTION
namespace

Only this namespace, or every namespace when None.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
tuple[StoreEntry, ...]

The entries.

RAISES DESCRIPTION
StoreError

If the namespace is malformed or an entry's metadata is corrupt.

Source code in src/quivers/incremental/store.py
def entries(self, namespace: str | None = None) -> tuple[StoreEntry, ...]:
    """Every entry, most recently used first.

    Parameters
    ----------
    namespace : str or None
        Only this namespace, or every namespace when None.

    Returns
    -------
    tuple[StoreEntry, ...]
        The entries.

    Raises
    ------
    StoreError
        If the namespace is malformed or an entry's metadata is corrupt.
    """
    if namespace is not None and _NAMESPACE.fullmatch(namespace) is None:
        raise StoreError(f"invalid cache namespace {namespace!r}")
    if not self._entries_root.exists():
        return ()
    pattern = f"{namespace or '*'}/*/*.json"
    found = [self._read_entry(path) for path in self._entries_root.glob(pattern)]
    return tuple(sorted(found, key=lambda entry: (-entry.accessed, entry.key)))

remove

remove(namespace: str, key: str) -> bool

Delete one entry.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

key

The key.

TYPE: str

RETURNS DESCRIPTION
bool

Whether the entry existed.

RAISES DESCRIPTION
StoreError

If the address is malformed.

Source code in src/quivers/incremental/store.py
def remove(self, namespace: str, key: str) -> bool:
    """Delete one entry.

    Parameters
    ----------
    namespace : str
        The namespace.
    key : str
        The key.

    Returns
    -------
    bool
        Whether the entry existed.

    Raises
    ------
    StoreError
        If the address is malformed.
    """
    payload_path, metadata_path = self._paths(namespace, key)
    existed = metadata_path.exists()
    metadata_path.unlink(missing_ok=True)
    payload_path.unlink(missing_ok=True)
    return existed

clear

clear(namespace: str | None = None) -> int

Delete every entry, or every entry of one namespace.

PARAMETER DESCRIPTION
namespace

The namespace to clear, or None for the whole store.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
int

How many entries were deleted.

RAISES DESCRIPTION
StoreError

If the namespace is malformed.

Source code in src/quivers/incremental/store.py
def clear(self, namespace: str | None = None) -> int:
    """Delete every entry, or every entry of one namespace.

    Parameters
    ----------
    namespace : str or None
        The namespace to clear, or None for the whole store.

    Returns
    -------
    int
        How many entries were deleted.

    Raises
    ------
    StoreError
        If the namespace is malformed.
    """
    removed = len(self.entries(namespace))
    target = (
        self._entries_root if namespace is None else self._entries_root / namespace
    )
    if target.exists():
        shutil.rmtree(target)
    return removed

prune

prune(*, max_bytes: int | None = None, older_than: float | None = None, keep: tuple[str, str] | None = None) -> tuple[StoreEntry, ...]

Evict entries by age and then by size.

PARAMETER DESCRIPTION
max_bytes

Evict least recently used entries until the store holds at most this many bytes; the store's limit when None.

TYPE: int or None DEFAULT: None

older_than

First evict every entry not used for this many seconds; nothing is evicted by age when None.

TYPE: float or None DEFAULT: None

keep

The namespace and key of one entry never to evict, the one just written.

TYPE: tuple[str, str] or None DEFAULT: None

RETURNS DESCRIPTION
tuple[StoreEntry, ...]

The evicted entries.

RAISES DESCRIPTION
StoreError

If an entry's metadata is corrupt.

Source code in src/quivers/incremental/store.py
def prune(
    self,
    *,
    max_bytes: int | None = None,
    older_than: float | None = None,
    keep: tuple[str, str] | None = None,
) -> tuple[StoreEntry, ...]:
    """Evict entries by age and then by size.

    Parameters
    ----------
    max_bytes : int or None
        Evict least recently used entries until the store holds at most
        this many bytes; the store's limit when None.
    older_than : float or None
        First evict every entry not used for this many seconds; nothing is
        evicted by age when None.
    keep : tuple[str, str] or None
        The namespace and key of one entry never to evict, the one just
        written.

    Returns
    -------
    tuple[StoreEntry, ...]
        The evicted entries.

    Raises
    ------
    StoreError
        If an entry's metadata is corrupt.
    """
    limit = self.max_bytes if max_bytes is None else max_bytes
    entries = list(self.entries())
    evicted: list[StoreEntry] = []
    now = time.time()
    if older_than is not None:
        for entry in list(entries):
            if (
                now - entry.accessed > older_than
                and (entry.namespace, entry.key) != keep
            ):
                self.remove(entry.namespace, entry.key)
                evicted.append(entry)
                entries.remove(entry)
    total = sum(entry.size for entry in entries)
    for entry in sorted(entries, key=lambda item: (item.accessed, item.key)):
        if total <= limit:
            break
        if (entry.namespace, entry.key) == keep:
            continue
        self.remove(entry.namespace, entry.key)
        evicted.append(entry)
        total -= entry.size
    return tuple(evicted)

usage

usage() -> StoreUsage

How much the store holds.

RETURNS DESCRIPTION
StoreUsage

Entry counts and byte totals, overall and per namespace.

RAISES DESCRIPTION
StoreError

If an entry's metadata is corrupt.

Source code in src/quivers/incremental/store.py
def usage(self) -> StoreUsage:
    """How much the store holds.

    Returns
    -------
    StoreUsage
        Entry counts and byte totals, overall and per namespace.

    Raises
    ------
    StoreError
        If an entry's metadata is corrupt.
    """
    entries = self.entries()
    by_namespace: dict[str, tuple[int, int]] = {}
    for entry in entries:
        count, size = by_namespace.get(entry.namespace, (0, 0))
        by_namespace[entry.namespace] = (count + 1, size + entry.size)
    return StoreUsage(
        root=str(self.root),
        entries=len(entries),
        size=sum(entry.size for entry in entries),
        max_bytes=self.max_bytes,
        namespaces=tuple(
            NamespaceUsage(namespace=name, entries=count, size=size)
            for name, (count, size) in sorted(by_namespace.items())
        ),
    )

StoreEntry didactic-model

StoreEntry(*, namespace: str, key: str, size: int, digest: str, created: float, accessed: float, label: str = '')

Bases: Model

One cached artifact.

PARAMETER DESCRIPTION
namespace

The kind of artifact ("check", "deduction", "fit", ...).

TYPE: str

key

The digest of everything that determines the artifact.

TYPE: str

size

The payload's size in bytes.

TYPE: int

digest

The BLAKE3 digest of the payload, checked on every read.

TYPE: str

created

When the entry was written, in seconds since the epoch.

TYPE: float

accessed

When the entry was last written or read, in seconds since the epoch.

TYPE: float

label

A human-readable description of what the entry holds.

TYPE: str DEFAULT: ''

StoreError

Bases: RuntimeError

The store cannot honor a request: a bad key, a corrupt entry, a limit.

StoreUsage didactic-model

StoreUsage(*, root: str, entries: int, size: int, max_bytes: int, namespaces: tuple[NamespaceUsage, ...] = ())

Bases: Model

How much a store holds.

PARAMETER DESCRIPTION
root

The store directory.

TYPE: str

entries

The number of entries.

TYPE: int

size

Their total payload size in bytes.

TYPE: int

max_bytes

The store's byte limit.

TYPE: int

namespaces

Each namespace's usage, sorted by name.

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

NamespaceUsage didactic-model

NamespaceUsage(*, namespace: str, entries: int, size: int)

Bases: Model

How much one namespace of a store holds.

PARAMETER DESCRIPTION
namespace

The namespace.

TYPE: str

entries

Its number of entries.

TYPE: int

size

Their total payload size in bytes.

TYPE: int

engine_identity

engine_identity() -> str

The digest of the engine that computes cached artifacts.

RETURNS DESCRIPTION
str

The digest of the quivers version, the kernel ABI, the content-hash format, the torch version, the Python implementation and version, and the operating system and machine. An artifact computed under any other engine is not reused, since checked modules and floating-point results may differ.

Source code in src/quivers/incremental/engine.py
def engine_identity() -> str:
    """The digest of the engine that computes cached artifacts.

    Returns
    -------
    str
        The digest of the quivers version, the kernel ABI, the content-hash
        format, the torch version, the Python implementation and version, and
        the operating system and machine. An artifact computed under any
        other engine is not reused, since checked modules and floating-point
        results may differ.
    """
    return tagged_digest(
        "engine",
        {
            "quivers": __version__,
            "qiec_abi": QIEC_ABI,
            "content_hash": CONTENT_HASH_FORMAT,
            "torch": torch.__version__,
            "python": f"{platform.python_implementation()} {platform.python_version()}",
            "system": platform.system(),
            "machine": platform.machine(),
        },
    )

program_source_digest

program_source_digest(source: ProgramSource) -> str

The digest that identifies a model's program source.

PARAMETER DESCRIPTION
source

The root module and the modules it imports.

TYPE: ProgramSource

RETURNS DESCRIPTION
str

The digest of each module's path with the alpha-normalized statement digest of its text (statements_digest), and of the hole fillings: invariant under comments, formatting, and renaming within each module, and changed by any other edit to any module of the program.

Source code in src/quivers/incremental/fits.py
def program_source_digest(source: ProgramSource) -> str:
    """The digest that identifies a model's program source.

    Parameters
    ----------
    source : ProgramSource
        The root module and the modules it imports.

    Returns
    -------
    str
        The digest of each module's path with the alpha-normalized statement
        digest of its text ([`statements_digest`][quivers.incremental.identity.statements_digest]),
        and of the hole fillings: invariant under comments, formatting, and
        renaming within each module, and changed by any other edit to any
        module of the program.
    """
    return tagged_digest(
        "program-source",
        cast(
            CoreJson,
            {
                "root": [source.module_path, statements_digest(source.root)],
                "modules": [
                    [item.path, statements_digest(item.text)] for item in source.modules
                ],
                "links": [[item.hole, item.module] for item in source.links],
            },
        ),
    )

value_digest

value_digest(value: ExternalValue | InferenceMethod[ModelFit], factories: Mapping[str, ArtifactFactory] | None = None) -> str

The digest of one external value.

PARAMETER DESCRIPTION
value

A datum, a site value, a configuration record, or an inference method: anything the fitted artifact format has a portable contract for.

TYPE: ExternalValue or InferenceMethod[ModelFit]

factories

Explicit contracts for values the format does not know.

TYPE: Mapping[str, ArtifactFactory] or None DEFAULT: None

RETURNS DESCRIPTION
str

The digest of the value's portable encoding.

RAISES DESCRIPTION
FitCacheError

If the value has no portable contract, so no stored fit could have been computed from it.

Source code in src/quivers/incremental/fits.py
def value_digest(
    value: ExternalValue | InferenceMethod[ModelFit],
    factories: Mapping[str, ArtifactFactory] | None = None,
) -> str:
    """The digest of one external value.

    Parameters
    ----------
    value : ExternalValue or InferenceMethod[ModelFit]
        A datum, a site value, a configuration record, or an inference
        method: anything the fitted artifact format has a portable contract
        for.
    factories : Mapping[str, ArtifactFactory] or None
        Explicit contracts for values the format does not know.

    Returns
    -------
    str
        The digest of the value's portable encoding.

    Raises
    ------
    FitCacheError
        If the value has no portable contract, so no stored fit could have
        been computed from it.
    """
    codec = _Codec(factories)
    try:
        encoded = cast(JsonValue, codec.encode(value))
    except TypeError as error:
        raise FitCacheError(f"a value has no content identity: {error}") from error
    return _encoded_digest(codec, encoded)

check_source

check_source(source: bytes, *, module_name: str, file_path: str, roots: tuple[str | Path, ...] = ()) -> QiecModule

Interpret and check a source, with its imports, down to its QIEC module.

The source is the root of a module graph (quivers.dsl.modules): its imports are found in the standard library and below roots, and the flat program is what is checked and hashed.

PARAMETER DESCRIPTION
source

The source.

TYPE: bytes

module_name

The name stable identities derive from (metadata of every hash).

TYPE: str

file_path

The path diagnostics name.

TYPE: str

roots

Directories the source's imported module paths are relative to.

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

RETURNS DESCRIPTION
QiecModule

The checked module.

RAISES DESCRIPTION
IdentityError

If the source does not parse, its module graph does not load or resolve, its QIEC lowering reports a diagnostic (located in the module it comes from), or a program was not elaborated. A module that failed to check has no meaning to hash, and a module missing a program would hash as if the program were absent.

Source code in src/quivers/incremental/identity.py
def check_source(
    source: bytes,
    *,
    module_name: str,
    file_path: str,
    roots: tuple[str | Path, ...] = (),
) -> QiecModule:
    """Interpret and check a source, with its imports, down to its QIEC module.

    The source is the root of a module graph (`quivers.dsl.modules`): its
    imports are found in the standard library and below ``roots``, and the
    flat program is what is checked and hashed.

    Parameters
    ----------
    source : bytes
        The source.
    module_name : str
        The name stable identities derive from (metadata of every hash).
    file_path : str
        The path diagnostics name.
    roots : tuple[str | Path, ...]
        Directories the source's imported module paths are relative to.

    Returns
    -------
    QiecModule
        The checked module.

    Raises
    ------
    IdentityError
        If the source does not parse, its module graph does not load or
        resolve, its QIEC lowering reports a diagnostic (located in the
        module it comes from), or a program was not elaborated. A module that failed to check has no
        meaning to hash, and a module missing a program would hash as if the
        program were absent.
    """
    try:
        flat = interpret_source(source.decode("utf-8"), label=file_path, roots=roots)
    except Exception as error:
        raise IdentityError(f"{file_path}: {error}") from error
    analysis = analyze_module(
        flat.module,
        module_name=module_name,
        file_path=file_path,
        compile_categorical=False,
    )
    if analysis.qiec_diagnostics:
        diagnostic = analysis.qiec_diagnostics[0]
        located = flat.source_map.locate(diagnostic.line, diagnostic.col)
        where = (
            f"{located.file}:{located.line}:{located.column}"
            if located is not None
            else f"{file_path}:{diagnostic.line}:{diagnostic.col}"
        )
        raise IdentityError(f"{where}: [{diagnostic.code}] {diagnostic.message}")
    module = analysis.qiec_module
    if module is None:
        raise IdentityError(f"{file_path}: the source has no checked QIEC module")
    return module

head_grammar

head_grammar() -> str

The panproto schema commit of the grammar this checkout parses.

RETURNS DESCRIPTION
str

The commit pinned for HEAD in the migration manifest.

Source code in src/quivers/incremental/identity.py
def head_grammar() -> str:
    """The panproto schema commit of the grammar this checkout parses.

    Returns
    -------
    str
        The commit pinned for ``HEAD`` in the migration manifest.
    """
    return SCHEMA_COMMITS["HEAD"]

identify

identify(source: str | bytes, *, module_name: str, file_path: str = '<source>', grammar: str | None = None, roots: tuple[str | Path, ...] = ()) -> ProgramIdentity

Every identity of one source file.

PARAMETER DESCRIPTION
source

The source text.

TYPE: str or bytes

module_name

The module name stable identities derive from.

TYPE: str

file_path

The path diagnostics name.

TYPE: str DEFAULT: '<source>'

grammar

The schema commit of the grammar the source is written in; head_grammar when None.

TYPE: str or None DEFAULT: None

roots

Directories the source's imported module paths are relative to.

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

RETURNS DESCRIPTION
ProgramIdentity

Its core hashes, statement source hashes, and source hash.

RAISES DESCRIPTION
IdentityError

If the source does not parse or check.

Source code in src/quivers/incremental/identity.py
def identify(
    source: str | bytes,
    *,
    module_name: str,
    file_path: str = "<source>",
    grammar: str | None = None,
    roots: tuple[str | Path, ...] = (),
) -> ProgramIdentity:
    """Every identity of one source file.

    Parameters
    ----------
    source : str or bytes
        The source text.
    module_name : str
        The module name stable identities derive from.
    file_path : str
        The path diagnostics name.
    grammar : str or None
        The schema commit of the grammar the source is written in;
        `head_grammar` when None.
    roots : tuple[str | Path, ...]
        Directories the source's imported module paths are relative to.

    Returns
    -------
    ProgramIdentity
        Its core hashes, statement source hashes, and source hash.

    Raises
    ------
    IdentityError
        If the source does not parse or check.
    """
    data = source.encode("utf-8") if isinstance(source, str) else source
    commit = head_grammar() if grammar is None else grammar
    module = check_source(
        data, module_name=module_name, file_path=file_path, roots=roots
    )
    core = ModuleContent(module).hashes
    tree = parse_tree(data, file_path)
    statements = statement_hashes(data, tree, file_names(tree, file_path))
    pairs: list[CoreJson] = [
        [kind, digest]
        for kind, digest in sorted(
            (statement.kind, statement.hash) for statement in statements
        )
    ]
    digest = tagged_digest("program", [core.module, commit, pairs])
    return ProgramIdentity(
        core=core,
        statements=statements,
        source=source_hash(data, grammar=commit),
        digest=digest,
    )

source_hash

source_hash(source: bytes, *, grammar: str) -> SourceHash

The hash of a source's exact bytes.

PARAMETER DESCRIPTION
source

The bytes.

TYPE: bytes

grammar

The schema commit of the grammar they are written in.

TYPE: str

RETURNS DESCRIPTION
SourceHash

The grammar commit with the BLAKE3 digest of the bytes.

Source code in src/quivers/incremental/identity.py
def source_hash(source: bytes, *, grammar: str) -> SourceHash:
    """The hash of a source's exact bytes.

    Parameters
    ----------
    source : bytes
        The bytes.
    grammar : str
        The schema commit of the grammar they are written in.

    Returns
    -------
    SourceHash
        The grammar commit with the BLAKE3 digest of the bytes.
    """
    return SourceHash(grammar=grammar, digest=content_digest(source))

statement_hashes

statement_hashes(source: bytes, tree: _Tree, names: FileNames) -> tuple[StatementHash, ...]

The alpha-normalized source hash of every top-level statement.

PARAMETER DESCRIPTION
source

The file's bytes.

TYPE: bytes

tree

Its parse tree.

TYPE: _Tree

names

Its name analysis.

TYPE: FileNames

RETURNS DESCRIPTION
tuple[StatementHash, ...]

One hash per statement, in source order. A statement's hash covers the hashes of the statements it refers to, so it changes when they do; statements that refer to one another are hashed as one component.

RAISES DESCRIPTION
IdentityError

If a reference cannot be resolved.

Source code in src/quivers/incremental/identity.py
def statement_hashes(
    source: bytes, tree: _Tree, names: FileNames
) -> tuple[StatementHash, ...]:
    """The alpha-normalized source hash of every top-level statement.

    Parameters
    ----------
    source : bytes
        The file's bytes.
    tree : _Tree
        Its parse tree.
    names : FileNames
        Its name analysis.

    Returns
    -------
    tuple[StatementHash, ...]
        One hash per statement, in source order. A statement's hash covers
        the hashes of the statements it refers to, so it changes when they
        do; statements that refer to one another are hashed as one component.

    Raises
    ------
    IdentityError
        If a reference cannot be resolved.
    """
    normalizer = _SourceNormalizer(source, tree, names)
    edges = normalizer.dependencies()
    resolved: dict[int, CoreJson] = {}
    hashes: dict[int, str] = {}
    for component in _statement_components(edges):
        members = set(component)

        def serialize(order: list[int], *, erase: bool = False) -> str:
            """The component's serialization in one member order.

            Parameters
            ----------
            order : list[int]
                The members, in the order to serialize them.
            erase : bool
                Whether references into the component are erased rather
                than numbered by position.

            Returns
            -------
            str
                The canonical JSON of the members' forms.
            """
            positions: dict[int, CoreJson] = {
                member: ({"$self": None} if erase else {"$self": i})
                for i, member in enumerate(order)
            }
            forms = [
                normalizer.form(
                    normalizer.statements[member], {**resolved, **positions}, []
                )
                for member in order
            ]
            return canonical_json(forms)

        if len(component) == 1:
            order = component
        else:
            colors: dict[int, str] = {}
            successors: dict[int, tuple[int, ...]] = {}
            for member in component:
                internal: list[int] = []
                form = normalizer.form(
                    normalizer.statements[member],
                    {**resolved, **{item: {"$self": None} for item in members}},
                    internal,
                )
                colors[member] = tagged_digest("statement-cycle-free", form)
                successors[member] = tuple(item for item in internal if item in members)
            order = canonical_order(component, colors, successors, serialize)
        unit = tagged_digest("statements", json.loads(serialize(order)))
        for position, member in enumerate(order):
            hashes[member] = unit if len(order) == 1 else f"{unit}.{position}"
            resolved[member] = hashes[member]
    return tuple(
        StatementHash(
            kind=statement.kind,
            names=statement.declared,
            hash=hashes[statement.index],
        )
        for statement in normalizer.statements
    )

statements_digest

statements_digest(source: str | bytes, *, file_path: str = '<source>', grammar: str | None = None) -> str

The digest of a source's statement hashes, without checking it.

PARAMETER DESCRIPTION
source

The source text.

TYPE: str or bytes

file_path

The path diagnostics name.

TYPE: str DEFAULT: '<source>'

grammar

The schema commit of the grammar the source is written in; head_grammar when None.

TYPE: str or None DEFAULT: None

RETURNS DESCRIPTION
str

The digest of the grammar commit and the multiset of the statements' alpha-normalized source hashes: invariant under renaming, reordering, comments, and formatting, and changed by any other edit to any statement.

RAISES DESCRIPTION
IdentityError

If the source does not parse.

Source code in src/quivers/incremental/identity.py
def statements_digest(
    source: str | bytes,
    *,
    file_path: str = "<source>",
    grammar: str | None = None,
) -> str:
    """The digest of a source's statement hashes, without checking it.

    Parameters
    ----------
    source : str or bytes
        The source text.
    file_path : str
        The path diagnostics name.
    grammar : str or None
        The schema commit of the grammar the source is written in;
        `head_grammar` when None.

    Returns
    -------
    str
        The digest of the grammar commit and the multiset of the statements'
        alpha-normalized source hashes: invariant under renaming, reordering,
        comments, and formatting, and changed by any other edit to any
        statement.

    Raises
    ------
    IdentityError
        If the source does not parse.
    """
    data = source.encode("utf-8") if isinstance(source, str) else source
    commit = head_grammar() if grammar is None else grammar
    try:
        tree = parse_tree(data, file_path)
        names = file_names(tree, file_path)
    except Exception as error:
        raise IdentityError(f"{file_path}: {error}") from error
    pairs: list[CoreJson] = [
        [kind, digest]
        for kind, digest in sorted(
            (statement.kind, statement.hash)
            for statement in statement_hashes(data, tree, names)
        )
    ]
    return tagged_digest("statements-digest", [commit, pairs])

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),
    )

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)

specialization_key

specialization_key(root: str, computation: str, statics: tuple[str, ...]) -> str

The specialize key of a computation at static arguments.

PARAMETER DESCRIPTION
root

The root module's path.

TYPE: str

computation

The computation's name.

TYPE: str

statics

NAME=TERM assignments, in any order.

TYPE: tuple[str, ...]

RETURNS DESCRIPTION
str

A key that names the same specialization however the assignments are ordered.

Source code in src/quivers/incremental/pipeline.py
def specialization_key(root: str, computation: str, statics: tuple[str, ...]) -> str:
    """The ``specialize`` key of a computation at static arguments.

    Parameters
    ----------
    root : str
        The root module's path.
    computation : str
        The computation's name.
    statics : tuple[str, ...]
        ``NAME=TERM`` assignments, in any order.

    Returns
    -------
    str
        A key that names the same specialization however the assignments
        are ordered.
    """
    return json.dumps([root, computation, sorted(statics)])

bytes_fingerprint

bytes_fingerprint(value: bytes) -> str

The fingerprint of a byte string.

PARAMETER DESCRIPTION
value

The bytes.

TYPE: bytes

RETURNS DESCRIPTION
str

Their BLAKE3 digest.

Source code in src/quivers/incremental/queries.py
def bytes_fingerprint(value: bytes) -> str:
    """The fingerprint of a byte string.

    Parameters
    ----------
    value : bytes
        The bytes.

    Returns
    -------
    str
        Their BLAKE3 digest.
    """
    return content_digest(value)

default_cache_directory

default_cache_directory(start: Path | None = None) -> Path

The cache directory of the project a path belongs to.

PARAMETER DESCRIPTION
start

A path inside the project; the working directory when None.

TYPE: Path or None DEFAULT: None

RETURNS DESCRIPTION
Path

$QVR_CACHE_DIR when set, else <project root>/.qvr/cache.

RAISES DESCRIPTION
StoreError

If the variable is unset and no project root is found.

Source code in src/quivers/incremental/store.py
def default_cache_directory(start: Path | None = None) -> Path:
    """The cache directory of the project a path belongs to.

    Parameters
    ----------
    start : Path or None
        A path inside the project; the working directory when None.

    Returns
    -------
    Path
        ``$QVR_CACHE_DIR`` when set, else ``<project root>/.qvr/cache``.

    Raises
    ------
    StoreError
        If the variable is unset and no project root is found.
    """
    override = os.environ.get(CACHE_DIRECTORY_VARIABLE)
    if override:
        return Path(override).expanduser().resolve()
    return find_project_root(start or Path.cwd()) / ".qvr" / "cache"

find_project_root

find_project_root(start: Path) -> Path

The root of the project a path belongs to.

PARAMETER DESCRIPTION
start

A file or directory inside the project.

TYPE: Path

RETURNS DESCRIPTION
Path

The nearest directory, from start upward, that holds a project marker (PROJECT_MARKERS): a qvr.toml manifest, a .qvr directory, or a .git checkout.

RAISES DESCRIPTION
StoreError

If no directory from start to the filesystem root holds a marker. A cache directory is never guessed, so it cannot land somewhere transient by accident.

Source code in src/quivers/incremental/store.py
def find_project_root(start: Path) -> Path:
    """The root of the project a path belongs to.

    Parameters
    ----------
    start : Path
        A file or directory inside the project.

    Returns
    -------
    Path
        The nearest directory, from ``start`` upward, that holds a project
        marker (`PROJECT_MARKERS`): a ``qvr.toml`` manifest, a ``.qvr``
        directory, or a ``.git`` checkout.

    Raises
    ------
    StoreError
        If no directory from ``start`` to the filesystem root holds a marker.
        A cache directory is never guessed, so it cannot land somewhere
        transient by accident.
    """
    current = start.resolve()
    if current.is_file():
        current = current.parent
    for directory in (current, *current.parents):
        if any((directory / marker).exists() for marker in PROJECT_MARKERS):
            return directory
    raise StoreError(
        f"no project root above {start}: none of {', '.join(PROJECT_MARKERS)} "
        f"exists there; create one or set {CACHE_DIRECTORY_VARIABLE}"
    )