Skip to content

session

session

Per-dispatch sessions (BE2): admitted -> active -> draining -> closed | revoked.

Classes

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: