Skip to content

Index

ipc

IPC layer for the conductor — Unix socket + JSON-RPC 2.0.

Classes

DaemonClient

DaemonClient(socket_path, *, timeout=30.0, pool_size=_DEFAULT_POOL_SIZE)

Async client for the Marianne daemon Unix socket IPC.

Parameters

socket_path: Path to the Unix domain socket created by DaemonServer. timeout: Seconds to wait for a response before raising TimeoutError. pool_size: Maximum number of pooled connections for call().

Source code in src/marianne/daemon/ipc/client.py
def __init__(
    self,
    socket_path: Path,
    *,
    timeout: float = 30.0,
    pool_size: int = _DEFAULT_POOL_SIZE,
) -> None:
    self._socket_path = socket_path
    self._timeout = timeout
    self._pool_size = pool_size
    self._next_id = 0
    self._pool: ConnectionPool | None = None
Methods:
close async
close()

Close the connection pool. Safe to call multiple times.

Source code in src/marianne/daemon/ipc/client.py
async def close(self) -> None:
    """Close the connection pool.  Safe to call multiple times."""
    pool, self._pool = self._pool, None
    if pool is not None:
        await pool.close()
call async
call(method, params=None)

Send an RPC; retry transport failures only for known safe reads.

A timeout never retries: the daemon may still be doing the operation. Cancellation and corrupt responses discard the connection, preventing late replies from contaminating the next request.

Source code in src/marianne/daemon/ipc/client.py
async def call(
    self,
    method: str,
    params: dict[str, Any] | None = None,
) -> Any:
    """Send an RPC; retry transport failures only for known safe reads.

    A timeout never retries: the daemon may still be doing the operation.
    Cancellation and corrupt responses discard the connection, preventing
    late replies from contaminating the next request.
    """
    request = JsonRpcRequest(method=method, params=params, id=self._next_request_id())
    pool = self._get_pool()
    attempts = 2 if method in _SAFE_RETRY_METHODS else 1
    for attempt in range(attempts):
        reader, writer = await pool.acquire()
        try:
            result = await self._send_and_receive(reader, writer, request)
        except (
            asyncio.CancelledError, TimeoutError, DaemonProtocolError,
            DaemonAccessDeniedError, ResourceExhaustedError,
        ):
            pool.discard(writer)
            raise
        except (OSError, DaemonNotRunningError):
            pool.discard(writer)
            if attempt + 1 == attempts:
                raise
            _logger.debug("pool_retry_safe_read", method=method)
        except DaemonError:
            # A valid application error is a complete matching response.
            pool.release(reader, writer)
            raise
        except BaseException:
            pool.discard(writer)
            raise
        else:
            pool.release(reader, writer)
            return result
stream async
stream(method, params=None)

Send a JSON-RPC request and yield streaming notifications.

Notifications (no id) are yielded as dicts. The final response (with id) terminates the iteration.

If the final response contains an error, raises the corresponding DaemonError.

Source code in src/marianne/daemon/ipc/client.py
async def stream(
    self,
    method: str,
    params: dict[str, Any] | None = None,
) -> AsyncIterator[dict[str, Any]]:
    """Send a JSON-RPC request and yield streaming notifications.

    Notifications (no ``id``) are yielded as dicts.  The final
    response (with ``id``) terminates the iteration.

    If the final response contains an error, raises the
    corresponding ``DaemonError``.
    """
    request = JsonRpcRequest(
        method=method,
        params=params,
        id=self._next_request_id(),
    )

    async with self._connect() as (reader, writer):
        async with asyncio.timeout(self._timeout):
            writer.write(request.model_dump_json().encode() + b"\n")
            await writer.drain()

        async for raw_line in reader:
            if not raw_line:
                break

            msg = json.loads(raw_line)

            if not isinstance(msg, dict) or msg.get("jsonrpc") != "2.0":
                raise DaemonProtocolError("Invalid streaming response envelope")
            if "id" in msg or "error" in msg or "result" in msg:
                self._validate_response(msg, request.id)
                if "error" in msg:
                    raise rpc_error_to_exception(msg["error"])
                return
            if not isinstance(msg.get("method"), str):
                raise DaemonProtocolError("Invalid streaming response notification")
            params = msg.get("params", {})
            if not isinstance(params, dict):
                raise DaemonProtocolError("Invalid streaming response notification params")
            yield params
        raise DaemonNotRunningError("Daemon closed stream before final response")
is_daemon_running async
is_daemon_running()

