Skip to main content

khive_runtime/daemon/
wire_frames.rs

1use serde::{Deserialize, Serialize};
2#[cfg(unix)]
3use tokio::io::{AsyncReadExt, AsyncWriteExt};
4
5#[cfg(doc)]
6use super::PROTOCOL_VERSION;
7use super::{ConnectionCapSnapshot, DaemonLifecycleSnapshot, RecallLedgerSnapshot};
8#[cfg(unix)]
9use super::{DAEMON_LEXICAL_TIMEOUT_MARKER, MAX_FRAME_BYTES};
10
11/// Request frame sent from a client to the daemon.
12#[derive(Serialize, Deserialize, Default)]
13pub struct DaemonRequestFrame {
14    pub ops: String,
15    /// Parse and inspect the catalog without dispatch, identity, or storage access.
16    #[serde(default)]
17    pub plan: bool,
18    #[serde(skip_serializing_if = "Option::is_none")]
19    pub presentation: Option<String>,
20    #[serde(skip_serializing_if = "Option::is_none")]
21    pub presentation_per_op: Option<Vec<Option<String>>>,
22    /// The client's resolved storage/gate default namespace for this request.
23    ///
24    /// As of protocol version 3 (ADR-096) the daemon serves the request under
25    /// this namespace instead of rejecting on mismatch: a per-request
26    /// identity input, not a same-process-identity assertion.
27    pub namespace: String,
28    /// The client's resolved write-stamp / gate actor identity (ADR-057),
29    /// carried on the frame so the warm daemon stamps writes with the
30    /// *caller's* actor instead of its own baked `actor_id` (ADR-096). `None`
31    /// mints `ActorRef::anonymous()`, matching an unconfigured actor.
32    #[serde(default)]
33    pub actor_id: Option<String>,
34    /// Opaque process provenance resolved in the originating client process.
35    /// It is carried per request because a shared warm daemon's environment
36    /// does not identify the worker that submitted the operation. Protocol v4
37    /// makes this field part of dispatch semantics: a v3 daemon must reject the
38    /// request rather than execute it while silently discarding provenance.
39    #[serde(default, skip_serializing_if = "Option::is_none")]
40    pub process_ref: Option<String>,
41    /// The originating client's working directory, as text. Attribution only, like
42    /// `process_ref`: the daemon records it on the audit rows of an anonymous caller alone,
43    /// bounded and stripped of control characters, and it reaches no gate decision, token or
44    /// stored record. Purely additive: `#[serde(default)]` with no `PROTOCOL_VERSION` bump, and a
45    /// daemon that predates the field ignores it, so its rows carry no directory.
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub client_cwd: Option<String>,
48    /// The client's resolved extra read-visibility namespaces (ADR-007 Rule
49    /// 3b), carried on the frame so the warm daemon widens read scope to
50    /// match the caller's own configuration rather than its own baked
51    /// `visible_namespaces` (ADR-096). A non-`local` `actor_id` joins default
52    /// reads where the registry mints the token (ADR-007 Rev 4 Rule 3b), so
53    /// an empty list still includes that actor in default reads. Explicit
54    /// `namespace=` operations remain scoped to exactly that namespace.
55    #[serde(default)]
56    pub visible_namespaces: Vec<String>,
57    /// Namespaces the client declared it owns (`[actor] owned_namespaces`,
58    /// ADR-021 Delta 1), carried with the caller's identity so the warm daemon
59    /// checks old-row namespaces against the caller's declaration rather than its
60    /// own. Omitted from the wire when empty. A daemon that predates the field
61    /// ignores it, so an owned row is refused there as `old-namespace`: a missing
62    /// declaration produces a refusal, never an admission. Purely additive:
63    /// `#[serde(default)]` with no `PROTOCOL_VERSION` bump.
64    #[serde(default, skip_serializing_if = "Vec::is_empty")]
65    pub owned_namespaces: Vec<String>,
66    /// Fingerprint of the client's engine-coherence config: packs, db target,
67    /// embedders, backend routing, and construction-baked outbound policy.
68    /// Identity fields are carried separately in this frame. The daemon rejects
69    /// requests whose configuration differs, except when its extra-embedder set
70    /// is a superset of the client's and every other field matches. See
71    /// ADR-027 / ADR-049 / ADR-096.
72    #[serde(default)]
73    pub config_id: String,
74    /// IPC protocol version sent by the client. Pre-versioning clients omit
75    /// this field (deserializes to 0). The daemon compares against
76    /// [`PROTOCOL_VERSION`] and rejects mismatches with an explicit error.
77    #[serde(default)]
78    pub protocol_version: u32,
79    /// When `true`, the daemon returns an identity frame (ok=true, result=None)
80    /// immediately after identity validation — without calling the dispatcher.
81    /// Used by the client's under-lock recovery probe to confirm a daemon is
82    /// alive and identity-matching without dispatching any mutating verb.
83    /// Pre-probe clients omit this field (deserializes to false → normal dispatch).
84    #[serde(default)]
85    pub probe_only: bool,
86    /// When `true`, the daemon returns a point-in-time [`MetricsSnapshot`] of
87    /// its server-side gauges (a read-only measurement surface for the
88    /// load/perf harness) instead of dispatching any op. Handled before the
89    /// `config_id` equality reject: a gauge read is process-global and
90    /// namespace/config-agnostic, not a namespaced record operation.
91    /// READ-ONLY — this field is the only input the frame accepts for a
92    /// metrics request; there is no reset or mutation reachable over the
93    /// wire. Pre-metrics clients omit this field (deserializes to `false` →
94    /// normal dispatch, unaffected).
95    #[serde(default)]
96    pub metrics_only: bool,
97    /// Output format for this request (ADR-078). Forwarded to the daemon's
98    /// serialization seam. `None` means use the daemon's resolved default.
99    #[serde(default)]
100    #[serde(skip_serializing_if = "Option::is_none")]
101    pub format: Option<String>,
102    /// Per-operation output format overrides (ADR-078).
103    #[serde(default)]
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub format_per_op: Option<Vec<Option<String>>>,
106    /// Whether this request originated from the agent-facing MCP `request`
107    /// tool (the wire surface). When `true`, the daemon rejects
108    /// `Visibility::Subhandler` verbs: agents must not invoke internal
109    /// subhandlers. When `false` (the default, and the only value any
110    /// operator path sends), subhandlers are allowed: `kkernel exec` and
111    /// other in-process callers are trusted operator surfaces.
112    ///
113    /// This is the origin discriminator, not a daemon-vs-local one: operator
114    /// requests flow through the daemon by default too, so the gate cannot
115    /// key on transport.
116    #[serde(default)]
117    pub from_wire: bool,
118    /// Request-group correlation id (khive#948), echoed back unchanged on
119    /// [`DaemonResponseFrame::request_id`] and stamped into the dispatch's
120    /// audit event (`resource.request_id`) so a benchmark harness can join
121    /// its own pre-send sample to the server-side audit row for the same
122    /// request. Agent-facing MCP requests always carry one: the bridge keeps a
123    /// caller-supplied value or mints an opaque nonzero value when absent.
124    /// Operator-built/probe frames may still use `None`. Purely additive —
125    /// `#[serde(default)]` matches `metrics_only`/`format`/`format_per_op`
126    /// precedent, with no `PROTOCOL_VERSION` bump.
127    #[serde(default)]
128    #[serde(skip_serializing_if = "Option::is_none")]
129    pub request_id: Option<u64>,
130}
131
132/// A dispatch failure whose domain outcome remains available to the transport.
133#[derive(Debug, Clone)]
134pub struct DaemonDispatchError {
135    pub message: String,
136    pub error_detail: serde_json::Value,
137}
138
139/// Per-field container limit, asserted equal to the request parser's bound by MCP.
140pub const ERROR_DETAIL_NESTING_DEPTH_LIMIT: usize = 64;
141
142/// Whether a JSON value fits the shared per-field container nesting limit.
143pub fn error_detail_value_within_limit(value: &serde_json::Value) -> bool {
144    let mut pending = vec![(value, 0_usize)];
145    while let Some((value, depth)) = pending.pop() {
146        match value {
147            serde_json::Value::Array(items) if depth < ERROR_DETAIL_NESTING_DEPTH_LIMIT => {
148                pending.extend(items.iter().map(|child| (child, depth + 1)));
149            }
150            serde_json::Value::Object(fields) if depth < ERROR_DETAIL_NESTING_DEPTH_LIMIT => {
151                pending.extend(fields.values().map(|child| (child, depth + 1)));
152            }
153            serde_json::Value::Array(_) | serde_json::Value::Object(_) => return false,
154            _ => {}
155        }
156    }
157    true
158}
159
160/// Discard an owned JSON value without recursing through nested containers.
161pub fn drop_error_detail_iteratively(value: serde_json::Value) {
162    let mut pending = vec![value];
163    while let Some(value) = pending.pop() {
164        match value {
165            serde_json::Value::Array(items) => pending.extend(items),
166            serde_json::Value::Object(fields) => pending.extend(fields.into_values()),
167            _ => {}
168        }
169    }
170}
171
172impl DaemonDispatchError {
173    /// Missing or unrecognized disposition from a legacy implementation is unknown.
174    pub fn new(message: impl Into<String>, error_detail: Option<serde_json::Value>) -> Self {
175        let message = message.into();
176        let mut fields = match error_detail {
177            Some(serde_json::Value::Object(fields)) => fields,
178            Some(data) => serde_json::Map::from_iter([("data".to_string(), data)]),
179            None => serde_json::Map::new(),
180        };
181        let disposition = match fields
182            .get("domain_disposition")
183            .and_then(serde_json::Value::as_str)
184        {
185            Some("committed") => crate::DomainDisposition::Committed,
186            Some("not_committed") => crate::DomainDisposition::NotCommitted,
187            _ => crate::DomainDisposition::Unknown,
188        };
189        if disposition != crate::DomainDisposition::Committed {
190            if let Some(result) = fields.remove("domain_result") {
191                drop_error_detail_iteratively(result);
192            }
193        }
194        let rejected: Vec<String> = fields
195            .iter()
196            .filter(|(_, value)| !error_detail_value_within_limit(value))
197            .map(|(name, _)| name.clone())
198            .collect();
199        let omitted_result = rejected.iter().any(|name| name == "domain_result");
200        let omitted_detail = !rejected.is_empty();
201        for name in rejected {
202            if let Some(value) = fields.remove(&name) {
203                drop_error_detail_iteratively(value);
204            }
205        }
206        let mut error_detail = serde_json::Value::Object(fields);
207        if error_detail["kind"].as_str().is_none() {
208            error_detail["kind"] = serde_json::json!("internal");
209        }
210        if error_detail["message"].as_str().is_none() {
211            error_detail["message"] = serde_json::json!(message);
212        }
213        error_detail["domain_disposition"] = serde_json::json!(disposition.as_str());
214        if omitted_detail {
215            error_detail["code"] = serde_json::json!(if omitted_result {
216                "result_too_deep"
217            } else {
218                "error_detail_too_deep"
219            });
220        }
221        Self {
222            message,
223            error_detail,
224        }
225    }
226}
227
228/// Response frame sent from the daemon back to a client.
229#[derive(Serialize, Deserialize, Debug)]
230pub struct DaemonResponseFrame {
231    pub ok: bool,
232    pub result: Option<String>,
233    pub error: Option<String>,
234    /// Additive failure metadata; legacy protocol-v4 peers still read `error` as text.
235    /// On a successful response, `{"lexical_timeout":true}` is a daemon-only
236    /// diagnostic that old clients ignore and new clients log locally.
237    #[serde(default, skip_serializing_if = "Option::is_none")]
238    pub error_detail: Option<serde_json::Value>,
239    pub namespace_mismatch: bool,
240    /// Set when the request's `config_id` does not match the daemon's. Like
241    /// `namespace_mismatch`, this signals the client to fall back to local
242    /// dispatch rather than execute under a different runtime/config.
243    #[serde(default)]
244    pub config_mismatch: bool,
245    /// The `config_id` the daemon dispatched under, echoed back so the client
246    /// can positively confirm the result came from a matching runtime. A
247    /// pre-`config_id` daemon omits this field (deserializes to `None`), which
248    /// the client treats as a mismatch and falls back to local dispatch — this
249    /// closes the upgrade window where a new restricted client could otherwise
250    /// trust a still-warm legacy daemon's broader registry.
251    #[serde(default)]
252    pub served_config_id: Option<String>,
253    /// Set when the client's `protocol_version` does not match the daemon's
254    /// [`PROTOCOL_VERSION`]. The client must treat this as a hard error and
255    /// surface the human-readable `error` field rather than falling back to
256    /// local dispatch (which would hide the version skew).
257    #[serde(default)]
258    pub version_mismatch: bool,
259    /// The daemon's [`PROTOCOL_VERSION`], echoed in error responses so the
260    /// client can include both sides in the diagnostic message. Pre-versioning
261    /// daemons omit this field (deserializes to 0).
262    #[serde(default)]
263    pub daemon_protocol_version: u32,
264    /// Populated when the request set `metrics_only: true`: a point-in-time
265    /// snapshot of the daemon's server-side gauges. `None` on every other
266    /// response, and on any response from a daemon that predates this field
267    /// (client-side back-compat via `#[serde(default)]`, matching
268    /// `served_config_id`'s upgrade-window handling above).
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub metrics: Option<MetricsSnapshot>,
271    /// Echo of the request's `request_id` (khive#948), present whenever the
272    /// frame that produced this response carried one — including on every
273    /// error/denied arm, not only success, so a client can join a failure
274    /// the same way it joins a success. `#[serde(default)]` so an older
275    /// daemon's response (predating this field) deserializes to `None`
276    /// rather than a parse error.
277    #[serde(default)]
278    pub request_id: Option<u64>,
279}
280
281/// Move the private dispatch signal out of the result before any client can
282/// observe it. Unmarked results retain their exact bytes. The marked result
283/// was serialized from a JSON Value by the MCP server, so reserializing after
284/// removal reproduces its public envelope. The marker's escaped frame cost
285/// equals `error_detail:{"lexical_timeout":true}`, keeping the server's exact
286/// frame-fit calculation valid after this move.
287#[cfg(unix)]
288pub(super) fn take_daemon_lexical_timeout_marker(
289    raw: String,
290) -> (String, Option<serde_json::Value>) {
291    if !raw.contains(DAEMON_LEXICAL_TIMEOUT_MARKER) {
292        return (raw, None);
293    }
294    let Ok(mut value) = serde_json::from_str::<serde_json::Value>(&raw) else {
295        return (raw, None);
296    };
297    let Some(fields) = value.as_object_mut() else {
298        return (raw, None);
299    };
300    if !fields
301        .get("results")
302        .is_some_and(serde_json::Value::is_array)
303    {
304        return (raw, None);
305    }
306    let Some(marker) = fields.remove(DAEMON_LEXICAL_TIMEOUT_MARKER) else {
307        return (raw, None);
308    };
309    let detail =
310        (marker.as_bool() == Some(true)).then(|| serde_json::json!({"lexical_timeout": true}));
311    (
312        serde_json::to_string(&value).expect("serde_json::Value is serializable"),
313        detail,
314    )
315}
316
317/// One checkpoint store in this daemon's fixed topology. IDs are process-local:
318/// `main` or `secondary:<index>` in dispatcher order. The basename is display-only,
319/// not an identity; no directory path is exposed. Restart/topology changes reset
320/// the interpretation of interval deltas.
321#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
322#[serde(default)]
323pub struct CheckpointStoreMetrics {
324    pub store_id: String,
325    pub role: String,
326    pub database: Option<String>,
327    #[serde(flatten)]
328    pub timing: khive_db::checkpoint::CheckpointTiming,
329}
330
331/// Point-in-time snapshot of the daemon's server-side gauges — the
332/// load/perf harness read-surface (measurement substrate, not a product feature).
333///
334/// Every field here is a **server-side** gauge reachable from `handle_conn`
335/// without any mutation: [`khive_storage::tx_registry`] (ADR-091 Plank 0,
336/// process-global singleton), the main pool's backend-keyed routine WAL
337/// sample and process TRUNCATE counters (`khive_db::checkpoint`), and the
338/// ADR-067 Component A write queue depth/latest writer-stage sample. There is
339/// no reset reachable through this type or through [`DaemonRequestFrame`] —
340/// gauges out, nothing in.
341#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq)]
342pub struct MetricsSnapshot {
343    /// Launch mode and the current lifecycle of this daemon incarnation.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub lifecycle: Option<DaemonLifecycleSnapshot>,
346    /// Last-observed WAL page count from the periodic checkpoint tick.
347    /// `None` when the checkpoint task has never ticked in this process
348    /// (for example, an in-memory dispatcher with no pool, or a daemon that
349    /// just started and hasn't hit its first tick yet).
350    pub wal_pages: Option<u64>,
351    /// Logical frames present in the WAL at the main backend's most recent
352    /// periodic PASSIVE checkpoint. Kept separate from physical allocation.
353    #[serde(default)]
354    pub wal_log_frames: Option<u64>,
355    /// Frames backfilled by that same periodic PASSIVE pass.
356    #[serde(default)]
357    pub wal_checkpointed_frames: Option<u64>,
358    /// Logical frames still pending after that pass (`log - checkpointed`).
359    #[serde(default)]
360    pub wal_pending_frames: Option<u64>,
361    /// Physical `-wal` sidecar bytes captured at the same routine tick.
362    #[serde(default)]
363    pub wal_physical_bytes: Option<u64>,
364    /// Wall-clock timestamp of the routine WAL sample, for staleness checks.
365    #[serde(default)]
366    pub wal_observed_at_unix_ms: Option<u64>,
367    /// Cumulative actual routine PASSIVE calls for each store this daemon
368    /// checkpoints. Microseconds preserve sub-millisecond costs; max is since
369    /// process start, not an interval maximum. Counters saturate rather than wrap.
370    #[serde(default)]
371    pub wal_checkpoint_stores: Vec<CheckpointStoreMetrics>,
372    /// Total WAL TRUNCATE escalation attempts (ADR-091 Plank 2) made in this
373    /// process's lifetime, regardless of whether they succeeded in reclaiming
374    /// pages.
375    pub wal_truncate_attempts: u64,
376    /// Current consecutive-failure count for TRUNCATE attempts that failed to
377    /// bring the WAL back below `warn_pages`; resets to 0 the next time an
378    /// attempt clears it.
379    pub wal_truncate_consecutive_failures: u64,
380    /// Total checkpoint ticks skipped because the dedicated checkpoint
381    /// connection was unavailable (ADR-091 checkpoint-pressure telemetry),
382    /// across this process's lifetime. `#[serde(default)]` so an older client
383    /// decoding a newer daemon's snapshot (or vice versa) does not fail.
384    #[serde(default)]
385    pub wal_checkpoint_skipped_ticks: u64,
386    /// Current consecutive-skip run length; 0 once the next tick is observed.
387    #[serde(default)]
388    pub wal_checkpoint_consecutive_skips: u64,
389    /// WAL page count last known at the time of the most recent skip, if any
390    /// skip has occurred yet in this process.
391    #[serde(default)]
392    pub wal_checkpoint_last_skip_wal_pages: Option<u64>,
393    /// Age, in microseconds, of the oldest currently-open transaction
394    /// registry entry (ADR-091 Plank 0). `None` when no transaction is
395    /// currently open.
396    pub oldest_pinned_tx_micros: Option<u64>,
397    /// Diagnostic label of the oldest currently-open transaction registry
398    /// entry, if any and if it was registered with one.
399    pub oldest_pinned_tx_label: Option<String>,
400    /// Number of currently open transaction registry entries.
401    pub open_tx_count: usize,
402    /// Current write-queue backlog depth (ADR-067 Component A): requests
403    /// enqueued but not yet accepted by the `WriterTask` drain loop. `None`
404    /// unless the write queue is enabled (`KHIVE_WRITE_QUEUE=1`) and a
405    /// file-backed pool is available.
406    pub write_queue_depth: Option<usize>,
407    /// The write queue's configured bounded capacity
408    /// (`PoolConfig::write_queue_capacity`), gated the same as
409    /// `write_queue_depth`.
410    pub write_queue_capacity: Option<usize>,
411    /// Latest completed writer-task span: bounded-channel admission/backlog.
412    #[serde(default)]
413    pub write_last_queue_wait_micros: Option<u64>,
414    /// Latest completed writer-task span: `BEGIN IMMEDIATE` acquisition.
415    #[serde(default)]
416    pub write_last_transaction_acquire_micros: Option<u64>,
417    /// Latest completed writer-task span: application transaction body.
418    #[serde(default)]
419    pub write_last_body_micros: Option<u64>,
420    /// Latest completed writer-task span: SQLite COMMIT/fsync phase.
421    #[serde(default)]
422    pub write_last_commit_micros: Option<u64>,
423    /// Whole latest writer-task request span, retained for compatibility and
424    /// comparison with the decomposed stages.
425    #[serde(default)]
426    pub write_last_total_micros: Option<u64>,
427    /// Wall-clock timestamp of the writer-stage sample.
428    #[serde(default)]
429    pub write_last_observed_at_unix_ms: Option<u64>,
430    /// Connection cap of the daemon socket this snapshot was served from.
431    /// `None` from a daemon that predates the cap and when no listener owns
432    /// the connection.
433    #[serde(default, skip_serializing_if = "Option::is_none")]
434    pub connections: Option<ConnectionCapSnapshot>,
435    /// Bounds and counts of the best-effort recall serve-ledger tasks.
436    /// `None` from a daemon that predates the bound.
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub recall_ledger: Option<RecallLedgerSnapshot>,
439}
440
441// ── framing ───────────────────────────────────────────────────────────────────
442
443/// Read one length-prefixed frame (4-byte BE u32 length + JSON bytes).
444#[cfg(unix)]
445pub async fn read_frame<R>(stream: &mut R) -> std::io::Result<Vec<u8>>
446where
447    R: tokio::io::AsyncRead + Unpin,
448{
449    let mut len_buf = [0u8; 4];
450    stream.read_exact(&mut len_buf).await?;
451    let len = u32::from_be_bytes(len_buf) as usize;
452    if len > MAX_FRAME_BYTES {
453        return Err(std::io::Error::new(
454            std::io::ErrorKind::InvalidData,
455            format!("daemon frame of {len} bytes exceeds {MAX_FRAME_BYTES} cap"),
456        ));
457    }
458    let mut buf = vec![0u8; len];
459    stream.read_exact(&mut buf).await?;
460    Ok(buf)
461}
462
463#[cfg(unix)]
464fn initial_frame_timeout_error() -> std::io::Error {
465    std::io::Error::new(
466        std::io::ErrorKind::TimedOut,
467        "daemon initial request frame read timed out",
468    )
469}
470
471#[cfg(unix)]
472pub(super) async fn read_initial_frame<R>(
473    stream: &mut R,
474    deadline: tokio::time::Instant,
475) -> std::io::Result<Vec<u8>>
476where
477    R: tokio::io::AsyncRead + Unpin,
478{
479    // Tokio polls the inner future before checking its timer. A frame already
480    // buffered when a delayed connection task first runs would otherwise pass
481    // even though its acceptance-time deadline has expired.
482    if tokio::time::Instant::now() >= deadline {
483        return Err(initial_frame_timeout_error());
484    }
485    let raw = tokio::time::timeout_at(deadline, read_frame(stream))
486        .await
487        .map_err(|_| initial_frame_timeout_error())??;
488    if tokio::time::Instant::now() >= deadline {
489        return Err(initial_frame_timeout_error());
490    }
491    Ok(raw)
492}
493
494/// Write one length-prefixed frame.
495#[cfg(unix)]
496pub async fn write_frame<W>(stream: &mut W, payload: &[u8]) -> std::io::Result<()>
497where
498    W: tokio::io::AsyncWrite + Unpin,
499{
500    if payload.len() > MAX_FRAME_BYTES {
501        return Err(std::io::Error::new(
502            std::io::ErrorKind::InvalidData,
503            format!(
504                "daemon frame of {} bytes exceeds {MAX_FRAME_BYTES} cap",
505                payload.len()
506            ),
507        ));
508    }
509    let len = (payload.len() as u32).to_be_bytes();
510    stream.write_all(&len).await?;
511    stream.write_all(payload).await?;
512    stream.flush().await?;
513    Ok(())
514}