kanade_shared/wire/result.rs
1use serde::{Deserialize, Serialize};
2use uuid::Uuid;
3
4/// Prefix injected into the UUIDv5 name string for deriving legacy
5/// `result_id`s. Fixed marker so two backends (or one backend across
6/// restarts) projecting the same legacy payload arrive at the same
7/// id. Tied to the standard `Uuid::NAMESPACE_OID` namespace below.
8/// Bumping this prefix would break dedupe of legacy redeliveries
9/// crossing the upgrade — don't.
10const LEGACY_RESULT_ID_PREFIX: &str = "kanade-issue-19/legacy-result-id:";
11
12#[derive(Serialize, Deserialize, Debug, Clone)]
13pub struct ExecResult {
14 /// v0.29 / Issue #19: agent-minted UUID, unique per (Command, PC)
15 /// run. Replaces `request_id` as the projector's primary key so
16 /// broadcast Commands (commands.all / commands.group.X) — where N
17 /// PCs share one `request_id` — finally persist all N results
18 /// instead of silently dropping all but the first. Pre-v0.29
19 /// agents omit this field; it deserialises as the empty string,
20 /// and [`Self::stable_result_id`] derives a deterministic UUIDv5
21 /// from `(request_id, pc_id)` so legacy payloads (a) get distinct
22 /// ids across broadcast PCs (PC #2's row stops being dropped) and
23 /// (b) get the SAME id on JetStream redelivery (the new `ON
24 /// CONFLICT(result_id) DO NOTHING` path correctly dedupes, so
25 /// `executions.success_count` doesn't double-count across retries).
26 #[serde(default)]
27 pub result_id: String,
28 /// The NATS reply token. Still surfaced for joining back to the
29 /// `kanade run` request/reply path. No longer unique across rows
30 /// (broadcast Commands share it).
31 pub request_id: String,
32 /// v0.29 / Issue #19: back-link to `executions.exec_id`. Copied
33 /// from `Command.exec_id` by the agent. `None` for ad-hoc
34 /// `kanade run` (no deployment) and for results emitted by
35 /// pre-v0.29 agents (decoded via `serde(default)`).
36 #[serde(default, skip_serializing_if = "Option::is_none")]
37 pub exec_id: Option<String>,
38 /// #955: back-link to the parent run's `result_id` for a
39 /// `finalize:` hook's own result row. Set by the agent to the
40 /// triggering run's `result_id` so the SPA can link the
41 /// `<job>__finalize` row to (and from) the run whose collect it
42 /// cleaned up. `None` for every ordinary run and every pre-#955
43 /// payload (`serde(default)` keeps older results decodable).
44 #[serde(default, skip_serializing_if = "Option::is_none")]
45 pub parent_result_id: Option<String>,
46 pub pc_id: String,
47 pub exit_code: i32,
48 /// stdout. Empty string when [`Self::stdout_object`] is set — the
49 /// agent overflowed the bytes into [`crate::kv::OBJECT_RESULT_OUTPUT`]
50 /// because the inline payload would have exceeded NATS's default
51 /// `max_payload` (#227). The backend projector derefs the pointer
52 /// before inserting; SQLite still stores the full text inline so
53 /// the SPA Activity page reads unchanged.
54 pub stdout: String,
55 pub stderr: String,
56 pub started_at: chrono::DateTime<chrono::Utc>,
57 pub finished_at: chrono::DateTime<chrono::Utc>,
58 /// Object Store key under [`crate::kv::OBJECT_RESULT_OUTPUT`] when
59 /// `stdout` overflowed the agent's inline threshold (#227). Set to
60 /// `Some("<request_id>/stdout")` by the agent's outbox drain; the
61 /// backend projector fetches the bytes from that key and uses them
62 /// in place of the (empty) `stdout` field. `None` for the common
63 /// small-stdout case + every pre-#227 payload (`serde(default)`
64 /// keeps older results decodable).
65 #[serde(default, skip_serializing_if = "Option::is_none")]
66 pub stdout_object: Option<String>,
67 /// Sibling of `stdout_object` for the stderr stream. Same key
68 /// shape (`<request_id>/stderr`).
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub stderr_object: Option<String>,
71 /// v0.13: the manifest id that produced this result. Sourced
72 /// from `Command.id` (which is the YAML `manifest.id`, e.g.
73 /// `"inventory-hw"`). Distinct from the per-deploy UUID stored
74 /// in `Command.exec_id`. The results projector uses this to
75 /// look up the manifest's `inventory:` hint and upsert
76 /// `inventory_facts` rows for inventory-tagged jobs.
77 #[serde(default, skip_serializing_if = "Option::is_none")]
78 pub manifest_id: Option<String>,
79 /// #219: Object Store key under [`crate::kv::OBJECT_COLLECTIONS`] for
80 /// the bundle this run collected, when the job carried a `collect:`
81 /// hint and the run succeeded. Set by the agent to
82 /// `Some("<pc_id>/<job_id>/<rfc3339>.zip")` after it zips the
83 /// script's listed files and uploads the archive. `None` for every
84 /// non-collect job + every pre-#219 payload (`serde(default)` keeps
85 /// older results decodable). The SPA Collect page lists / downloads
86 /// these straight from the bucket.
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub collect_object: Option<String>,
89}
90
91/// Synthetic exit code for a run the agent skipped because the
92/// Command's `version` didn't match the `script_current` pin. One of
93/// the four reserved skip codes (124–127): the agent publishes a
94/// normal [`ExecResult`] so the operator can see *why* nothing ran,
95/// but the script itself never executed — consumers that derive state
96/// from a run's output (e.g. the backend's `check_status` projection)
97/// must treat these as "no new evidence", not as a run (#909).
98pub const EXIT_SKIP_VERSION_PIN: i32 = 124;
99/// Synthetic exit code: `deadline_at` passed before the agent could
100/// fire. See [`EXIT_SKIP_VERSION_PIN`] for the shared contract.
101pub const EXIT_SKIP_DEADLINE: i32 = 125;
102/// Synthetic exit code: the script is revoked in
103/// `BUCKET_SCRIPT_STATUS`. See [`EXIT_SKIP_VERSION_PIN`].
104pub const EXIT_SKIP_REVOKED: i32 = 126;
105/// Synthetic exit code: the `staleness.mode: strict` policy suppressed
106/// the fire. See [`EXIT_SKIP_VERSION_PIN`].
107pub const EXIT_SKIP_STALENESS: i32 = 127;
108/// Synthetic exit code: the agent **refused** the command because its
109/// provenance signature did not check out (#1165 stage 3).
110///
111/// Extends the reserved block downwards, because 124–127 was full. It shares
112/// the block's contract — the script never ran, so this is not evidence about
113/// its outcome — but it is not a *skip*: the other four mean "policy said not
114/// now", while this one means "this command was not authorised". The specific
115/// code is what carries that distinction; [`is_synthetic_skip`] deliberately
116/// does not, because every consumer of that predicate is asking the narrower
117/// question of whether the script ran.
118///
119/// Emitting a result at all is the point. `kanade run` waits on
120/// `results.<request_id>`, so a refusal that published nothing would be
121/// indistinguishable from an agent that is simply gone — and the most likely
122/// refusal in practice is an operator's own break-glass command going stale on
123/// a host whose clock is wrong, during an incident, with the backend down and
124/// the obs event stuck in the outbox.
125pub const EXIT_REJECTED_UNSIGNED: i32 = 123;
126
127/// True when `exit_code` is one of the reserved synthetic codes (123–127) —
128/// the agent published this result *instead of* running the script, so it
129/// carries no evidence about the script's outcome.
130pub fn is_synthetic_skip(exit_code: i32) -> bool {
131 (EXIT_REJECTED_UNSIGNED..=EXIT_SKIP_STALENESS).contains(&exit_code)
132}
133
134impl ExecResult {
135 /// Return the `result_id` if the agent supplied one (v0.29+
136 /// payloads always do), otherwise derive a stable UUIDv5 from
137 /// `(request_id, pc_id)`. The projector calls this before INSERT
138 /// so legacy payloads still get a non-empty PK, AND so that
139 /// JetStream redeliveries of the same legacy payload hash to the
140 /// same id and dedupe via `ON CONFLICT`. Per-PC fan-out stays
141 /// distinct (different `pc_id` → different hash).
142 pub fn stable_result_id(&self) -> String {
143 if !self.result_id.is_empty() {
144 return self.result_id.clone();
145 }
146 let name = format!(
147 "{LEGACY_RESULT_ID_PREFIX}{}:{}",
148 self.request_id, self.pc_id
149 );
150 Uuid::new_v5(&Uuid::NAMESPACE_OID, name.as_bytes()).to_string()
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use chrono::TimeZone;
158
159 #[test]
160 fn synthetic_skip_covers_exactly_the_reserved_codes() {
161 for code in [
162 EXIT_REJECTED_UNSIGNED,
163 EXIT_SKIP_VERSION_PIN,
164 EXIT_SKIP_DEADLINE,
165 EXIT_SKIP_REVOKED,
166 EXIT_SKIP_STALENESS,
167 ] {
168 assert!(is_synthetic_skip(code), "{code} is a reserved skip code");
169 }
170 // 123 moved into the reserved block when the signature rejection was
171 // added (#1165) — the block was full at 124-127 and grew downwards.
172 // 122 is the new edge, and pinning both edges is what makes a future
173 // widening a deliberate act rather than an accident.
174 for code in [0, 1, -1, 122, 128, 255] {
175 assert!(!is_synthetic_skip(code), "{code} is a real exit code");
176 }
177 }
178
179 #[test]
180 fn exec_result_round_trips_through_json() {
181 let t0 = chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap();
182 let t1 = chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 5).unwrap();
183 let r = ExecResult {
184 result_id: "result-uuid-1".into(),
185 request_id: "req-1".into(),
186 exec_id: Some("exec-uuid-1".into()),
187 parent_result_id: None,
188 pc_id: "pc-01".into(),
189 exit_code: 0,
190 stdout: "hello\n".into(),
191 stderr: String::new(),
192 started_at: t0,
193 finished_at: t1,
194 stdout_object: None,
195 stderr_object: None,
196 manifest_id: Some("inventory-hw".into()),
197 collect_object: None,
198 };
199 let json = serde_json::to_string(&r).unwrap();
200 let back: ExecResult = serde_json::from_str(&json).unwrap();
201 assert_eq!(back.result_id, r.result_id);
202 assert_eq!(back.request_id, r.request_id);
203 assert_eq!(back.exec_id.as_deref(), Some("exec-uuid-1"));
204 assert_eq!(back.exit_code, r.exit_code);
205 assert_eq!(back.stdout, r.stdout);
206 assert_eq!(back.started_at, t0);
207 assert_eq!(back.finished_at, t1);
208 assert_eq!(back.manifest_id.as_deref(), Some("inventory-hw"));
209 }
210
211 #[test]
212 fn exec_result_without_manifest_id_decodes() {
213 // Older agents (pre-0.13) sent ExecResult with no manifest_id field.
214 let json = r#"{
215 "request_id":"r","pc_id":"x","exit_code":0,
216 "stdout":"","stderr":"",
217 "started_at":"2026-05-16T00:00:00Z",
218 "finished_at":"2026-05-16T00:00:00Z"
219 }"#;
220 let r: ExecResult = serde_json::from_str(json).unwrap();
221 assert_eq!(r.manifest_id, None);
222 }
223
224 #[test]
225 fn exec_result_without_result_id_decodes_empty() {
226 // v0.29 / Issue #19: pre-v0.29 agents don't send `result_id`.
227 // `#[serde(default)]` decodes it as the empty string so the
228 // projector can detect "legacy payload" and call
229 // `stable_result_id()` to derive a deterministic PK.
230 let json = r#"{
231 "request_id":"r","pc_id":"x","exit_code":0,
232 "stdout":"","stderr":"",
233 "started_at":"2026-05-16T00:00:00Z",
234 "finished_at":"2026-05-16T00:00:00Z"
235 }"#;
236 let r: ExecResult = serde_json::from_str(json).unwrap();
237 assert_eq!(r.result_id, "");
238 assert!(r.exec_id.is_none());
239 }
240
241 #[test]
242 fn stable_result_id_is_deterministic_for_legacy_payload() {
243 // Gemini #65 medium fix: legacy redeliveries (same request_id +
244 // pc_id) must hash to the SAME result_id so the projector's
245 // ON CONFLICT(result_id) DO NOTHING dedupes — otherwise
246 // `executions.success_count` double-counts on JetStream ack
247 // timeouts.
248 let json = r#"{
249 "request_id":"r","pc_id":"x","exit_code":0,
250 "stdout":"","stderr":"",
251 "started_at":"2026-05-16T00:00:00Z",
252 "finished_at":"2026-05-16T00:00:00Z"
253 }"#;
254 let a: ExecResult = serde_json::from_str(json).unwrap();
255 let b: ExecResult = serde_json::from_str(json).unwrap();
256 assert_eq!(
257 a.stable_result_id(),
258 b.stable_result_id(),
259 "same legacy payload must hash to the same result_id",
260 );
261 }
262
263 #[test]
264 fn stable_result_id_differs_across_pcs_for_broadcast() {
265 // The other half: a broadcast Command published to two PCs
266 // produces two legacy ExecResults sharing one request_id but
267 // with different pc_ids. Each must get its OWN result_id so
268 // both rows persist (the whole point of Issue #19).
269 let json_a = r#"{
270 "request_id":"shared","pc_id":"pc-1","exit_code":0,
271 "stdout":"","stderr":"",
272 "started_at":"2026-05-16T00:00:00Z",
273 "finished_at":"2026-05-16T00:00:00Z"
274 }"#;
275 let json_b = r#"{
276 "request_id":"shared","pc_id":"pc-2","exit_code":0,
277 "stdout":"","stderr":"",
278 "started_at":"2026-05-16T00:00:00Z",
279 "finished_at":"2026-05-16T00:00:00Z"
280 }"#;
281 let a: ExecResult = serde_json::from_str(json_a).unwrap();
282 let b: ExecResult = serde_json::from_str(json_b).unwrap();
283 assert_ne!(
284 a.stable_result_id(),
285 b.stable_result_id(),
286 "different pc_id must produce a different result_id",
287 );
288 }
289
290 #[test]
291 fn stable_result_id_passes_through_explicit_value() {
292 // v0.29 agents always supply result_id; the helper must
293 // return that as-is (no surprise re-hashing).
294 let r = ExecResult {
295 result_id: "agent-minted-uuid".into(),
296 request_id: "r".into(),
297 exec_id: None,
298 parent_result_id: None,
299 pc_id: "x".into(),
300 exit_code: 0,
301 stdout: String::new(),
302 stderr: String::new(),
303 started_at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
304 finished_at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
305 stdout_object: None,
306 stderr_object: None,
307 manifest_id: None,
308 collect_object: None,
309 };
310 assert_eq!(r.stable_result_id(), "agent-minted-uuid");
311 }
312
313 #[test]
314 fn exec_result_collect_object_round_trips_and_omits_when_absent() {
315 // #219: collect_object is off the wire when None
316 // (skip_serializing_if) so pre-#219 readers stay compatible...
317 let t0 = chrono::Utc.with_ymd_and_hms(2026, 6, 15, 0, 0, 0).unwrap();
318 let mut r = ExecResult {
319 result_id: "r1".into(),
320 request_id: "req".into(),
321 exec_id: None,
322 parent_result_id: None,
323 pc_id: "PC1".into(),
324 exit_code: 0,
325 stdout: String::new(),
326 stderr: String::new(),
327 started_at: t0,
328 finished_at: t0,
329 stdout_object: None,
330 stderr_object: None,
331 manifest_id: Some("collect-diagnostics".into()),
332 collect_object: None,
333 };
334 let json = serde_json::to_string(&r).unwrap();
335 assert!(
336 !json.contains("collect_object"),
337 "collect_object must be absent when None: {json}"
338 );
339 // ...and a set key survives the round-trip.
340 r.collect_object = Some("PC1/collect-diagnostics/20260615T000000Z.zip".into());
341 let back: ExecResult = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
342 assert_eq!(
343 back.collect_object.as_deref(),
344 Some("PC1/collect-diagnostics/20260615T000000Z.zip"),
345 );
346 }
347
348 #[test]
349 fn exec_result_parent_result_id_round_trips_and_omits_when_absent() {
350 // #955: a finalize row carries `parent_result_id`; ordinary runs
351 // leave it None, and it stays off the wire so pre-#955 readers
352 // are unaffected (skip_serializing_if).
353 let t0 = chrono::Utc.with_ymd_and_hms(2026, 7, 4, 0, 0, 0).unwrap();
354 let mut r = ExecResult {
355 result_id: "fin-1".into(),
356 request_id: "req__finalize".into(),
357 exec_id: None,
358 parent_result_id: None,
359 pc_id: "PC1".into(),
360 exit_code: 0,
361 stdout: String::new(),
362 stderr: String::new(),
363 started_at: t0,
364 finished_at: t0,
365 stdout_object: None,
366 stderr_object: None,
367 manifest_id: Some("screenshot-collect__finalize".into()),
368 collect_object: None,
369 };
370 let json = serde_json::to_string(&r).unwrap();
371 assert!(
372 !json.contains("parent_result_id"),
373 "parent_result_id must be absent when None: {json}"
374 );
375 r.parent_result_id = Some("parent-run-uuid".into());
376 let back: ExecResult = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
377 assert_eq!(back.parent_result_id.as_deref(), Some("parent-run-uuid"));
378 }
379}