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 pub pc_id: String,
39 pub exit_code: i32,
40 /// stdout. Empty string when [`Self::stdout_object`] is set — the
41 /// agent overflowed the bytes into [`crate::kv::OBJECT_RESULT_OUTPUT`]
42 /// because the inline payload would have exceeded NATS's default
43 /// `max_payload` (#227). The backend projector derefs the pointer
44 /// before inserting; SQLite still stores the full text inline so
45 /// the SPA Activity page reads unchanged.
46 pub stdout: String,
47 pub stderr: String,
48 pub started_at: chrono::DateTime<chrono::Utc>,
49 pub finished_at: chrono::DateTime<chrono::Utc>,
50 /// Object Store key under [`crate::kv::OBJECT_RESULT_OUTPUT`] when
51 /// `stdout` overflowed the agent's inline threshold (#227). Set to
52 /// `Some("<request_id>/stdout")` by the agent's outbox drain; the
53 /// backend projector fetches the bytes from that key and uses them
54 /// in place of the (empty) `stdout` field. `None` for the common
55 /// small-stdout case + every pre-#227 payload (`serde(default)`
56 /// keeps older results decodable).
57 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub stdout_object: Option<String>,
59 /// Sibling of `stdout_object` for the stderr stream. Same key
60 /// shape (`<request_id>/stderr`).
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub stderr_object: Option<String>,
63 /// v0.13: the manifest id that produced this result. Sourced
64 /// from `Command.id` (which is the YAML `manifest.id`, e.g.
65 /// `"inventory-hw"`). Distinct from the per-deploy UUID stored
66 /// in `Command.exec_id`. The results projector uses this to
67 /// look up the manifest's `inventory:` hint and upsert
68 /// `inventory_facts` rows for inventory-tagged jobs.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub manifest_id: Option<String>,
71 /// #219: Object Store key under [`crate::kv::OBJECT_COLLECTIONS`] for
72 /// the bundle this run collected, when the job carried a `collect:`
73 /// hint and the run succeeded. Set by the agent to
74 /// `Some("<pc_id>/<job_id>/<rfc3339>.zip")` after it zips the
75 /// script's listed files and uploads the archive. `None` for every
76 /// non-collect job + every pre-#219 payload (`serde(default)` keeps
77 /// older results decodable). The SPA Collect page lists / downloads
78 /// these straight from the bucket.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub collect_object: Option<String>,
81}
82
83/// Synthetic exit code for a run the agent skipped because the
84/// Command's `version` didn't match the `script_current` pin. One of
85/// the four reserved skip codes (124–127): the agent publishes a
86/// normal [`ExecResult`] so the operator can see *why* nothing ran,
87/// but the script itself never executed — consumers that derive state
88/// from a run's output (e.g. the backend's `check_status` projection)
89/// must treat these as "no new evidence", not as a run (#909).
90pub const EXIT_SKIP_VERSION_PIN: i32 = 124;
91/// Synthetic exit code: `deadline_at` passed before the agent could
92/// fire. See [`EXIT_SKIP_VERSION_PIN`] for the shared contract.
93pub const EXIT_SKIP_DEADLINE: i32 = 125;
94/// Synthetic exit code: the script is revoked in
95/// `BUCKET_SCRIPT_STATUS`. See [`EXIT_SKIP_VERSION_PIN`].
96pub const EXIT_SKIP_REVOKED: i32 = 126;
97/// Synthetic exit code: the `staleness.mode: strict` policy suppressed
98/// the fire. See [`EXIT_SKIP_VERSION_PIN`].
99pub const EXIT_SKIP_STALENESS: i32 = 127;
100
101/// True when `exit_code` is one of the reserved synthetic skip codes
102/// (124–127) — the agent published this result *instead of* running
103/// the script, so it carries no evidence about the script's outcome.
104pub fn is_synthetic_skip(exit_code: i32) -> bool {
105 (EXIT_SKIP_VERSION_PIN..=EXIT_SKIP_STALENESS).contains(&exit_code)
106}
107
108impl ExecResult {
109 /// Return the `result_id` if the agent supplied one (v0.29+
110 /// payloads always do), otherwise derive a stable UUIDv5 from
111 /// `(request_id, pc_id)`. The projector calls this before INSERT
112 /// so legacy payloads still get a non-empty PK, AND so that
113 /// JetStream redeliveries of the same legacy payload hash to the
114 /// same id and dedupe via `ON CONFLICT`. Per-PC fan-out stays
115 /// distinct (different `pc_id` → different hash).
116 pub fn stable_result_id(&self) -> String {
117 if !self.result_id.is_empty() {
118 return self.result_id.clone();
119 }
120 let name = format!(
121 "{LEGACY_RESULT_ID_PREFIX}{}:{}",
122 self.request_id, self.pc_id
123 );
124 Uuid::new_v5(&Uuid::NAMESPACE_OID, name.as_bytes()).to_string()
125 }
126}
127
128#[cfg(test)]
129mod tests {
130 use super::*;
131 use chrono::TimeZone;
132
133 #[test]
134 fn synthetic_skip_covers_exactly_the_reserved_codes() {
135 for code in [
136 EXIT_SKIP_VERSION_PIN,
137 EXIT_SKIP_DEADLINE,
138 EXIT_SKIP_REVOKED,
139 EXIT_SKIP_STALENESS,
140 ] {
141 assert!(is_synthetic_skip(code), "{code} is a reserved skip code");
142 }
143 for code in [0, 1, -1, 123, 128, 255] {
144 assert!(!is_synthetic_skip(code), "{code} is a real exit code");
145 }
146 }
147
148 #[test]
149 fn exec_result_round_trips_through_json() {
150 let t0 = chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap();
151 let t1 = chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 5).unwrap();
152 let r = ExecResult {
153 result_id: "result-uuid-1".into(),
154 request_id: "req-1".into(),
155 exec_id: Some("exec-uuid-1".into()),
156 pc_id: "pc-01".into(),
157 exit_code: 0,
158 stdout: "hello\n".into(),
159 stderr: String::new(),
160 started_at: t0,
161 finished_at: t1,
162 stdout_object: None,
163 stderr_object: None,
164 manifest_id: Some("inventory-hw".into()),
165 collect_object: None,
166 };
167 let json = serde_json::to_string(&r).unwrap();
168 let back: ExecResult = serde_json::from_str(&json).unwrap();
169 assert_eq!(back.result_id, r.result_id);
170 assert_eq!(back.request_id, r.request_id);
171 assert_eq!(back.exec_id.as_deref(), Some("exec-uuid-1"));
172 assert_eq!(back.exit_code, r.exit_code);
173 assert_eq!(back.stdout, r.stdout);
174 assert_eq!(back.started_at, t0);
175 assert_eq!(back.finished_at, t1);
176 assert_eq!(back.manifest_id.as_deref(), Some("inventory-hw"));
177 }
178
179 #[test]
180 fn exec_result_without_manifest_id_decodes() {
181 // Older agents (pre-0.13) sent ExecResult with no manifest_id field.
182 let json = r#"{
183 "request_id":"r","pc_id":"x","exit_code":0,
184 "stdout":"","stderr":"",
185 "started_at":"2026-05-16T00:00:00Z",
186 "finished_at":"2026-05-16T00:00:00Z"
187 }"#;
188 let r: ExecResult = serde_json::from_str(json).unwrap();
189 assert_eq!(r.manifest_id, None);
190 }
191
192 #[test]
193 fn exec_result_without_result_id_decodes_empty() {
194 // v0.29 / Issue #19: pre-v0.29 agents don't send `result_id`.
195 // `#[serde(default)]` decodes it as the empty string so the
196 // projector can detect "legacy payload" and call
197 // `stable_result_id()` to derive a deterministic PK.
198 let json = r#"{
199 "request_id":"r","pc_id":"x","exit_code":0,
200 "stdout":"","stderr":"",
201 "started_at":"2026-05-16T00:00:00Z",
202 "finished_at":"2026-05-16T00:00:00Z"
203 }"#;
204 let r: ExecResult = serde_json::from_str(json).unwrap();
205 assert_eq!(r.result_id, "");
206 assert!(r.exec_id.is_none());
207 }
208
209 #[test]
210 fn stable_result_id_is_deterministic_for_legacy_payload() {
211 // Gemini #65 medium fix: legacy redeliveries (same request_id +
212 // pc_id) must hash to the SAME result_id so the projector's
213 // ON CONFLICT(result_id) DO NOTHING dedupes — otherwise
214 // `executions.success_count` double-counts on JetStream ack
215 // timeouts.
216 let json = r#"{
217 "request_id":"r","pc_id":"x","exit_code":0,
218 "stdout":"","stderr":"",
219 "started_at":"2026-05-16T00:00:00Z",
220 "finished_at":"2026-05-16T00:00:00Z"
221 }"#;
222 let a: ExecResult = serde_json::from_str(json).unwrap();
223 let b: ExecResult = serde_json::from_str(json).unwrap();
224 assert_eq!(
225 a.stable_result_id(),
226 b.stable_result_id(),
227 "same legacy payload must hash to the same result_id",
228 );
229 }
230
231 #[test]
232 fn stable_result_id_differs_across_pcs_for_broadcast() {
233 // The other half: a broadcast Command published to two PCs
234 // produces two legacy ExecResults sharing one request_id but
235 // with different pc_ids. Each must get its OWN result_id so
236 // both rows persist (the whole point of Issue #19).
237 let json_a = r#"{
238 "request_id":"shared","pc_id":"pc-1","exit_code":0,
239 "stdout":"","stderr":"",
240 "started_at":"2026-05-16T00:00:00Z",
241 "finished_at":"2026-05-16T00:00:00Z"
242 }"#;
243 let json_b = r#"{
244 "request_id":"shared","pc_id":"pc-2","exit_code":0,
245 "stdout":"","stderr":"",
246 "started_at":"2026-05-16T00:00:00Z",
247 "finished_at":"2026-05-16T00:00:00Z"
248 }"#;
249 let a: ExecResult = serde_json::from_str(json_a).unwrap();
250 let b: ExecResult = serde_json::from_str(json_b).unwrap();
251 assert_ne!(
252 a.stable_result_id(),
253 b.stable_result_id(),
254 "different pc_id must produce a different result_id",
255 );
256 }
257
258 #[test]
259 fn stable_result_id_passes_through_explicit_value() {
260 // v0.29 agents always supply result_id; the helper must
261 // return that as-is (no surprise re-hashing).
262 let r = ExecResult {
263 result_id: "agent-minted-uuid".into(),
264 request_id: "r".into(),
265 exec_id: None,
266 pc_id: "x".into(),
267 exit_code: 0,
268 stdout: String::new(),
269 stderr: String::new(),
270 started_at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
271 finished_at: chrono::Utc.with_ymd_and_hms(2026, 5, 16, 0, 0, 0).unwrap(),
272 stdout_object: None,
273 stderr_object: None,
274 manifest_id: None,
275 collect_object: None,
276 };
277 assert_eq!(r.stable_result_id(), "agent-minted-uuid");
278 }
279
280 #[test]
281 fn exec_result_collect_object_round_trips_and_omits_when_absent() {
282 // #219: collect_object is off the wire when None
283 // (skip_serializing_if) so pre-#219 readers stay compatible...
284 let t0 = chrono::Utc.with_ymd_and_hms(2026, 6, 15, 0, 0, 0).unwrap();
285 let mut r = ExecResult {
286 result_id: "r1".into(),
287 request_id: "req".into(),
288 exec_id: None,
289 pc_id: "PC1".into(),
290 exit_code: 0,
291 stdout: String::new(),
292 stderr: String::new(),
293 started_at: t0,
294 finished_at: t0,
295 stdout_object: None,
296 stderr_object: None,
297 manifest_id: Some("collect-diagnostics".into()),
298 collect_object: None,
299 };
300 let json = serde_json::to_string(&r).unwrap();
301 assert!(
302 !json.contains("collect_object"),
303 "collect_object must be absent when None: {json}"
304 );
305 // ...and a set key survives the round-trip.
306 r.collect_object = Some("PC1/collect-diagnostics/20260615T000000Z.zip".into());
307 let back: ExecResult = serde_json::from_str(&serde_json::to_string(&r).unwrap()).unwrap();
308 assert_eq!(
309 back.collect_object.as_deref(),
310 Some("PC1/collect-diagnostics/20260615T000000Z.zip"),
311 );
312 }
313}