Skip to content

backend

backend

The files backend: journaled, custody-checked, capped scope-tree memory on disk.

On-disk layout (all under the files root, ~/.marianne/memory/files by default)::

<root>/<family>/<id>/*.md                tier files (recent.md, growth.md, ...)
<root>/<family>/<id>/{displaced,archive,actions}/   prior tier versions, forgotten
                                          facts, bind receipts
<root>/trees/<tree-key>/state.json       the ledger (facts, tombstones, revision)
<root>/trees/<tree-key>/journal/NNNNNNNN.json        write-intent journal
<root>/trees/<tree-key>/locks/write.lock flock(2) writer lock

Every tier write is: journal pending -> displaced copy -> temp file in the same directory -> os.replace -> ledger save -> journal committed. A crash anywhere is resolved by the next writer: tier at the post-image digest completes the write, at the pre-image digest discards it, anything else is ambiguous and refuses writes until reconcile(resolve_interrupted_journal=True). The ledger remembers the digest of each tier it last wrote; a tier that differs on disk was edited by something else (custody violation) and is refused until reconcile adopts it. A raw writer's bytes are never overwritten silently.

Known departures, wave A: no renameat2(RENAME_EXCHANGE) (plain os.replace plus a retained displaced copy), no registry persons, no verbatim legacy mode. The writer lock is acquired by polling flock(LOCK_NB) with a short capped backoff until the call deadline; that bounded retry is the only sleep.

Classes

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

FilesBackend

FilesBackend(config)

memory-backend/1.1 over Markdown tier files; see the module docstring.

Source code in src/marianne/memory/backends/files/backend.py
def __init__(self, config: Mapping[str, Any]) -> None:
    try:
        cfg = FilesBackendConfig.model_validate(dict(config))
    except ValidationError as exc:
        detail = "; ".join(
            f"{'.'.join(str(p) for p in e['loc']) or 'config'}: {e['msg']}"
            for e in exc.errors()
        )
        raise files_error(
            "config_invalid", detail, remedy="fix the attachment configuration",
        ) from None
    if cfg.registry_root:
        raise files_error(
            "config_invalid", "registry persons are not supported in wave A",
            remedy="leave registry_root empty",
        )
    if cfg.legacy != "sectioned":
        raise files_error(
            "config_invalid", "only legacy=sectioned is built in wave A",
            remedy="use legacy: sectioned",
        )
    self._cfg = cfg
    self._scope = cfg.scope
    self._tree = Path(cfg.memory_tree)
    self._attach = Path(cfg.attachment_dir)
    key = hashlib.sha256(cfg.memory_tree.encode("utf-8")).hexdigest()[:16]
    self._state_dir = Path(cfg.state_root) / key
    self._failpoint: Callable[[str], None] | None = None
    self._closed = False
    with _TREES_LOCK:
        held = _TREES.get(cfg.memory_tree)
        if held is not None and held[0] != self._scope:
            raise files_error(
                "config_invalid",
                f"conflicting_scope_alias: tree {cfg.memory_tree} already serves "
                f"{held[0]!r}, not {self._scope!r}",
                remedy="give each scope its own tree",
            )
        _TREES[cfg.memory_tree] = (self._scope, (held[1] if held else 0) + 1)
Methods:
close
close()

Release this binding's claim on its tree (idempotent).

Source code in src/marianne/memory/backends/files/backend.py
def close(self) -> None:
    """Release this binding's claim on its tree (idempotent)."""
    if self._closed:
        return
    self._closed = True
    with _TREES_LOCK:
        held = _TREES.get(self._cfg.memory_tree)
        if held is not None:
            if held[1] <= 1:
                del _TREES[self._cfg.memory_tree]
            else:
                _TREES[self._cfg.memory_tree] = (held[0], held[1] - 1)
reconcile
reconcile(ctx, resolve_interrupted_journal=False)

Adopt the tiers as they are on disk (admin). Never rewrites a tier.

Source code in src/marianne/memory/backends/files/backend.py
def reconcile(
    self, ctx: RequestContext, resolve_interrupted_journal: bool = False,
) -> dict[str, Any]:
    """Adopt the tiers as they are on disk (admin). Never rewrites a tier."""
    self._guard(ctx, Permission.ADMIN)
    self._check_deadline(ctx)
    with self._storage(), self._locked(ctx, resolve=bool(resolve_interrupted_journal)):
        state = self._load_state()
        tiers = self._scan()
        adopted = sorted(
            name for name, t in tiers.items() if state["tiers"].get(name) != t.digest
        )
        state["tiers"] = {name: t.digest for name, t in tiers.items()}
        self._save_state(state)
        return {"adopted": adopted, "revision": int(state["revision"])}

Functions:

files_backend_factory

files_backend_factory(config)

Build a :class:FilesBackend from an attachment config. Does no I/O.

Source code in src/marianne/memory/backends/files/backend.py
def files_backend_factory(config: Mapping[str, Any]) -> FilesBackend:
    """Build a :class:`FilesBackend` from an attachment config. Does no I/O."""
    return FilesBackend(config)