memory_gate
memory_gate
¶
The memory dispatch gate: per-dispatch memory sessions for the baton adapter.
All memory logic the conductor needs at dispatch lives here, so the adapter only
makes three small, guarded calls (register/deregister a job, prepare before a
backend is acquired, teardown when the dispatch ends).
- A job without a
memory:key never reaches this module:preparereturnsNoneat once and nothing heavy (gateway, endpoint, backend, audit log) exists until the first dispatch that needs one. Those are created lazily. prepareis all-or-nothing: if any attachment fails to open, every session and socket opened for that dispatch so far is closed and a typed :class:MemoryGateErrornaming the attachment is raised.- The harness gets one MCP config file per dispatch, in its own directory
<workspace>/.marianne-memory/<hash>/mcp.json(0700/0600), holding the technique servers plus one shim entry per attachment. The file names a socket and nothing else: no principal, scope, grant or session id. teardownnever raises into the caller; it reports what it could not stop.- Session lifetime is the owner's liveness, read at call time. One
threading.Event(the dispatch's "ended" flag) is shared by every session of a dispatch and checked first on every call. It is set, instantly and from the loop, byteardown(before any I/O is queued),deregister_job,shutdownand a done-callback on the owner task. No clock, lease or renewal is involved: a finished or cancelled sheet's sessions refuse the very next call however busy the worker is. A reaper task exists for hygiene only (it enqueues the teardown that a flagged dispatch missed, and ends ownerless dispatches after a grace on the monotonic clock); if it dies, flagged sessions are still refused and only socket and directory cleanup waits for deregister or shutdown. - All gate I/O (session open/close with its audit fsync, config write/delete, sweeps) runs
on ONE ordered daemon worker thread. One slow job therefore delays opens and cleanups for
every dispatch (head-of-line blocking), but it can no longer end a live session: a job that
runs longer than
SLOW_JOB_SECONDSis logged (memory_gate.slow_job, with its kind). - Still on the event loop: endpoint bind/unbind (socket creation,
start_unix_server), backend construction and close, the run-directorymkdirin_ensure, the sweep of stale sockets' bookkeeping, the cam endpoint table (set_cam_endpointsrebinds it whole), and all gate dictionaries. None blocks on a lock or an fsync. - A failed memory open fails the dispatch; it does not degrade to "no memory". That is
intended: the sheet's prompt names tools that must exist. A misconfigured attachment
(
MemoryConfigError) is stronger still: it fails the sheet at once (MEMORY_CONFIG_ERROR,E301) — it is not retried and does not move along the fallback chain, because no instrument can deliver it. - Same-UID limit (stated once): the socket path is passed in the shim's environment rather
than argv, which hides it from other users but not from other processes of the same user
(
/proc/<pid>/environis readable too), and every job of one conductor shares one principal; so a sheet with a shell can reach another job's session if it finds the path.
Classes¶
MemoryGateError
¶
Bases: Exception
A memory attachment could not be delivered. Names the attachment and the reason.
Source code in src/marianne/daemon/baton/memory_gate.py
MemoryConfigCollision
¶
Bases: MemoryGateError
A memory server name is already present in the technique MCP config.
Source code in src/marianne/daemon/baton/memory_gate.py
MemoryConfigError
¶
Bases: MemoryGateError
A memory attachment is misconfigured: no retry and no other instrument can change it.
config_key is the memory_backends.cam.<name> key the refusal points at: the
missing endpoint for an unknown endpoint, the attachment's own endpoint for an
operator-only setting. It is None when no one key is at fault (an unknown setting,
an endpoint that is not a name). The adapter adds the key to the dispatch failure's
message when the reason does not already name it.
Source code in src/marianne/daemon/baton/memory_gate.py
SheetIdentity
dataclass
¶
The sheet a dispatch is for: number, movement number and (optional) phase name.
OpenedSession
dataclass
¶
One attachment's live session. Conductor-side only; never rendered to a musician.
TeardownReport
dataclass
¶
What teardown left behind: calls still running, and steps that failed.
PreparedMemory
dataclass
¶
What the adapter needs from one dispatch: the text to append and the config to attach.
MemoryDispatchGate
¶
MemoryDispatchGate(*, run_dir, memory_root, audit_dir, user, cam_endpoints=None, clock=time, monotonic=monotonic, shutdown_bound_seconds=SHUTDOWN_BOUND_SECONDS, start_reaper=True, ownerless_grace_seconds=OWNERLESS_GRACE_SECONDS, slow_job_seconds=SLOW_JOB_SECONDS, reap_interval_seconds=REAP_INTERVAL_SECONDS)
Opens and closes the memory sessions of each dispatch, per (job, dispatch).
Concurrency model (see also MEMORY-DISPATCH-GATE-NOTES.md):
- The loop owns all bookkeeping (
_open,_jobs, registered backends) and the cam endpoint table: :meth:set_cam_endpointsrebinds it whole, and the loop is its lock. - Every blocking action goes through ONE single-thread worker, in submission order: open a session, close a session, write a config, delete a config, sweep. Because there is one worker, two actions on the same thing can never overlap.
- A worker job is never cancelled with its awaiter. Its result is applied on the loop by a completion step that runs whether or not anybody still awaits it, and that step decides ownership: every successful open is either recorded in an open dispatch or has a close enqueued (the one-open-one-owner invariant); a config written for a dispatch that is gone is deleted.
Source code in src/marianne/daemon/baton/memory_gate.py
Methods:¶
set_cam_endpoints
¶
Replace the cam endpoint table (#573); the next dispatch resolves against it.
The table is replaced whole, on the loop. No lock is taken: the loop is the lock,
because the only reader (_cam_settings) runs on the loop with no await between
reading the table and building the backend. A session that is already open keeps the
backend it was opened with; an endpoint whose settings changed gets a new backend,
because the resolved settings are part of the backend key. DaemonConfig validates
the section before it reaches the gate, so nothing is checked here.
Source code in src/marianne/daemon/baton/memory_gate.py
deregister_job
¶
Forget the job, tear down its open dispatches, then remove its dispatch dirs.
Source code in src/marianne/daemon/baton/memory_gate.py
drain
async
¶
Wait for the gate's own background work and queued worker jobs (not callers' tasks).
Source code in src/marianne/daemon/baton/memory_gate.py
merge_config
¶
Queue this dispatch's merged MCP config under its own directory.
Returns a future. Its completion step runs on the loop whether or not anybody is still awaiting: if the dispatch is gone by then, the file is queued for deletion.
Source code in src/marianne/daemon/baton/memory_gate.py
deliver
async
¶
prepare + merge_config as one all-or-nothing step for the adapter.
Returns None when the job has no active attachment for this sheet. On any
failure everything opened is torn down before the error propagates.
Source code in src/marianne/daemon/baton/memory_gate.py
set_owner
¶
Record the task whose life bounds this dispatch: when it ends, so do the sessions.
Source code in src/marianne/daemon/baton/memory_gate.py
tick
async
¶
One hygiene pass; public so a test can drive it with an injected clock.
Enqueues the teardown of a dispatch whose flag is set but whose teardown was never enqueued (a missed one), and ends a dispatch that still has no owner after the grace. Correctness never depends on it: the flag alone refuses calls.
Source code in src/marianne/daemon/baton/memory_gate.py
sweep_stale
async
¶
Run :meth:_sweep_sockets on the worker (never on the loop); returns how many.
With no <run_dir>/s directory there is nothing to sweep (no memory job has ever
run here): return 0 without starting the worker thread.
Source code in src/marianne/daemon/baton/memory_gate.py
sweep_stale_configs
async
¶
Remove dispatch directories a dead conductor left in workspace; returns how many.
Runs on the worker, and spares every directory of a dispatch this gate has open (asked when the worker reaches it), so it is safe while the recovered job is already running.
Source code in src/marianne/daemon/baton/memory_gate.py
schedule_config_sweep
¶
Fire-and-forget :meth:sweep_stale_configs for each workspace (needs a running loop).
Called when a job is recovered after a conductor restart: its sheets' dispatch directories from the previous process are dead, and nothing else would remove them. A failure is logged, never raised.
Source code in src/marianne/daemon/baton/memory_gate.py
schedule_teardown
¶
Fire-and-forget teardown for a done-callback (needs a running loop).
Source code in src/marianne/daemon/baton/memory_gate.py
teardown
async
¶
Close sockets and sessions and remove the config. Idempotent; never raises.
Source code in src/marianne/daemon/baton/memory_gate.py
shutdown
async
¶
Close everything within a bound. Never awaits or cancels a caller's task.
Sets _closing first (no new prepare; an open still in flight is closed by its
own completion step), queues a close for every open dispatch, waits for the worker
queue to drain up to shutdown_bound_seconds, reports what is still pending,
then stops the worker.
Source code in src/marianne/daemon/baton/memory_gate.py
Functions:¶
can_deliver
¶
Why this backend/instrument cannot be handed an MCP config, or None if it can.
Source code in src/marianne/daemon/baton/memory_gate.py
lookup_profile
¶
The instrument profile the pool would use, or None when it cannot be read.
Source code in src/marianne/daemon/baton/memory_gate.py
merge_mcp_config
¶
Write dest_dir/name holding the existing config's servers plus entries.
Atomic (temp file in the same directory, fsync, os.replace), mode 0600. A name
present in both the existing config and entries is refused, never overwritten.
The existing file is only read. (The gate itself writes through
:func:_write_dispatch_config, which never follows a symlink.)