malkuth

v0.7.0
malkuth Checked 5 hours ago

A composable service-supervision toolkit for Rust

Composable service-supervision toolkit for Rust Malkuth helps automated, long-running programs handle supervision — graceful shutdown, health probes, coordination locks, and rolling updates: 1. Pluggable transport — JSON-RPC over TCP, WebSocket, or IPC (Unix sockets / named pipes). One Transport trait, dispatched by URL scheme. 2. Supervised workers — spawn a process, monitor its health, restart it on failure, drain connections before shutdown. 3. Optional facilities — exit source, probes, heartbeat and drain hooks are *traits*. Use the defaults or supply your own. 4.

Summary extracted from the README.

License: SySL-1.0 GitHub Checks Docs docs.rs

English · 简体中文 · 繁體中文 · 日本語 · 한국어 · Français · Español · Русский · العربية

Malkuth helps automated, long-running programs handle supervision — graceful shutdown, health probes, coordination locks, and rolling updates:

  1. Pluggable transport — JSON-RPC over TCP, WebSocket, or IPC (Unix sockets / named pipes). One Transport trait, dispatched by URL scheme.
  2. Supervised workers — spawn a process, monitor its health, restart it on failure, drain connections before shutdown.
  3. Optional facilities — exit source, probes, heartbeat and drain hooks are traits. Use the defaults or supply your own.
  4. A watchdog CLI — malkuth -- <cmd> wraps any program with file watching, a pod pool, and an L4 sticky reverse proxy.

As a CLI

