Skip to content

Index

gateway

The in-process memory gateway: sessions, grants, the six-tool surface, the audit log.

A library a conductor can host; it holds no socket and no daemon. It reaches backends only through the memory-backend/1.1 protocol.

Classes

AuditLog

AuditLog(root)

Writer for per-session chained segments.

Source code in src/marianne/memory/gateway/audit.py
def __init__(self, root: Path | str) -> None:
    self._root = Path(root)
    self._lock = threading.Lock()
    self._tails: dict[Path, tuple[int, str]] = {}  # path -> (next seq, last hash)
Methods:
append
append(*, dispatch_id, session_id, principal, event, seal=False, **fields)

Append one record (fsynced) and return it. seal stamps segment_hash.

Source code in src/marianne/memory/gateway/audit.py
def append(
    self, *, dispatch_id: str | None, session_id: str, principal: str, event: str,
    seal: bool = False, **fields: Any,
) -> dict[str, Any]:
    """Append one record (fsynced) and return it. ``seal`` stamps ``segment_hash``."""
    if event not in _EVENTS:
        raise SchemaViolation(f"unknown audit event {event!r}", subtype="audit_event_invalid")
    if dispatch_id is None:
        session_id = hashlib.sha256(session_id.encode("utf-8")).hexdigest()[:16]
    path = self.path_for(dispatch_id, session_id)
    with self._lock:
        seq, prev = self._tail(path)
        record: dict[str, Any] = {
            "schema": AUDIT_SCHEMA, "seq": seq, "event": event, "timestamp": time.time(),
            "dispatch_id": dispatch_id, "session_id": session_id, "principal": principal,
            **fields, "prev_hash": None if seq == 0 else prev,
        }
        record["record_hash"] = _hash(prev, record)
        if seal:
            record["segment_hash"] = record["record_hash"]
        path.parent.mkdir(parents=True, exist_ok=True)
        data = (json.dumps(record, sort_keys=True, ensure_ascii=False) + "\n").encode()
        fd = os.open(path, os.O_WRONLY | os.O_APPEND | os.O_CREAT, 0o600)
        try:
            os.write(fd, data)
            os.fsync(fd)
        finally:
            os.close(fd)
        if seal:
            # A sealed segment is finished: keep no per-session state for it. A stray later
            # append re-reads the tail from the file, so correctness never rested on the cache.
            self._tails.pop(path, None)
        else:
            self._tails[path] = (seq + 1, record["record_hash"])
        return record

Gateway

Gateway(*, grants=None, audit=None, require_audit=True, clock=time)

A library a conductor can host. Holds no socket; reaches backends only via the Protocol.

Source code in src/marianne/memory/gateway/gateway.py
def __init__(
    self, *, grants: GrantStore | None = None, audit: AuditLog | None = None,
    require_audit: bool = True, clock: Callable[[], float] = time.time,
) -> None:
    self._clock = clock
    if audit is None and require_audit:
        raise SchemaViolation(
            "a gateway without an audit log is refused",
            subtype="audit_required", remedy="pass audit=AuditLog(...) or require_audit=False",
        )
    self.sessions = SessionTable(clock=clock)
    self._audit = audit
    self._grants = grants
    self._backends: dict[str, MemoryBackend] = {}
Methods:
open_session
open_session(*, principal, attachment_id, scope, dispatch_id, deadline_at, permissions=(), job_id=None, caps=None, access=None, ended=None)

Admit a session. A grant: reference fixes the permission ceiling (BE3.3/3.4).

Source code in src/marianne/memory/gateway/gateway.py
def open_session(
    self, *, principal: str, attachment_id: str, scope: str, dispatch_id: str,
    deadline_at: float, permissions: tuple[str, ...] = (), job_id: str | None = None,
    caps: MemoryCaps | None = None, access: AccessRef | None = None,
    ended: threading.Event | None = None,
) -> Session:
    """Admit a session. A ``grant:`` reference fixes the permission ceiling (BE3.3/3.4)."""
    if attachment_id not in self._backends:
        raise NotFound(
            f"attachment {attachment_id!r} has no registered backend",
            subtype="attachment_unbound",
        )
    canonical = parse_scope(scope).canonical
    if access is not None and access.kind == "grant":
        if self._grants is None:
            raise SchemaViolation(
                "grant reference given but the gateway has no grant store",
                subtype="grant_store_missing",
            )
        grant = self._grants.resolve_ref(access)
        if grant.principal != principal or not scope_covers(grant.scope, canonical):
            raise ScopeRefused(
                f"grant {grant.name!r} does not belong to {principal} at {canonical}",
                subtype="scope_refused",
            )
        permissions = tuple(
            p for p in grant.permissions if not permissions or p in permissions
        )
    session = self.sessions.open(
        principal=principal, attachment_id=attachment_id, scope=canonical,
        permissions=permissions, dispatch_id=dispatch_id, deadline_at=deadline_at,
        job_id=job_id, caps=caps, ended=ended,
    )
    session.grant_ref = access if access is not None and access.kind == "grant" else None
    if self._audit is not None:
        self._audit.append(
            dispatch_id=session.dispatch_id, session_id=session.session_id,
            principal=session.principal, event="session_opened", scope=session.scope,
            result_status="ok",
        )
    return session
