Skip to content

Index

memory

Memory as a Marianne primitive (GH #496): the backend contract.

This package defines memory-backend/1.1 — the :class:MemoryBackend protocol, the per-call :class:RequestContext, the value types facts travel in, and the errors/1 taxonomy. Contract modules are pure (no I/O); the shipped backends live under :mod:marianne.memory.backends.

Classes

AccessRef dataclass

AccessRef(kind, name=None, version=None)

A parsed access: value: inherit or a (possibly pinned) grant.

GrantRecord dataclass

GrantRecord(name, version, principal, scope, permissions, revocation_state, created_at, revoked_at=None, parent_version=None)

One version of a named grant (grant-record/1).

Updating a grant writes version n+1 and marks n superseded with parent_version linking the lineage. A pinned reference to a superseded version keeps that version's permissions; a revoked version never confers authority.

MemoryBackend

Bases: Protocol

memory-backend/1.1: what every memory backend implements.

Every operation takes the gateway-built :class:RequestContext first. Failures raise a typed :class:~marianne.memory.errors.MemoryBackendError subclass; a backend never returns an error as a success-shaped dict.

Methods:
declare
declare(ctx, fact, scope, provenance=None, confidence=1.0, tags=None)

Remember fact with its evidence; idempotent per (claim, evidence).

Source code in src/marianne/memory/backend_protocol.py
def declare(
    self,
    ctx: RequestContext,
    fact: str,
    scope: str,
    provenance: Provenance | None = None,
    confidence: float = 1.0,
    tags: list[str] | None = None,
) -> DeclareResult:
    """Remember ``fact`` with its evidence; idempotent per (claim, evidence)."""
    ...
recall
recall(ctx, query, scope, limit=100, cursor=None, cap_bytes=None)

Facts relevant to query, within the per-response byte cap.

cap_bytes is an optional per-call ceiling the gateway sets to min(recall_cap_bytes, quota_remaining); the backend applies the smaller of it and its own cap, stops reading at it and returns its cursor. None keeps the backend's own cap (the 1.1 behaviour).

Source code in src/marianne/memory/backend_protocol.py
def recall(
    self,
    ctx: RequestContext,
    query: str,
    scope: str,
    limit: int = 100,
    cursor: str | None = None,
    cap_bytes: int | None = None,
) -> RecallResult:
    """Facts relevant to ``query``, within the per-response byte cap.

    ``cap_bytes`` is an optional per-call ceiling the gateway sets to
    ``min(recall_cap_bytes, quota_remaining)``; the backend applies the
    smaller of it and its own cap, stops reading at it and returns its
    cursor. ``None`` keeps the backend's own cap (the 1.1 behaviour).
    """
    ...
verify
verify(ctx, fact_id_or_hash, expected_evidence='')

Re-check a fact against its evidence; read-only.

Source code in src/marianne/memory/backend_protocol.py
def verify(
    self, ctx: RequestContext, fact_id_or_hash: str, expected_evidence: str = "",
) -> VerifyResult:
    """Re-check a fact against its evidence; read-only."""
    ...
bind
bind(ctx, fact_id, target_symbol, evidence_receipt=None)

Bind a freshly verified fact to an action; re-checks disk first.

Source code in src/marianne/memory/backend_protocol.py
def bind(
    self,
    ctx: RequestContext,
    fact_id: str,
    target_symbol: str,
    evidence_receipt: str | None = None,
) -> BindResult:
    """Bind a freshly verified fact to an action; re-checks disk first."""
    ...
forget
forget(ctx, fact_id, reason='')

Tombstone a fact (archive, never silent delete).

Source code in src/marianne/memory/backend_protocol.py
def forget(self, ctx: RequestContext, fact_id: str, reason: str = "") -> ForgetResult:
    """Tombstone a fact (archive, never silent delete)."""
    ...
fetch
fetch(ctx, unit_id, offset, length)

A bounded byte range of an oversized unit.

Source code in src/marianne/memory/backend_protocol.py
def fetch(self, ctx: RequestContext, unit_id: str, offset: int, length: int) -> FetchResult:
    """A bounded byte range of an oversized unit."""
    ...
stream_facts
stream_facts(ctx, scope, since_revision=None)

Export every live fact and tombstone as migration-facts/1 batches.

Source code in src/marianne/memory/backend_protocol.py
def stream_facts(
    self, ctx: RequestContext, scope: str, since_revision: int | None = None,
) -> Iterator[MigrationBatch]:
    """Export every live fact and tombstone as ``migration-facts/1`` batches."""
    ...
migration_ingest
migration_ingest(ctx, migration_id, envelope)

Staged import: begin -> batch... -> finalize | abort.

Source code in src/marianne/memory/backend_protocol.py
def migration_ingest(
    self, ctx: RequestContext, migration_id: str, envelope: MigrationEnvelope,
) -> MigrationResult:
    """Staged import: ``begin`` -> ``batch``... -> ``finalize`` | ``abort``."""
    ...
health
health()

A memory-health/1 record for this backend's binding.

Source code in src/marianne/memory/backend_protocol.py
def health(self) -> MemoryHealth:
    """A ``memory-health/1`` record for this backend's binding."""
    ...

RequestContext dataclass

RequestContext(principal, scope, permissions, deadline_at, dispatch_id=None, job_id=None, session_id=None)

The immutable per-call envelope (memory-backend/1.1).

deadline_at is a POSIX timestamp. A conforming backend clamps every lock wait to remaining_seconds and aborts with E10 before it mutates anything once the deadline has passed. scope is canonicalised on construction; permissions is the session's ceiling.

Attributes
remaining_seconds property
remaining_seconds

Seconds left before deadline_at; never negative.

Methods:
require
require(permission)

Raise E2 naming permission when the ceiling lacks it.

Source code in src/marianne/memory/backend_protocol.py
def require(self, permission: Permission) -> None:
    """Raise E2 naming ``permission`` when the ceiling lacks it."""
    if not self.has(permission):
        raise PermissionDenied(
            f"operation needs `{permission.value}`; session holds "
            f"{list(self.permissions) or 'no permissions'}",
            subtype="permission_denied",
        )
require_any
require_any(*permissions)

Raise E2 unless the ceiling holds at least one of permissions.

Source code in src/marianne/memory/backend_protocol.py
def require_any(self, *permissions: Permission) -> None:
    """Raise E2 unless the ceiling holds at least one of ``permissions``."""
    if not any(self.has(p) for p in permissions):
        names = " or ".join(f"`{p.value}`" for p in permissions)
        raise PermissionDenied(
            f"operation needs {names}; session holds "
            f"{list(self.permissions) or 'no permissions'}",
            subtype="permission_denied",
        )

AuthorityRevoked

AuthorityRevoked(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E8: the session's authority epoch is stale (grant revoked).

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

BackendUnreachable

BackendUnreachable(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E5: the backend cannot be reached or its storage cannot be opened.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

DeadBackend

DeadBackend(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E6: reserved — the backend died mid-session.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

DeadlineExceeded

DeadlineExceeded(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E10: the call deadline passed before mutation began.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

ErrorCode

Bases: str, Enum

The eleven errors/1 codes. Member name is the wire code.

LockTimeout

LockTimeout(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E9: lock acquisition did not succeed within the call's budget.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

MemoryBackendError

MemoryBackendError(detail, *, subtype='', remedy='')

Bases: Exception

Base of every typed memory failure.

Deliberately not derived from the builtin MemoryError (which means the interpreter ran out of RAM). Construct a subclass, never this base.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)
Methods:
to_wire
to_wire()

Serialise for the gateway's tool-call error response.

Source code in src/marianne/memory/errors.py
def to_wire(self) -> WireError:
    """Serialise for the gateway's tool-call error response."""
    return {
        "code": self.code.name,
        "name": self.code.value,
        "subtype": self.subtype,
        "detail": self.detail,
        "remedy": self.remedy,
    }

NotFound

NotFound(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E11: the fact, unit or attachment does not exist in the bound store.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

PermissionDenied

PermissionDenied(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E2: the session lacks the permission the operation needs.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

RecallCapExceeded

RecallCapExceeded(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E4: the dispatch's cumulative recall quota is spent.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

SchemaViolation

SchemaViolation(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E7: an argument or configuration value fails the contract.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

ScopeRefused

ScopeRefused(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E3: scope expression malformed or outside the authorised scope.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

Unauthenticated

Unauthenticated(detail, *, subtype='', remedy='')

Bases: MemoryBackendError

E1: peer credentials missing or wrong for this endpoint.

Source code in src/marianne/memory/errors.py
def __init__(self, detail: str, *, subtype: str = "", remedy: str = "") -> None:
    self.detail = detail
    self.subtype = subtype or self.code.value
    self.remedy = remedy
    text = f"{self.code.name} {self.code.value}"
    if self.subtype != self.code.value:
        text += f" ({self.subtype})"
    text += f": {detail}"
    if remedy:
        text += f" — remedy: {remedy}"
    super().__init__(text)

FactRecord

Bases: TypedDict

One fact with its evidence and its clocks, as it migrates.

MigrationBatch

Bases: TypedDict

One migration-facts/1 record yielded by stream_facts.

Permission

Bases: str, Enum

The seven memory permissions. They live in conductor access records, never in score YAML.

Provenance

Bases: TypedDict

Evidence a musician supplies with a declaration.

evidence_locator names where the claim can be re-checked (a path, a URL, snapshot:<sha256>); observed_at is the source observation clock, distinct from the backend's asserted_at write clock.

RecallResult

Bases: TypedDict

One recall page.

cursor is a page cut (resume with its token) or None when nothing is left. Units too large for the page cap are never truncated: each is listed in oversized with remedy: fetch, so a page cut and several oversized markers can travel in one response.

ScopeKey dataclass

ScopeKey(family, ident)

A canonical scope: one family and one identifier.

The canonical spelling is local:<id> for the local family and <family>/<id> for every other, so one (family, id) pair has exactly one string everywhere it is joined on.

Tombstone

Bases: TypedDict

A generational erasure: revokes the claim at or before cutoff.

Functions:

parse_access

parse_access(raw)

Parse an access: expression or raise E7 schema_violation.

Source code in src/marianne/memory/access.py
def parse_access(raw: str) -> AccessRef:
    """Parse an ``access:`` expression or raise E7 ``schema_violation``."""
    if raw == "inherit":
        return INHERIT
    match = _ACCESS_RE.match(raw) if isinstance(raw, str) else None
    if match is None:
        raise SchemaViolation(
            f"access {raw!r} is neither `inherit` nor `grant:<name>[@<version>]` "
            "(name: a-z 0-9 _ -; version: a positive integer)",
            subtype="access_invalid",
            remedy="write `access: inherit` or `access: grant:<name>` / `grant:<name>@<n>`",
        )
    version = int(match.group(2)) if match.group(2) else None
    return AccessRef(kind="grant", name=match.group(1), version=version)

content_hash

content_hash(text)

SHA-256 hex digest of the fact text (UTF-8).

Source code in src/marianne/memory/model.py
def content_hash(text: str) -> str:
    """SHA-256 hex digest of the fact text (UTF-8)."""
    return hashlib.sha256(text.encode("utf-8")).hexdigest()

derive_fact_id

derive_fact_id(scope, evidence_locator, chash, claim_digest)

Deterministic 16-hex fact id over (scope, locator, content hash, claim digest).

Fields are NUL-separated so ("a", "bc") and ("ab", "c") differ. Re-declaring the same claim with the same evidence yields the same id.

Source code in src/marianne/memory/model.py
def derive_fact_id(scope: str, evidence_locator: str, chash: str, claim_digest: str) -> str:
    """Deterministic 16-hex fact id over (scope, locator, content hash, claim digest).

    Fields are NUL-separated so ``("a", "bc")`` and ``("ab", "c")`` differ.
    Re-declaring the same claim with the same evidence yields the same id.
    """
    joined = "\0".join((scope, evidence_locator, chash, claim_digest))
    return hashlib.sha256(joined.encode("utf-8")).hexdigest()[:16]

memory_health

memory_health(status, detail, *, checked_at=0.0)

Build a memory-health/1 record; failure_class follows status.

Source code in src/marianne/memory/model.py
def memory_health(status: HealthStatus, detail: str, *, checked_at: float = 0.0) -> MemoryHealth:
    """Build a ``memory-health/1`` record; ``failure_class`` follows ``status``."""
    if status not in _HEALTH_STATUSES:
        raise SchemaViolation(f"unknown health status {status!r}", subtype="health_status_invalid")
    if not math.isfinite(checked_at):
        raise SchemaViolation("checked_at must be finite", subtype="health_status_invalid")
    failure: FailureClass | None
    if status == "unreachable":
        failure = "unreachable"
    elif status == "unauthenticated":
        failure = "unauthenticated"
    elif status == "scope_refused":
        failure = "scope_refused"
    elif status == "degraded":
        failure = "degraded"
    else:
        failure = None
    return {
        "schema": "memory-health/1",
        "status": status,
        "detail": detail,
        "checked_at": checked_at,
        "failure_class": failure,
    }

oversized_unit_cursor

oversized_unit_cursor(unit_id, unit_bytes, cap_bytes)

A single unit larger than the page cap: page it with fetch.

Source code in src/marianne/memory/model.py
def oversized_unit_cursor(unit_id: str, unit_bytes: int, cap_bytes: int) -> OversizedUnit:
    """A single unit larger than the page cap: page it with ``fetch``."""
    return {
        "kind": "oversized_unit",
        "unit_id": unit_id,
        "unit_bytes": unit_bytes,
        "cap_bytes": cap_bytes,
        "remedy": "fetch",
    }

page_cursor

page_cursor(cursor, section_id, omitted)

A page cut: resume with cursor to receive the omitted sections.

Source code in src/marianne/memory/model.py
def page_cursor(cursor: str, section_id: str, omitted: int) -> PageCursor:
    """A page cut: resume with ``cursor`` to receive the omitted sections."""
    return {"kind": "page", "cursor": cursor, "section_id": section_id, "omitted": omitted}

parse_scope

parse_scope(raw)

Parse and canonicalise a scope expression, or raise E3 scope_refused.

Grammar: <family>(:|/)<id> with <id> in [a-z0-9_.-]+; input is stripped and lowercased. An id made only of dots is refused because the files backend maps a scope onto a directory and .. would escape it.

Source code in src/marianne/memory/model.py
def parse_scope(raw: str) -> ScopeKey:
    """Parse and canonicalise a scope expression, or raise E3 ``scope_refused``.

    Grammar: ``<family>(:|/)<id>`` with ``<id>`` in ``[a-z0-9_.-]+``; input is
    stripped and lowercased. An id made only of dots is refused because the
    files backend maps a scope onto a directory and ``..`` would escape it.
    """
    text = raw.strip().lower() if isinstance(raw, str) else ""
    match = _SCOPE_RE.match(text)
    if match is None:
        raise ScopeRefused(
            f"scope {raw!r} does not match <family>/<id> "
            f"(families: {', '.join(SCOPE_FAMILIES)}; id: a-z 0-9 _ . -)",
            subtype="scope_invalid",
            remedy="write a scope like `project/my-project` or `local:default`",
        )
    family = _FAMILY_ALIASES.get(match.group(1), match.group(1))
    ident = match.group(3)
    if set(ident) == {"."}:
        raise ScopeRefused(
            f"scope {raw!r} has a path-like id {ident!r}",
            subtype="scope_invalid",
            remedy="use a name, not `.` or `..`",
        )
    return ScopeKey(family=family, ident=ident)