malkuth [--watch PATH]... [--build CMD | --build-stage NAME=CMD]... [--install CMD]
        [--watch-remote URL#REF] [--remote-poll-secs SECS] [--debounce SECS]
        [--pause-file PATH] [--build-lock PATH]
        [--proxy PUBLIC:LO-HI] [--pod-count N] -- <cmd> [args...]

Run 5 parallel copies of your server (each listening on the PORT env var → they self-assign 3001–3005), fronted by a sticky proxy on 3000:

malkuth --watch ./src --watch ./res \
        --proxy 3000:3000-3999 --pod-count 5 \
        -- cargo run

The proxy routes each client IP to a fixed backend via consistent hashing, so a client keeps hitting the same pod until that pod restarts or scales down — the basis for gray release / rolling restart. On a file change it drains and restarts one pod at a time.

Multi-stage build pipeline (0.3.0)

A trigger — a debounced file change, or an upstream ref movement seen by --watch-remote — can run a composable deploy pipeline instead of a single --build command:

malkuth --watch /usr/local/bin/my-svc \
        --build-lock /run/lock/my-svc-build.lock \
        --pause-file /srv/my-svc/.deploy-pause \
        --watch-remote https://github.com/org/repo.git#master --remote-poll-secs 120 \
        --build-stage deps='pnpm install --frozen-lockfile' \
        --build-stage web='pnpm -C packages/webui build' \
        --build-stage bin='cargo build --release -p core' \
        --install 'sudo /usr/local/lib/my-svc/install.sh' \
        -- /usr/local/bin/my-svc
  • --build-stage NAME=CMD (repeatable): sequential, fail-stop stages. The first non-zero exit skips the rest, the install hook and the restart. --build CMD remains the single anonymous stage (mutually exclusive with --build-stage).
  • --install CMD: privileged install hook that runs after all stages succeeded — point it at a sudoers-narrowed root helper that copies the artifact into the deploy path. Its failure counts as a pipeline failure.
  • --watch-remote URL#REF: polls git ls-remote and fires the same pipeline when the upstream SHA moves (local checkout paths work too; the first poll only primes the baseline). Stages and the install hook receive MALKUTH_TRIGGER=files|remote and, on remote triggers, MALKUTH_REMOTE_SHA.
  • --pause-file PATH: while the file exists, triggers are skipped — the manual-deploy handshake.
  • --build-lock PATH: an exclusive flock held for the pipeline's duration so sibling units or external build scripts sharing one source checkout cannot interleave builds.
  • Failure backoff: consecutive pipeline failures delay the next attempt exponentially (30 s → 15 min cap); one success resets it.

The restart decision is unchanged from the single-command era: restart when the pipeline changed the watched paths' mtimes, or when the supervised binary itself was replaced; a build that produced no visible change skips the restart.

npx (no Rust toolchain required)

Prebuilt binaries are published to npm, so you can run malkuth with a single command — no cargo build:

npx @celestia-island/malkuth --watch ./src -- cargo run
npx @celestia-island/malkuth mcp        # the MCP server (needs the mcp build)

The @celestia-island/malkuth root package pulls the right platform subpackage (-linux-x64 / -linux-arm64 / -darwin-arm64 / -darwin-x64 / -win32-x64) automatically. The Linux binaries are statically linked against musl, so they run on any distro regardless of its glibc version; the macOS and Windows binaries are native. To pin a version:

npx @celestia-island/malkuth@0.1.0 -- cargo run

Windows service

On Windows the daemon runs under the Service Control Manager, and the CLI mirrors the systemd operations:

malkuth service install --config C:\celestia\malkuth.toml --name malkuth
malkuth service start|stop|restart|status|uninstall --name malkuth

service install registers the current malkuth.exe with the launch command daemon --config <path> --service --service-name <name>, starts it automatically at boot, and routes SCM Stop/Shutdown through the same graceful drain path as the systemd unit. The service host reports StartPending → Running → Stopped; supervised children get the drain budget before they are terminated.

As a library

[dependencies]
malkuth = "0.1"
# features: tcp (default) | ws | ipc | signals (default) | worker | probes |
#           file-lock | lease | pg-lock | replica | leader-follower | schema | cli
use std::sync::Arc;
use malkuth::{Client, Router, Server, Supervised, Transport};
use malkuth::transport::TcpTransport;
use serde_json::json;

#[tokio::main]
async fn main() -> std::io::Result<()> {
    // Bind once; build a router with the standard lifecycle RPC + your methods.
    let lis = TcpTransport.listen("tcp://127.0.0.1:0").await?;
    let supervised = Supervised::new().signals();           // OS-signal exit source
    let ctrl = supervised.drain_controller();
    let handler = Arc::new(
        Router::new()
            .lifecycle(ctrl, None)                          // Lifecycle.Drain/Status/...
            .route("ping", |_| Box::pin(async { Ok(json!("pong")) })),
    );
    // Race the server against the exit source, then run drain hooks.
    supervised.serve_rpc_listener(lis, handler).await
}

Need drain triggered by your own logic instead of signals? Implement malkuth::ExitSource and pass it via .exit(...). Want Postgres-backed coordination? The pg-lock feature provides a CoordinationLock backend.

Feature flags

Feature Enables
tcp (default) JSON-RPC over local/remote TCP (tokio::net)
ws JSON-RPC over WebSocket (tokio-tungstenite)
ipc JSON-RPC over local IPC (interprocess)
signals (default) Default OS-signal ExitSource (tokio::signal)
worker Supervised child-process workers (tokio::process)
probes axum /healthz + /readyz router
file-lock POSIX flock CoordinationLock backend (unix)
lease File-lease CoordinationLock with TTL auto-expiry (crash-safe)
pg-lock PostgreSQL pg_advisory_lock backend (tokio-postgres)
replica In-memory InstanceRegistry
leader-follower LeaseLeaderElector (over the lease backend)
schema schemars::JsonSchema derives for wire types
cli The malkuth watchdog binary (pod pool + sticky proxy)

Status

Layers 1–3 (lifecycle/drain, probes, listener handoff) and the JSON-RPC core (codec + server/client + tcp/ws/ipc transports) are implemented and tested end-to-end. The CLI pod pool + sticky proxy is working (e2e-verified). All three CoordinationLock backends (file-lock, lease, pg-lock) and the leader-follower LeaseLeaderElector are implemented. See docs/design/ for the design.

MCP server

Build malkuth with the mcp feature and run the stdio server — it exposes the supervision toolkit to AI coding assistants over the Model Context Protocol:

malkuth mcp

The server advertises seven tools:

Tool What it does
malkuth_supervise Launch a set of workers under the supervisor with restart policies + a sliding-window rate limit. Blocks until they exit or the timeout fires, then returns the final snapshot and a run_id.
malkuth_status Non-blocking per-worker snapshot (id / kind / phase / pid / starttime / uptime / restart count / last error) of every known run, or one run_id. starttime is /proc/<pid>/stat field 22 — the pid-reuse check — and is null between children.
malkuth_approve Register one target-bound approval (proposal_id + worker_id + action restart/drain + decision allow/review/block/unblock — action and decision are both required; an omitted field is refused, never defaulted) for a future action. Since P0b an allow/review must also carry the gate issuer's grant — sig (an ed25519 signature over the canonical malkuth-gate-grant/v2 message binding proposal + worker + action + the worker's live pid/starttime + issued_at + budget) — verified against the built-in key or MALKUTH_GATE_VERIFY_KEY. The v2 grant carries a spend envelope: a drain grant must name budget_secs (1..=300 — the maximum drain budget the approval may ever be spent with; a spend resolving above it answers approval_budget_exceeded and stays unspent), while a restart grant carries none (the field is minted as 0). /v1 signatures are no longer accepted — grants are re-issued by the same coordinated wave (scepter signs v2, devtools' reference oracle pins the same bytes). block records a refusal and unblock lifts exactly that pair — neither authorizes an action, so neither needs a grant. Live 300 s, bound to exactly that pair and action (and, when granted, to that worker incarnation's pid/starttime), and spent by the first action that uses it. block revokes the pair's live approval and refuses any later allow/review for that pair with approval_blocked — only an explicit unblock lifts it (a fresh allow cannot talk past an operator's stop). Records only — never acts. Caller = the executor (celestia-devtools judge-fleet act) after an operator approved the proposal in scepter; malkuth writes nothing back to scepter — the durable row is scepter's judge_actions — but since P1 malkuth keeps its own local gate journal: every spend, block, and refusal is appended as a receipt to the JSONL file named by MALKUTH_GATE_JOURNAL, a spend whose receipt cannot be persisted refuses the action (approval_journal_unavailable), and operator blocks replay from that file at startup. Without the variable the journal lives in memory only (nothing survives a restart).
malkuth_restart Restart one worker by run_id + worker_id + the proposal_id it spends (graceful stop, then a fresh child). Operator budget: 5 accepted restarts per worker per 60 s. Refuses an unknown/ended/draining/already-restarting/over-budget worker, or a missing/expired/spent approval, with a stable error code.
malkuth_drain Graceful (default) or immediate drain of a run, with a bounded wait; idempotent (a re-drain of an already-draining run is a no-op and spends nothing). Requires proposal_id + the judged worker_id it acts on. Any other kind — reload included — is refused with unsupported_kind.
malkuth_logs Bounded tail of one worker's captured stdout/stderr (lines ≤ 500, max_bytes ≤ 64 KiB, minimum 256 — smaller requests are raised to 256) with omission markers.
malkuth_probe HTTP healthz / readyz check against a service URL.