Check if daemon is running by performing a lightweight health RPC.

Uses a dedicated connection with a short deadline. Missing/refused sockets return False; an endpoint that accepts but does not respond raises DaemonUnresponsiveError, preserving the difference from absence.

Source code in src/marianne/daemon/ipc/client.py
async def is_daemon_running(self) -> bool:
    """Check if daemon is running by performing a lightweight health RPC.

    Uses a dedicated connection with a short deadline. Missing/refused
    sockets return False; an endpoint that accepts but does not respond
    raises DaemonUnresponsiveError, preserving the difference from absence.
    """
    if not _socket_exists(self._socket_path):
        return False

    async def probe() -> None:
        request = JsonRpcRequest(method="daemon.health", id=self._next_request_id())
        async with self._connect() as (reader, writer):
            try:
                await self._send_and_receive(reader, writer, request)
            except DaemonNotRunningError as exc:
                raise DaemonUnresponsiveError(
                    "Conductor accepted the health probe but closed before responding"
                ) from exc

    try:
        await asyncio.wait_for(probe(), timeout=_HEALTH_TIMEOUT_SECONDS)
    except DaemonNotRunningError:
        return False
    except TimeoutError as exc:
        raise DaemonUnresponsiveError(
            "Conductor socket exists but did not respond to the health probe"
        ) from exc
    except (json.JSONDecodeError, ValueError) as exc:
        raise DaemonProtocolError(f"Invalid conductor health response: {exc}") from exc
    return True
status async
status()

Get daemon status.

Source code in src/marianne/daemon/ipc/client.py
async def status(self) -> DaemonStatus:
    """Get daemon status."""
    result = await self.call("daemon.status")
    return DaemonStatus(**result)
register_schedule async
register_schedule(config_path)

Request daemon-side recurring registration and accepted digest.

Source code in src/marianne/daemon/ipc/client.py
async def register_schedule(self, config_path: Path) -> ScheduleVenueResult:
    """Request daemon-side recurring registration and accepted digest."""
    try:
        raw = await self.call("schedule.register", {"config_path": str(config_path)})
    except MethodNotFoundError:
        return self._inconclusive_schedule("", "method_not_found")
    try:
        result = ScheduleVenueResult.model_validate(raw)
    except (TypeError, ValueError) as exc:
        raise DaemonProtocolError("Unbound schedule registration response") from exc
    if result.state in {"live", "disabled"} and not (
        result.registry_identity and result.schedule_id and result.source_digest
    ):
        raise DaemonProtocolError("Unbound schedule registration response")
    return result
current_schedule async
current_schedule(schedule_id, registry_identity, source_digest)

Read only the venue and schedule bound by an accepted receipt.

Source code in src/marianne/daemon/ipc/client.py
async def current_schedule(
    self, schedule_id: str, registry_identity: str, source_digest: str,
) -> ScheduleVenueResult:
    """Read only the venue and schedule bound by an accepted receipt."""
    params = {"schedule_id": schedule_id, "registry_identity": registry_identity,
              "source_digest": source_digest}
    try:
        raw = await self.call("schedule.current", params)
    except MethodNotFoundError:
        return self._inconclusive_schedule(schedule_id, "method_not_found")
    return self._bind_schedule_result(
        raw, schedule_id, registry_identity, source_digest,
    )
cancel_schedule async
cancel_schedule(schedule_id, registry_identity, source_digest)

Cancel one bound schedule; never retry a lost mutation response.

Source code in src/marianne/daemon/ipc/client.py
async def cancel_schedule(
    self, schedule_id: str, registry_identity: str, source_digest: str,
) -> ScheduleVenueResult:
    """Cancel one bound schedule; never retry a lost mutation response."""
    params = {"schedule_id": schedule_id, "registry_identity": registry_identity,
              "source_digest": source_digest}
    try:
        raw = await self.call("schedule.cancel", params)
    except MethodNotFoundError:
        return self._inconclusive_schedule(schedule_id, "method_not_found")
    return self._bind_schedule_result(
        raw, schedule_id, registry_identity, source_digest,
    )
register_schedule_v2 async
register_schedule_v2(config_path)

Request a daemon-minted receipt for caller-owned durable custody.

