mlua_swarm/core/config.rs
1//! EngineCfg + LongHoldConfig.
2
3use std::time::Duration;
4
5/// Built-in default for [`EngineCfg::worker_token_ttl_secs`] — 1800s
6/// (30 min). Deliberately short: a worker token is handed out of the
7/// process, so its TTL is the only bound on the capability. See the field
8/// doc for when to raise it.
9pub const DEFAULT_WORKER_TOKEN_TTL_SECS: u64 = 1800;
10
11fn random_token_secret() -> Vec<u8> {
12 let mut buf = vec![0u8; 32];
13 getrandom::fill(&mut buf).expect("OS RNG unavailable");
14 buf
15}
16
17/// Lock acquisition + max-hold guard configuration.
18#[derive(Debug, Clone)]
19pub struct EngineCfg {
20 /// When `true`, `Engine::with_state` never retries on a busy lock — it
21 /// fails fast with `EngineError::LockBusy` on the very first
22 /// `try_lock` miss instead of backing off and retrying.
23 pub try_only: bool,
24 /// Max number of `try_lock` retries before giving up with
25 /// `EngineError::LockBusyAfterRetry` (ignored when `try_only = true`).
26 pub max_retry: u32,
27 /// Linear backoff step (ms) between retries; the sleep duration for
28 /// attempt `n` is `backoff_ms_step * (n + 1)`.
29 pub backoff_ms_step: u64,
30 /// R4 guard threshold: if a single `with_state` closure holds the lock
31 /// longer than this (ms), `with_state` reports a long operation having
32 /// leaked inside the lock in violation of the R3 discipline — it emits
33 /// a `tracing::warn!` with `op` / `elapsed_ms` / `max_hold_ms` and
34 /// continues, unless [`Self::max_hold_panic`] escalates the overrun to
35 /// a panic.
36 pub max_hold_ms: u128,
37 /// When `true`, an R4 overrun panics (after the warn) instead of
38 /// continuing. Off by default in every build: the guard measures
39 /// wall-clock hold time, which on a loaded shared runner includes
40 /// scheduler preemption, so a threshold panic is structurally flaky in
41 /// CI — a trivial closure was observed held for 186ms > 50ms on a
42 /// GitHub macOS runner, and the panic killed the server under test.
43 /// Enable locally when hunting a suspected R3 violation (a long op /
44 /// blocking call leaked inside the lock).
45 pub max_hold_panic: bool,
46 /// HMAC secret used by `TokenSigner` to sign/verify `CapToken`s.
47 ///
48 /// `Default` generates this fresh (32 random bytes from the OS RNG) on
49 /// every call when the caller does not supply one — set it explicitly
50 /// for tokens to stay valid across restarts, or when multiple
51 /// independently-constructed engines/signers must accept each other's
52 /// tokens.
53 pub token_secret: Vec<u8>,
54 /// Long-hold session tuning (idle keepalive, heartbeat cadence).
55 pub long_hold: LongHoldConfig,
56 /// TTL (seconds) stamped into every worker capability token the engine
57 /// mints — both the `dispatch_attempt` path and the ordinary-spawn path
58 /// of `dispatch_run_ctx` read this one value.
59 ///
60 /// Unlike an Operator token, a worker token **leaves the process**: it is
61 /// handed to a SubAgent as `Authorization: Bearer <CapToken::encode()>`,
62 /// so nothing downstream can revoke it and this TTL is the only effective
63 /// bound on the capability. That is why it stays short by default
64 /// (`1800` = 30 min) rather than tracking the run TTL.
65 ///
66 /// The flip side: a Step whose SubAgent runs longer than this fails
67 /// authentication mid-flight. When raising the run TTL for long Steps
68 /// (`default_run_ttl` / `sync_timeout_secs`), raise this alongside it —
69 /// a run TTL on its own cannot lift the worker-side ceiling.
70 pub worker_token_ttl_secs: u64,
71 /// Worker recursive spawn depth ceiling (guards against unbounded spawn).
72 ///
73 /// When `Ctx.meta.runtime["spawn_depth"]` has already reached this value
74 /// and a Worker token tries to call `start_task`, the engine raises
75 /// `EngineError::SpawnDepthExceeded`. `0` = root (a task launched
76 /// directly by an Operator); `4` = default, which allows four levels of
77 /// nested sub-tasks.
78 pub max_spawn_depth: u32,
79 /// GH #31: threshold/mode/storage tuning for delivering an oversized
80 /// baked `system_prompt` by reference (`WorkerPayload.system_ref`)
81 /// instead of inline (`WorkerPayload.system`). See
82 /// [`SystemRefConfig`].
83 pub system_ref: SystemRefConfig,
84 /// Policy that governs how submit-time projection sinks react when a
85 /// fail-open condition is encountered (missing `work_dir`/
86 /// `project_root`, `OutputStore` write error, adapter materialize
87 /// error, state lookup error). Default [`CheckPolicy::Warn`]
88 /// preserves the pre-existing warn-and-continue behaviour of every
89 /// call site — see [`CheckPolicy`] for the semantics of the other
90 /// two modes and [`apply_check_policy`](crate::core::engine::apply_check_policy)
91 /// for the shared decision helper. Per-run override is threaded via
92 /// `POST /v1/tasks` (subtask-1c).
93 pub check_policy: CheckPolicy,
94}
95
96// `CheckPolicy` is the Swarm IF SoT type; it lives in the
97// `mlua-swarm-schema` crate (enum relocation) and is
98// re-exported here so every existing path
99// (`crate::core::config::CheckPolicy`, `EngineCfg.check_policy`,
100// `TaskSpec.check_policy`, `apply_check_policy`) keeps its type path
101// unchanged. There is exactly ONE definition — no duplicate enum / `From`
102// bridge — and the wire form (`"silent"` / `"warn"` / `"strict"`) is
103// byte-identical to the pre-relocation form. See the schema crate for the
104// full mode semantics.
105pub use mlua_swarm_schema::CheckPolicy;
106
107impl EngineCfg {
108 /// Strict variant: `try_only = true` (no retry/backoff) and a tight
109 /// `max_hold_ms = 10`. Useful for tests that want lock contention to
110 /// fail fast rather than silently wait.
111 pub fn strict() -> Self {
112 Self {
113 try_only: true,
114 max_retry: 0,
115 backoff_ms_step: 0,
116 max_hold_ms: 10,
117 ..Self::default()
118 }
119 }
120
121 /// Relaxed variant: higher `max_retry` / `backoff_ms_step` /
122 /// `max_hold_ms` than the default, for environments where lock
123 /// contention is expected to be more frequent or operations slower.
124 pub fn relaxed() -> Self {
125 Self {
126 try_only: false,
127 max_retry: 10,
128 backoff_ms_step: 50,
129 max_hold_ms: 200,
130 ..Self::default()
131 }
132 }
133}
134
135impl Default for EngineCfg {
136 /// Baseline configuration: bounded retry with backoff, a generous
137 /// (but non-zero) `max_hold_ms`, `max_spawn_depth = 4`, and
138 /// `worker_token_ttl_secs = 1800` (the pre-config hard-coded value).
139 /// `token_secret` is generated fresh per call — see the field doc.
140 fn default() -> Self {
141 Self {
142 try_only: false,
143 max_retry: 3,
144 backoff_ms_step: 10,
145 max_hold_ms: 50,
146 max_hold_panic: false,
147 token_secret: random_token_secret(),
148 long_hold: LongHoldConfig::default(),
149 worker_token_ttl_secs: DEFAULT_WORKER_TOKEN_TTL_SECS,
150 max_spawn_depth: 4,
151 system_ref: SystemRefConfig::default(),
152 check_policy: CheckPolicy::default(),
153 }
154 }
155}
156
157/// GH #31: server-side config for how a baked `system_prompt` too large
158/// to inline is delivered instead — see `Engine::fetch_worker_payload`'s
159/// threshold branch (`crate::core::engine`) for where this is consumed.
160/// Single server-side setting, not per-request: every fetch of a given
161/// `(task_id, attempt)` sees the same `mode` and `threshold_bytes`.
162#[derive(Debug, Clone)]
163pub struct SystemRefConfig {
164 /// Byte length of the baked `system` string above which
165 /// `Engine::fetch_worker_payload{,_trusted}` switches from inlining
166 /// the value (`WorkerPayload.system`) to a reference
167 /// (`WorkerPayload.system_ref`). Default (`25 * 1024`, 25 KiB)
168 /// matches `bp_doctor`'s existing WARN threshold
169 /// (`AGENT_MD_DEFAULT_WARN_BYTES` in
170 /// `crates/mlua-swarm-cli/src/mcp.rs`) — the same SubAgent
171 /// context-window headroom rationale that threshold documents
172 /// applies here to inline-vs-reference delivery.
173 pub threshold_bytes: usize,
174 /// Which [`crate::types::SystemRefMode`] an over-threshold response
175 /// uses to deliver its content.
176 pub mode: crate::types::SystemRefMode,
177 /// Directory `SystemRefMode::File` writes rendered `system` bodies
178 /// into (`<store_dir>/<task_id>-<attempt>.md`). No eviction policy —
179 /// files accumulate for the process lifetime (explicitly out of
180 /// scope; see the risk note on `Engine::fetch_worker_payload`).
181 pub store_dir: std::path::PathBuf,
182}
183
184impl Default for SystemRefConfig {
185 /// `threshold_bytes = 25 * 1024`, `mode = SystemRefMode::File`,
186 /// `store_dir = std::env::temp_dir().join("mse-system-ref")`.
187 fn default() -> Self {
188 Self {
189 threshold_bytes: 25 * 1024,
190 mode: crate::types::SystemRefMode::File,
191 store_dir: std::env::temp_dir().join("mse-system-ref"),
192 }
193 }
194}
195
196/// Tuning for long-running (suspend/resume-capable) sessions and tasks —
197/// how long a poll/suspend may hold, how often heartbeats are expected,
198/// and whether idle tasks are kept alive across a detach.
199#[derive(Debug, Clone)]
200pub struct LongHoldConfig {
201 /// Default wait duration used by long-poll style waits when the
202 /// caller does not specify one explicitly.
203 pub default_hold: Duration,
204 /// Upper bound on how long a single suspend/poll wait may block.
205 pub max_hold: Duration,
206 /// Expected cadence of `Engine::heartbeat` calls from an attached
207 /// session; consumed by `Engine::start_detach_loop`.
208 pub heartbeat_interval: Duration,
209 /// Number of missed heartbeat intervals tolerated before the detach
210 /// loop flips a session's `attached` flag to `false`.
211 pub heartbeat_miss_threshold: u32,
212 /// When `true`, a task survives (its state is retained) across a
213 /// session detach, so a later reattach can resume it in place.
214 pub keepalive_on_idle: bool,
215}
216
217impl Default for LongHoldConfig {
218 fn default() -> Self {
219 Self {
220 default_hold: Duration::from_secs(3600),
221 max_hold: Duration::from_secs(48 * 3600),
222 heartbeat_interval: Duration::from_secs(300),
223 heartbeat_miss_threshold: 3,
224 keepalive_on_idle: true,
225 }
226 }
227}