malkuth_restart and malkuth_drain sit behind an approval gate: without a live approval for the exact (proposal_id, worker_id, action) triple they answer approval_required and touch nothing, and a spent approval answers approval_consumed — one approval authorizes one action. approval_expired means the 300 s window closed, approval_blocked means an operator revoked the approval, approval_action_mismatch means the approval was issued for the other action kind (a drain grant never vouches for a restart), and invalid_request means the request itself is malformed. approval_unattested covers every attestation failure at the boundary: a spendable (allow/review) approval submitted without a grant signature, a signature that does not verify, one minted for another worker identity, or a live identity that no longer matches the granted (pid, starttime) at spend time (respawned worker) — in every case nothing is registered, signalled, or spent. approval_epoch_stale refuses a grant outside its clock window (60 s future skew, 300 s TTL), and approval_registry_full means a bounded section is at capacity — the approval registry refuses instead of silently evicting older approvals (a same-pair re-approval still replaces its own entry), and the operator block list refuses its 4097th distinct pair rather than evicting a block. approval_blocked covers the spend against a blocked pair, a later allow/review attempt on it, and a redundant re-block of an already-blocked pair (blocks are refused rather than silently idempotent — the refusal receipt is archived either way). approval_journal_unavailable means the receipt journal refused the write: the spend is refused and the approval left unspent (fail-closed — retry after the journal recovers). invalid_budget covers the library API's explicit budget range (1..=300). approval_budget_exceeded is the v2 envelope refusal: the spend's resolved budget (the library's explicit budget, or the service default 30 on the MCP drain path — deliberately not the operational wait timeout_secs) exceeds what the grant signed. The v2 budget shapes are enforced at the boundary too: a drain grant without budget_secs (or outside 1..=300) and a restart grant with one are invalid_request. decision: review is recorded and passes the gate exactly like allow (it means "a human already looked"); do not map a platform-side "needs review" state onto it — that state must not be approved yet. That is also why both allow and review require a grant — anything that passes the gate must be signed.

The supervising call keeps its blocking semantics; the other arms are non-blocking and safe to issue while it is still outstanding — MCP requests are handled concurrently, so an assistant can observe and steer a run instead of waiting for it to end. Every arm answers a JSON object with an ok field and, on failure, a stable code: unknown_run, unknown_worker, run_finished, worker_stopped, worker_draining, already_restarting, restart_budget_exhausted, unsupported_kind, worker_required, approval_required, approval_expired, approval_consumed, approval_blocked, approval_action_mismatch, approval_unattested, approval_epoch_stale, approval_registry_full, invalid_request, invalid_budget, unsupported_action, unsupported_decision, internal_state_poisoned (and the malkuth_approve refusals approval_decision_required / approval_action_required).

Wire it into an MCP client:

{
  "mcpServers": {
    "malkuth": { "command": "malkuth", "args": ["mcp"] }
  }
}

The mcp feature implies worker + schema; it adds rmcp and a reqwest client for the probe tool.

License

SySL-1.0 (Synthetic Source License). See LICENSE or the SySL website.

MCP Server Deployment

For production MCP deployments, use an auto-restart wrapper to keep the server alive across updates without interrupting the client session.

#!/bin/bash while true; do /path/to/malkuth mcp sleep 0.2 done

How it works

  1. The wrapper runs malkuth mcp in a while true loop.
  2. If the process exits, it restarts within 0.2 seconds.
  3. To update: kill $(pgrep -f "malkuth mcp" | head -1)
  4. malkuth can also supervise other MCP tools — use it as a watcher for the entire MCP toolchain.