Source code in src/marianne/daemon/ipc/client.py
async def register_schedule_v2(self, config_path: Path) -> ScheduleVenueResult:
    """Request a daemon-minted receipt for caller-owned durable custody."""
    try:
        raw = await self.call("schedule.register_v2", {"config_path": str(config_path)})
    except MethodNotFoundError:
        return self._inconclusive_schedule("", "method_not_found")
    try:
        result = ScheduleVenueResult.model_validate(raw)
    except (TypeError, ValueError) as exc:
        raise DaemonProtocolError("Malformed v2 registration response") from exc
    if result.state in {"live", "disabled"} and not (
        result.receipt_version == 2 and result.registration_id
        and result.registry_identity and result.schedule_id and result.source_digest
    ):
        raise DaemonProtocolError("Unbound v2 registration response")
    return result
submit_job async
submit_job(request)

Submit a job to the daemon.

Source code in src/marianne/daemon/ipc/client.py
async def submit_job(self, request: JobRequest) -> JobResponse:
    """Submit a job to the daemon."""
    result = await self.call("job.submit", request.model_dump(mode="json"))
    return JobResponse(**result)
get_job_status async
get_job_status(job_id, workspace)

Get status of a specific job.

Source code in src/marianne/daemon/ipc/client.py
async def get_job_status(self, job_id: str, workspace: str) -> dict[str, Any]:
    """Get status of a specific job."""
    result = await self.call("job.status", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
pause_job async
pause_job(job_id, workspace)

Pause a running job. Returns {"paused": bool}.

Source code in src/marianne/daemon/ipc/client.py
async def pause_job(self, job_id: str, workspace: str) -> dict[str, Any]:
    """Pause a running job. Returns ``{"paused": bool}``."""
    result = await self.call("job.pause", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
resume_job async
resume_job(job_id, workspace)

Resume a paused job. Returns a JobResponse dict.

Source code in src/marianne/daemon/ipc/client.py
async def resume_job(self, job_id: str, workspace: str) -> dict[str, Any]:
    """Resume a paused job. Returns a JobResponse dict."""
    result = await self.call("job.resume", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
cancel_job async
cancel_job(job_id, workspace)

Cancel a running or paused job. Returns {"cancelled": bool}.

Source code in src/marianne/daemon/ipc/client.py
async def cancel_job(self, job_id: str, workspace: str) -> dict[str, Any]:
    """Cancel a running or paused job. Returns ``{"cancelled": bool}``."""
    result = await self.call("job.cancel", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
list_jobs async
list_jobs()

List all jobs known to the daemon.

Source code in src/marianne/daemon/ipc/client.py
async def list_jobs(self) -> list[dict[str, Any]]:
    """List all jobs known to the daemon."""
    return cast(list[dict[str, Any]], await self.call("job.list"))
clear_jobs async
clear_jobs(statuses=None, older_than_seconds=None, job_ids=None)

Clear terminal jobs from the daemon registry.

Parameters:

Name Type Description Default
statuses list[str] | None

Status filter (defaults to terminal statuses).

None
older_than_seconds float | None

Only clear jobs older than this.

None
job_ids list[str] | None

Only clear these specific job IDs.

None

Returns:

Type Description
dict[str, Any]

Dict with "deleted" count.

Source code in src/marianne/daemon/ipc/client.py
async def clear_jobs(
    self,
    statuses: list[str] | None = None,
    older_than_seconds: float | None = None,
    job_ids: list[str] | None = None,
) -> dict[str, Any]:
    """Clear terminal jobs from the daemon registry.

    Args:
        statuses: Status filter (defaults to terminal statuses).
        older_than_seconds: Only clear jobs older than this.
        job_ids: Only clear these specific job IDs.

    Returns:
        Dict with "deleted" count.
    """
    params: dict[str, Any] = {}
    if statuses is not None:
        params["statuses"] = statuses
    if older_than_seconds is not None:
        params["older_than_seconds"] = older_than_seconds
    if job_ids is not None:
        params["job_ids"] = job_ids
    return cast(dict[str, Any], await self.call("job.clear", params))
config async
config()

Get the conductor's live running configuration.

Source code in src/marianne/daemon/ipc/client.py
async def config(self) -> dict[str, Any]:
    """Get the conductor's live running configuration."""
    return cast(dict[str, Any], await self.call("daemon.config"))
reload_config async
reload_config(reason='cli')

Trigger the conductor's single config reload path (#408).

Not in _SAFE_RETRY_METHODS: a reload is a mutation, so a response lost after send has an unknown outcome and is never blindly retried.

Source code in src/marianne/daemon/ipc/client.py
async def reload_config(self, reason: str = "cli") -> dict[str, Any]:
    """Trigger the conductor's single config reload path (#408).

    Not in ``_SAFE_RETRY_METHODS``: a reload is a mutation, so a
    response lost after send has an unknown outcome and is never
    blindly retried.
    """
    return cast(
        dict[str, Any], await self.call("daemon.reload", {"reason": reason})
    )
health async
health()

Liveness probe independent of busy pooled request connections.

Source code in src/marianne/daemon/ipc/client.py
async def health(self) -> dict[str, Any]:
    """Liveness probe independent of busy pooled request connections."""
    async def probe() -> dict[str, Any]:
        request = JsonRpcRequest(method="daemon.health", id=self._next_request_id())
        async with self._connect() as (reader, writer):
            return cast(dict[str, Any], await self._send_and_receive(reader, writer, request))

    return await asyncio.wait_for(
        probe(), timeout=min(self._timeout, _HEALTH_TIMEOUT_SECONDS),
    )
readiness async
readiness()

Readiness probe — is the daemon accepting new jobs?

Source code in src/marianne/daemon/ipc/client.py
async def readiness(self) -> dict[str, Any]:
    """Readiness probe — is the daemon accepting new jobs?"""
    return cast(dict[str, Any], await self.call("daemon.ready"))
get_errors async
get_errors(job_id, workspace=None)

Get errors for a specific job.

Source code in src/marianne/daemon/ipc/client.py
async def get_errors(self, job_id: str, workspace: str | None = None) -> dict[str, Any]:
    """Get errors for a specific job."""
    result = await self.call("job.errors", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
diagnose async
diagnose(job_id, workspace=None)

Get diagnostic data for a specific job.

Source code in src/marianne/daemon/ipc/client.py
async def diagnose(self, job_id: str, workspace: str | None = None) -> dict[str, Any]:
    """Get diagnostic data for a specific job."""
    result = await self.call("job.diagnose", {"job_id": job_id, "workspace": workspace})
    return cast(dict[str, Any], result)
get_execution_history async
get_execution_history(job_id, workspace=None, sheet_num=None, limit=50)

Get execution history for a specific job.

Source code in src/marianne/daemon/ipc/client.py
async def get_execution_history(
    self, job_id: str, workspace: str | None = None,
    sheet_num: int | None = None, limit: int = 50,
) -> dict[str, Any]:
    """Get execution history for a specific job."""
    result = await self.call("job.history", {
        "job_id": job_id, "workspace": workspace,
        SHEET_NUM_KEY: sheet_num, "limit": limit,
    })
    return cast(dict[str, Any], result)
recover_job async
recover_job(job_id, workspace=None, sheet_num=None, dry_run=False)

Request recovery data for a specific job.

Source code in src/marianne/daemon/ipc/client.py
async def recover_job(
    self, job_id: str, workspace: str | None = None,
    sheet_num: int | None = None, dry_run: bool = False,
) -> dict[str, Any]:
    """Request recovery data for a specific job."""
    result = await self.call("job.recover", {
        "job_id": job_id, "workspace": workspace,
        SHEET_NUM_KEY: sheet_num, "dry_run": dry_run,
    })
    return cast(dict[str, Any], result)
rate_limits async
rate_limits()

Get current rate limit state across all backends.

Source code in src/marianne/daemon/ipc/client.py
async def rate_limits(self) -> dict[str, Any]:
    """Get current rate limit state across all backends."""
    return cast(dict[str, Any], await self.call("daemon.rate_limits"))
learning_patterns async
learning_patterns(limit=20)

Get recent learning patterns from the global store.

Source code in src/marianne/daemon/ipc/client.py
async def learning_patterns(self, limit: int = 20) -> dict[str, Any]:
    """Get recent learning patterns from the global store."""
    return cast(dict[str, Any], await self.call("daemon.learning.patterns", {"limit": limit}))

DaemonServer

DaemonServer(socket_path, handler, *, permissions=432, backlog=100, max_connections=DEFAULT_MAX_CONNECTIONS, max_concurrent_requests=DEFAULT_MAX_CONCURRENT_REQUESTS, max_streams=DEFAULT_MAX_STREAMS, request_timeout=300.0, write_timeout=10.0, read_idle_timeout=DEFAULT_READ_IDLE_TIMEOUT, enforce_peer_uid=True)

Async Unix domain socket server with JSON-RPC 2.0 routing.

Parameters

socket_path: Filesystem path for the Unix domain socket. handler: RequestHandler that dispatches JSON-RPC methods. permissions: Octal file permissions applied to the socket after creation. Defaults to 0o660 (owner + group read/write). max_connections: Maximum simultaneous connected clients. FD protection — idle connections are cheap, so the default is high (~500). max_concurrent_requests: Maximum requests being processed at once across all connections. This is the real concurrency control (~50). read_idle_timeout: Seconds a connection may sit between complete messages before the server closes it (dead/stuck client FD hygiene). enforce_peer_uid: Refuse connections whose peer UID differs from the daemon's effective UID. Defense-in-depth over socket file permissions — the 0o660 mode admits the owning group, and root bypasses file modes entirely. On platforms where the peer UID cannot be read (no SO_PEERCRED) the gate fails open, because absence of the credential is not evidence of a foreign peer. Unix credentials are user-granular: this stops other users, not other processes running as the same user.

Source code in src/marianne/daemon/ipc/server.py
def __init__(
    self,
    socket_path: Path,
    handler: RequestHandler,
    *,
    permissions: int = 0o660,
    backlog: int = 100,
    max_connections: int = DEFAULT_MAX_CONNECTIONS,
    max_concurrent_requests: int = DEFAULT_MAX_CONCURRENT_REQUESTS,
    max_streams: int = DEFAULT_MAX_STREAMS,
    request_timeout: float = 300.0,
    write_timeout: float = 10.0,
    read_idle_timeout: float = DEFAULT_READ_IDLE_TIMEOUT,
    enforce_peer_uid: bool = True,
) -> None:
    if backlog < 1 or max_streams < 1:
        raise ValueError("backlog and max_streams must be >= 1")
    if request_timeout <= 0 or write_timeout <= 0:
        raise ValueError("request_timeout and write_timeout must be > 0")
    if max_connections < 1:
        raise ValueError(f"max_connections must be >= 1, got {max_connections}")
    if max_concurrent_requests < 1:
        raise ValueError(
            f"max_concurrent_requests must be >= 1, got {max_concurrent_requests}"
        )
    if read_idle_timeout <= 0:
        raise ValueError(
            f"read_idle_timeout must be > 0, got {read_idle_timeout}"
        )

    self._socket_path = socket_path
    self._handler = handler
    self._permissions = permissions
    self._backlog = backlog
    self._max_connections = max_connections
    self._max_concurrent_requests = max_concurrent_requests
    self._read_idle_timeout = read_idle_timeout
    self._request_timeout = request_timeout
    self._write_timeout = write_timeout
    self._enforce_peer_uid = enforce_peer_uid
    self._server: asyncio.AbstractServer | None = None
    self._socket_owner = OwnedUnixSocket(socket_path)
    self._stop_task: asyncio.Task[None] | None = None
    self._connections: set[asyncio.Task[None]] = set()
    self._connection_semaphore = asyncio.Semaphore(max_connections)
    self._request_semaphore = asyncio.Semaphore(max_concurrent_requests)
    self._stream_semaphore = asyncio.Semaphore(max_streams)
Attributes
is_running property
is_running

Return whether the server is currently accepting connections.

Methods:
start async
start()

Bind the Unix socket and start accepting connections.

Source code in src/marianne/daemon/ipc/server.py
async def start(self) -> None:
    """Bind the Unix socket and start accepting connections."""
    if self._stop_task is not None and not self._stop_task.done():
        raise RuntimeError("IPC server shutdown is still in progress")
    self._stop_task = None
    self._server = await self._socket_owner.start(
        self._accept_connection,
        permissions=self._permissions,
        backlog=self._backlog,
        limit=MAX_MESSAGE_BYTES,
    )

    _logger.info(
        "ipc_server_started",
        socket_path=str(self._socket_path),
        max_connections=self._max_connections,
        max_concurrent_requests=self._max_concurrent_requests,
    )
stop async
stop()

Finish owned cleanup before propagating caller cancellation.

Source code in src/marianne/daemon/ipc/server.py
async def stop(self) -> None:
    """Finish owned cleanup before propagating caller cancellation."""
    if self._stop_task is None:
        if self._server is None:
            return
        self._stop_task = asyncio.create_task(
            self._stop_resources(), name="ipc-server-stop",
        )
    cleanup = self._stop_task
    cancelled = False
    # A canceled caller must not cancel handler finalizers or abandon the
    # lifetime lock. Concurrent stop callers share the same owned cleanup.
    while not cleanup.done():
        try:
            await asyncio.shield(cleanup)
        except asyncio.CancelledError:
            cancelled = True
    cleanup.result()
    if cancelled:
        raise asyncio.CancelledError