Skip to content

Query engine

Memoized queries with red-green verification, early cutoff, persistence, and a log of every step.

queries

A demand-driven query engine with red-green invalidation and early cutoff.

A compilation is a set of queries: functions of a key (parse of a module, check of a module, interface of a module, ...) that read inputs (source text) and other queries. The engine memoizes every query result together with the queries and inputs it read, its fingerprint (a digest of the result), and two revisions: when it was last verified and when it last changed.

Setting an input to a value with a new fingerprint starts a new revision. Asking for a query then walks its recorded dependencies in the order it read them: if none changed after the result was last verified, the result is green and is reused without running the query. Otherwise the query runs again, and if its new result has the old fingerprint the result is backdated (early cutoff): its change revision stays where it was, so the queries that read it stay green. This is the scheme of Salsa and of rustc's incremental compilation, a constructive-trace build system in the terminology of Mokhov, Mitchell, and Peyton Jones (2018).

A query declared with a QueryCodec is also persisted in an ArtifactStore: its result and the fingerprints of its dependencies survive the process, and a later engine reuses the stored result when every dependency still has the recorded fingerprint, without running the query.

Every step is recorded in QueryEngine.log, which is how a caller (or a test) sees exactly what was recomputed.

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.

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

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

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.
    """

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

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
    )

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)