close_session
close_session(session_id)

Close a session once. A second close (or a close of a forgotten id) is a no-op.

The live-to-closed transition and the was_live read happen in one locked section, so exactly one caller writes the sealed audit row. Returns None when the session was already forgotten.

Source code in src/marianne/memory/gateway/gateway.py
def close_session(self, session_id: str) -> Session | None:
    """Close a session once. A second close (or a close of a forgotten id) is a no-op.

    The live-to-closed transition and the ``was_live`` read happen in one locked
    section, so exactly one caller writes the sealed audit row. Returns ``None`` when
    the session was already forgotten.
    """
    try:
        s, was_live = self.sessions.close_if_live(session_id)
    except Unauthenticated:  # a tombstoned id: already closed, sealed and forgotten
        return None
    if self._audit is not None and was_live:
        self._audit.append(
            dispatch_id=s.dispatch_id, session_id=s.session_id, principal=s.principal,
            event="session_closed", seal=True, scope=s.scope, result_status="ok",
            call_count=s.call_count, bytes_read=s.bytes_read, bytes_written=s.bytes_written,
            duration_seconds=self._clock() - s.opened_at,
        )
    if was_live:
        self.sessions.forget(session_id)
    return s
audit_endpoint_event
audit_endpoint_event(session_id, *, tool, result_status, error_code=None, **fields)

Record an endpoint-level event (refused attempt, cancellation) for a session.

Source code in src/marianne/memory/gateway/gateway.py
def audit_endpoint_event(
    self, session_id: str, *, tool: str | None, result_status: str,
    error_code: str | None = None, **fields: Any,
) -> None:
    """Record an endpoint-level event (refused attempt, cancellation) for a session."""
    if self._audit is None:
        return
    s = self.sessions.get(session_id)
    self._audit.append(
        dispatch_id=s.dispatch_id, session_id=s.session_id, principal=s.principal,
        event="operation", scope=s.scope, tool=tool, result_status=result_status,
        error_code=error_code, **fields,
    )

MemoryCaps dataclass

MemoryCaps(recall_cap_bytes=32768, dispatch_recall_quota_bytes=None, provenance='optional', per_call_budget_seconds=10.0, lock_timeout_seconds=10.0)

Per-session caps (spec Interfaces 1 MemoryCaps).

SessionTable

SessionTable(clock=time)

Thread-safe table of sessions; legal transitions only.

Source code in src/marianne/memory/gateway/session.py
def __init__(self, clock: Callable[[], float] = time.time) -> None:
    self._clock = clock
    self._sessions: dict[str, Session] = {}
    self._tombstones: OrderedDict[str, None] = OrderedDict()
    self._lock = threading.RLock()
Methods:
admit_call
admit_call(session_id, permission)

Gate one call by owner flag, state, deadline and permission; the first success activates.

permission is the permission the tool needs. Every refusal leaves call_count and the state untouched, except that an expired session is moved to closed so it can never be used again.

Source code in src/marianne/memory/gateway/session.py
def admit_call(self, session_id: str, permission: str) -> Session:
    """Gate one call by owner flag, state, deadline and permission; the first success activates.

    ``permission`` is the permission the tool needs. Every refusal leaves
    ``call_count`` and the state untouched, except that an expired session
    is moved to ``closed`` so it can never be used again.
    """
    if permission not in PERMISSION_VALUES:
        raise SchemaViolation(
            f"unknown permission {permission!r}", subtype="permission_invalid"
        )
    with self._lock:
        s = self.get(session_id)
        if s.ended is not None and s.ended.is_set():
            raise Unauthenticated(
                "session is closed", subtype="session_closed", remedy="open a new session",
            )
        if s.state is SessionState.REVOKED:
            raise AuthorityRevoked(
                "session authority was revoked", subtype="authority_revoked",
                remedy="open a new session",
            )
        if s.state is SessionState.CLOSED:
            raise Unauthenticated(
                "session is closed", subtype="session_closed", remedy="open a new session",
            )
        if self._clock() >= s.deadline_at:
            s.state = SessionState.CLOSED
            raise DeadlineExceeded(
                "the session deadline has passed", subtype="deadline_exceeded",
                remedy="open a new session",
            )
        if permission not in s.permissions:
            raise PermissionDenied(
                f"call needs `{permission}`; session holds "
                f"{list(s.permissions) or 'no permissions'}",
                subtype="permission_denied",
            )
        if s.state is SessionState.DRAINING and permission in WRITE_PERMISSIONS:
            raise PermissionDenied(
                "session is draining; new writes are refused", subtype="session_draining",
            )
        if s.state is SessionState.ADMITTED:
            s.state = SessionState.ACTIVE
        s.call_count += 1
        return s
