Skip to content

Project store

The persistent, size-limited, content-addressed directory every cache of a project lives in, managed from the command line by qvr cache.

store

A persistent, size-limited, content-addressed store for a project's caches.

The store keeps every cached artifact of a project (checked modules, compiled deductions, fitted runs) under one directory, .qvr/cache at the project root by default. Entries are addressed by a namespace and a 64-character digest of everything that determines them, so an entry is either exactly the artifact its key describes or absent: a key never names stale content.

The store has a byte limit. Writing past it evicts the least recently used entries until the store fits again, and ArtifactStore.prune and the qvr cache command evict on demand. Every payload is stored with its BLAKE3 digest and checked on every read.

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.

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_DIRECTORY_VARIABLE module-attribute

CACHE_DIRECTORY_VARIABLE = 'QVR_CACHE_DIR'

The environment variable that overrides the cache directory.

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.

StoreError

Bases: RuntimeError

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

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: ''

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

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: ()

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

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}"
    )

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"