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