reserve_recall
reserve_recall(session_id, cap)

Atomically reserve min(cap, quota - used - reserved) bytes; 0 means none left.

With no dispatch quota nothing is reserved and cap is returned unchanged.

Source code in src/marianne/memory/gateway/session.py
def reserve_recall(self, session_id: str, cap: int) -> int:
    """Atomically reserve ``min(cap, quota - used - reserved)`` bytes; 0 means none left.

    With no dispatch quota nothing is reserved and ``cap`` is returned unchanged.
    """
    with self._lock:
        s = self._sessions[session_id]
        quota = s.caps.dispatch_recall_quota_bytes
        if quota is None:
            return cap
        amount = max(0, min(cap, quota - s.recall_bytes_used - s.recall_reserved))
        s.recall_reserved += amount
        return amount
settle_recall
settle_recall(session_id, reserved, used)

Return the whole reservation and account the bytes actually returned.

Source code in src/marianne/memory/gateway/session.py
def settle_recall(self, session_id: str, reserved: int, used: int) -> None:
    """Return the whole reservation and account the bytes actually returned."""
    with self._lock:
        s = self._sessions[session_id]
        if s.caps.dispatch_recall_quota_bytes is not None:
            s.recall_reserved -= reserved
        s.recall_bytes_used += used
close_if_live
close_if_live(session_id)

Close under the lock; True only for the one caller that made the transition.

Source code in src/marianne/memory/gateway/session.py
def close_if_live(self, session_id: str) -> tuple[Session, bool]:
    """Close under the lock; ``True`` only for the one caller that made the transition."""
    with self._lock:
        s = self.get(session_id)
        was_live = s.state not in TERMINAL
        if was_live:
            s.state = SessionState.CLOSED
        return s, was_live
forget
forget(session_id)

Drop a terminal session from the table, keeping a bounded tombstone of its id.

Source code in src/marianne/memory/gateway/session.py
def forget(self, session_id: str) -> bool:
    """Drop a terminal session from the table, keeping a bounded tombstone of its id."""
    with self._lock:
        s = self._sessions.get(session_id)
        if s is None or s.state not in TERMINAL:
            return False
        del self._sessions[session_id]
        self._tombstones[session_id] = None
        while len(self._tombstones) > self.TOMBSTONES:
            self._tombstones.popitem(last=False)
        return True
revoke_for
revoke_for(*, principal)

Revoke every live session of principal; returns their ids.

Source code in src/marianne/memory/gateway/session.py
def revoke_for(self, *, principal: str) -> list[str]:
    """Revoke every live session of ``principal``; returns their ids."""
    with self._lock:
        hit = [
            s.session_id for s in self._sessions.values()
            if s.principal == principal and s.state not in TERMINAL
        ]
        for sid in hit:
            self._sessions[sid].state = SessionState.REVOKED
        return hit

Functions:

verify_audit_file

verify_audit_file(path, *, require_sealed=False)

Recompute the chain; report the first line that is removed-after, edited or reordered.

Source code in src/marianne/memory/gateway/audit.py
def verify_audit_file(path: Path | str, *, require_sealed: bool = False) -> AuditVerification:
    """Recompute the chain; report the first line that is removed-after, edited or reordered."""
    p = Path(path)
    prev = GENESIS
    count = 0
    sealed = False
    for n, raw in enumerate(p.read_text(encoding="utf-8").splitlines(), start=1):
        def bad(reason: str, n: int = n, seen: int = count) -> AuditVerification:
            return AuditVerification(False, seen, n, reason)

        try:
            rec = json.loads(raw)
            if not isinstance(rec, dict):
                raise ValueError("not an object")
        except ValueError:
            return bad("line is not a JSON object")
        if rec.get("schema") != AUDIT_SCHEMA:
            return bad("wrong schema")
        if rec.get("seq") != count:
            return bad(f"seq {rec.get('seq')!r} where {count} expected (line removed or moved)")
        if rec.get("prev_hash") != (None if count == 0 else prev):
            return bad("prev_hash does not link to the previous record")
        if _hash(prev, rec) != rec.get("record_hash"):
            return bad("record_hash does not match the record (edited)")
        if sealed:
            return bad("record after the sealing record")
        if "segment_hash" in rec:
            if rec["segment_hash"] != rec["record_hash"]:
                return bad("segment_hash differs from the terminal record_hash")
            sealed = True
        prev = rec["record_hash"]
        count += 1
    if require_sealed and not sealed:
        return AuditVerification(False, count, None, "segment is not sealed", sealed=False)
    return AuditVerification(True, count, sealed=sealed)