khive-wire-protocol 0.21.0

Frame protocol for khive's tailnet wire transport: frame kinds, handshake state machine, wire error taxonomy, and the length-prefixed codec (ADR-137). No async I/O, no transport.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
use super::*;

#[test]
fn empty_operation_id_is_rejected_at_deserialization() {
    // An empty operation id can never be a unique caller-
    // generated id, so the wire form rejects it. In-memory
    // construction stays unrestricted (checked below).
    let err = serde_json::from_str::<OperationId>(r#""""#).unwrap_err();
    assert!(
        err.to_string().contains("non-empty"),
        "unexpected error: {err}"
    );
    assert_eq!(OperationId::from(""), OperationId("".to_string()));
}

#[test]
fn non_empty_operation_id_round_trips() {
    let id: OperationId = serde_json::from_str(r#""op-1""#).unwrap();
    assert_eq!(id, OperationId::from("op-1"));
    assert_eq!(serde_json::to_string(&id).unwrap(), r#""op-1""#);
}

#[test]
fn direct_serde_rejects_every_invalid_wire_shape() {
    let frames = [
        Frame::Handshake {
            version: ProtocolVersion::new(0),
        },
        Frame::HandshakeAck {
            version: ProtocolVersion::new(0),
        },
        Frame::Request {
            id: OperationId::from(""),
            ops: "stats()".to_string(),
            deadline_ms: None,
            namespace: None,
            actor_id: None,
            visible_namespaces: None,
        },
        Frame::Response {
            id: OperationId::from(""),
            result: serde_json::json!({}).into(),
        },
        Frame::Error {
            id: Some(OperationId::from("")),
            code: crate::error::WireErrorCode::Internal,
            message: "failure".to_string(),
            unrecognized_code: None,
        },
        Frame::Cancel {
            id: OperationId::from(""),
        },
        Frame::Subscribe {
            id: OperationId::from(""),
            topic: "a.b".to_string(),
            resume_cursor: None,
        },
        Frame::SubscribeAck {
            id: OperationId::from(""),
            topic: "a.b".to_string(),
            start_cursor: 0,
        },
        Frame::Unsubscribe {
            id: OperationId::from(""),
            topic: "a.b".to_string(),
        },
        Frame::UnsubscribeAck {
            id: OperationId::from(""),
            topic: "a.b".to_string(),
        },
        Frame::Error {
            id: Some(OperationId::from("op-1")),
            code: crate::error::WireErrorCode::FrameTooLarge,
            message: "too big".to_string(),
            unrecognized_code: None,
        },
        Frame::Error {
            id: None,
            code: crate::error::WireErrorCode::Cancelled,
            message: "cancelled".to_string(),
            unrecognized_code: None,
        },
        Frame::Error {
            id: None,
            code: crate::error::WireErrorCode::Internal,
            message: "future".to_string(),
            unrecognized_code: Some("future_code_xyz".to_string()),
        },
    ];

    for frame in frames {
        assert!(
            serde_json::to_vec(&frame).is_err(),
            "invalid frame {:?} serialized successfully",
            frame.kind()
        );
    }
}

#[test]
fn direct_serde_matches_encode_payload_for_a_valid_frame() {
    let frame = Frame::Request {
        id: OperationId::from("op-1"),
        ops: "stats()".to_string(),
        deadline_ms: Some(5000),
        namespace: Some("default".to_string()),
        actor_id: Some("actor".to_string()),
        visible_namespaces: Some(vec!["default".to_string()]),
    };
    let direct = serde_json::to_vec(&frame).unwrap();
    let encoded = crate::codec::encode_frame(&frame).unwrap();
    assert_eq!(direct, &encoded[crate::codec::LENGTH_PREFIX_BYTES..]);
    assert_eq!(serde_json::from_slice::<Frame>(&direct).unwrap(), frame);
}

#[test]
fn unknown_kind_through_direct_serde_is_rejected() {
    let err = serde_json::from_str::<Frame>(r#"{"kind":"ping"}"#).unwrap_err();
    assert!(err.to_string().contains("unknown frame kind"));
}

#[test]
fn client_to_server_kinds_are_all_frame_kinds() {
    for kind in CLIENT_TO_SERVER_KINDS {
        assert!(
            FRAME_KINDS.contains(kind),
            "client-to-server kind {kind:?} is missing from FRAME_KINDS"
        );
    }
}

#[test]
fn direct_serde_rejects_connection_terminal_error_carrying_an_id() {
    // The id/scope rule is enforced inside the visitor itself, so a
    // DIRECT serde decode — bypassing `decode_payload` entirely —
    // cannot represent an inconsistent error frame either.
    let err = serde_json::from_str::<Frame>(
        r#"{"kind":"error","id":"op-1","code":"frame_too_large","message":"too big"}"#,
    )
    .unwrap_err();
    let message = err.to_string();
    assert!(
        message.contains("id/scope rule"),
        "unexpected error: {message}"
    );
    assert!(message.contains("frame_too_large"), "error: {message}");
    assert!(message.contains("op-1"), "error: {message}");
}

#[test]
fn direct_serde_rejects_request_terminal_error_without_an_id() {
    let err = serde_json::from_str::<Frame>(
        r#"{"kind":"error","code":"cancelled","message":"cancelled"}"#,
    )
    .unwrap_err();
    let message = err.to_string();
    assert!(
        message.contains("id/scope rule"),
        "unexpected error: {message}"
    );
    assert!(message.contains("cancelled"), "error: {message}");
}

#[test]
fn direct_serde_accepts_both_consistent_error_scopes() {
    let connection_terminal: Frame = serde_json::from_str(
        r#"{"kind":"error","code":"unsupported_version","message":"no common version"}"#,
    )
    .unwrap();
    assert!(matches!(connection_terminal, Frame::Error { id: None, .. }));

    let request_terminal: Frame = serde_json::from_str(
        r#"{"kind":"error","id":"op-9","code":"deadline_exceeded","message":"too slow"}"#,
    )
    .unwrap();
    match request_terminal {
        Frame::Error {
            id,
            code,
            unrecognized_code,
            ..
        } => {
            assert_eq!(id, Some(OperationId::from("op-9")));
            assert_eq!(code, crate::error::WireErrorCode::DeadlineExceeded);
            assert!(unrecognized_code.is_none());
        }
        other => panic!("expected an error frame, got {other:?}"),
    }
}

#[test]
fn direct_serde_fills_unrecognized_code_for_an_unknown_wire_code() {
    // ADR-137 Amendment 1 Decision 5 keeps this fallback only with an id;
    // the superseded id-less acceptance is now tested as a refusal below.
    let frame: Frame = serde_json::from_str(
        r#"{"kind":"error","id":"op-7","code":"future_code_xyz","message":"from newer peer"}"#,
    )
    .unwrap();
    assert_eq!(
        frame,
        Frame::Error {
            id: Some(OperationId::from("op-7")),
            code: crate::error::WireErrorCode::Internal,
            message: "from newer peer".to_string(),
            unrecognized_code: Some("future_code_xyz".to_string()),
        }
    );
    assert_eq!(
        crate::error::WireErrorCode::Internal.terminal_scope(),
        crate::error::TerminalScope::Request
    );
    assert!(serde_json::to_vec(&frame).is_err());
    assert_eq!(
        crate::codec::encode_frame(&frame).unwrap_err(),
        crate::codec::CodecError::FallbackFrameNotEncodable {
            code: "future_code_xyz".to_string(),
        }
    );
}

#[test]
fn direct_serde_rejects_unknown_wire_code_without_an_id() {
    // Decision 5 is enforced on Frame itself, independently of a client
    // or server gate. Both raw serde and Value-driven entry points agree.
    let json = r#"{"kind":"error","code":"future_code_xyz","message":"from newer peer"}"#;
    let value: serde_json::Value = serde_json::from_str(json).unwrap();
    let results = [
        ("raw serde", serde_json::from_str::<Frame>(json)),
        ("Value serde", serde_json::from_value::<Frame>(value)),
    ];
    for (entrypoint, result) in results {
        assert!(
            result.is_err(),
            "D5 {entrypoint} accepted an id-less unknown error code"
        );
        let error = result.unwrap_err();
        let message = error.to_string();
        assert!(
            message.contains("id/scope rule"),
            "unexpected error: {message}"
        );
        assert!(
            message.contains("unknown error code requires an operation id"),
            "unexpected error: {message}"
        );
    }
}

#[test]
fn direct_serde_leaves_unrecognized_code_none_for_a_literal_internal() {
    // `"internal"` is a closed-set member, not a fallback: the
    // diagnostic must stay `None` so the encode side does not mistake
    // an honest `internal` for a decoded-fallback frame.
    let frame: Frame =
        serde_json::from_str(r#"{"kind":"error","id":"op-1","code":"internal","message":"boom"}"#)
            .unwrap();
    match frame {
        Frame::Error {
            unrecognized_code, ..
        } => assert!(unrecognized_code.is_none()),
        other => panic!("expected an error frame, got {other:?}"),
    }
}

#[test]
fn direct_serde_rejects_duplicate_envelope_keys_before_field_validation() {
    // Amendment 1 Decision 4 supersedes lossy root-map last-wins behavior.
    // Missing/unknown fields and invalid first values must not hide a duplicate.
    for raw in [
        r#"{"kind":"cancel","kind":"cancel","id":"op-1"}"#,
        r#"{"kind":"cancel","id":"","id":"op-1"}"#,
        r#"{"kind":"cancel","id":"op-1","\u0069d":"op-1"}"#,
        r#"{"kind":"cancel","id":"op-1","extra":1,"extra":2}"#,
        r#"{"extra":1,"extra":2}"#,
    ] {
        let error = serde_json::from_str::<Frame>(raw).unwrap_err();
        assert!(
            error.to_string().contains("duplicate envelope field"),
            "D4 must reject the duplicate before field validation: {raw}: {error}"
        );
    }
}

#[test]
fn direct_serde_distinguishes_omitted_optional_fields_from_null() {
    let cases = [
        (
            "deadline_ms",
            r#"{"kind":"request","id":"op-1","ops":"stats()","deadline_ms":null}"#,
            r#"{"kind":"request","id":"op-1","ops":"stats()"}"#,
        ),
        (
            "namespace",
            r#"{"kind":"request","id":"op-1","ops":"stats()","namespace":null}"#,
            r#"{"kind":"request","id":"op-1","ops":"stats()"}"#,
        ),
        (
            "actor_id",
            r#"{"kind":"request","id":"op-1","ops":"stats()","actor_id":null}"#,
            r#"{"kind":"request","id":"op-1","ops":"stats()"}"#,
        ),
        (
            "visible_namespaces",
            r#"{"kind":"request","id":"op-1","ops":"stats()","visible_namespaces":null}"#,
            r#"{"kind":"request","id":"op-1","ops":"stats()"}"#,
        ),
        (
            "resume_cursor",
            r#"{"kind":"subscribe","id":"op-1","topic":"a.b","resume_cursor":null}"#,
            r#"{"kind":"subscribe","id":"op-1","topic":"a.b"}"#,
        ),
        (
            "id",
            r#"{"kind":"error","id":null,"code":"unsupported_version","message":"unsupported"}"#,
            r#"{"kind":"error","code":"unsupported_version","message":"unsupported"}"#,
        ),
    ];
    for (field, raw, omitted) in cases {
        // Prove the otherwise equivalent omitted form is a valid frame first.
        let healthy: Frame = serde_json::from_str(omitted).unwrap();
        assert!(serde_json::to_value(healthy).unwrap().get(field).is_none());
        let error = serde_json::from_str::<Frame>(raw).unwrap_err();
        assert!(error.to_string().contains("null"), "D4 {field}: {error}");
    }

    // The same names, nulls and repeated members inside opaque JSON are data.
    let response: Frame = serde_json::from_str(
        r#"{"kind":"response","id":"op-1","result":{"namespace":null,"id":1,"id":2}}"#,
    )
    .unwrap();
    let Frame::Response { result, .. } = response else {
        panic!("expected response")
    };
    assert_eq!(
        result.to_value().unwrap().get("namespace"),
        Some(&serde_json::Value::Null)
    );
    let response_null: Frame =
        serde_json::from_str(r#"{"kind":"response","id":"op-1","result":null}"#).unwrap();
    let Frame::Response { result, .. } = response_null else {
        panic!("expected response")
    };
    assert_eq!(result.to_value().unwrap(), serde_json::Value::Null);
    let event: Frame = serde_json::from_str(
        r#"{"kind":"event","topic":"a.b","cursor":1,"occurred_at":"2026-08-04T11:00:00Z","payload":{"resume_cursor":null,"id":1,"id":2}}"#,
    ).unwrap();
    let Frame::Event { payload, .. } = event else {
        panic!("expected event")
    };
    assert_eq!(
        payload.to_value().unwrap().get("resume_cursor"),
        Some(&serde_json::Value::Null)
    );
}

#[test]
fn direct_serde_requires_an_object_event_payload() {
    let healthy: Frame = serde_json::from_str(
        r#"{"kind":"event","topic":"a.b","cursor":1,"occurred_at":"2026-08-04T11:00:00Z","payload":{"nested":[null,true]}}"#,
    ).unwrap();
    assert!(matches!(healthy, Frame::Event { payload, .. } if payload.is_object()));

    for payload in ["[]", r#""text""#, "1", "true", "null"] {
        let raw = format!(
            r#"{{"kind":"event","topic":"a.b","cursor":1,"occurred_at":"2026-08-04T11:00:00Z","payload":{payload}}}"#
        );
        let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
        for (entrypoint, result) in [
            ("raw serde", serde_json::from_str::<Frame>(&raw)),
            ("Value serde", serde_json::from_value::<Frame>(value)),
        ] {
            let error = result.unwrap_err();
            assert!(
                error
                    .to_string()
                    .contains("event payload must be a JSON object"),
                "D10 {entrypoint} returned an unrelated refusal: {error}"
            );
        }
    }
}

#[test]
fn direct_and_codec_serialization_require_an_object_event_payload() {
    // Invalid local frames are constructed directly. D10 decode must not be
    // used as setup for an encode-only refusal witness.
    let event = |payload: serde_json::Value| Frame::Event {
        topic: "a.b".to_string(),
        cursor: 1,
        occurred_at: "2026-08-04T11:00:00Z".to_string(),
        payload: payload.into(),
    };
    let healthy = event(serde_json::json!({"nested": [null, true]}));
    let direct = serde_json::to_vec(&healthy).unwrap();
    let wire = crate::codec::encode_frame(&healthy).unwrap();
    assert_eq!(direct, &wire[crate::codec::LENGTH_PREFIX_BYTES..]);
    let response_null = Frame::Response {
        id: OperationId::from("op-1"),
        result: serde_json::Value::Null.into(),
    };
    serde_json::to_vec(&response_null).unwrap();
    crate::codec::encode_frame(&response_null).unwrap();

    for payload in [
        serde_json::json!([]),
        serde_json::json!("text"),
        serde_json::json!(1),
        serde_json::json!(true),
        serde_json::Value::Null,
    ] {
        let frame = event(payload);
        let direct_error = serde_json::to_vec(&frame).unwrap_err();
        assert!(
            direct_error
                .to_string()
                .contains("payload must be a JSON object"),
            "D10 direct serialization returned an unrelated refusal: {direct_error}"
        );
        match crate::codec::encode_frame(&frame).unwrap_err() {
            crate::codec::CodecError::InvalidFields { kind, detail } => {
                assert_eq!(kind, "event");
                assert_eq!(detail, "payload must be a JSON object");
            }
            other => panic!("D10 expected typed event payload refusal, got {other:?}"),
        }
    }
}

#[test]
fn direct_serde_requires_a_positive_present_request_deadline() {
    for (member, expected) in [
        ("", None),
        (",\"deadline_ms\":1", Some(1_u64)),
        (",\"deadline_ms\":18446744073709551615", Some(u64::MAX)),
    ] {
        let raw = format!(r#"{{"kind":"request","id":"op-1","ops":"stats()"{member}}}"#);
        let value: serde_json::Value = serde_json::from_str(&raw).unwrap();
        for frame in [
            serde_json::from_str::<Frame>(&raw).unwrap(),
            serde_json::from_value::<Frame>(value).unwrap(),
        ] {
            let Frame::Request { deadline_ms, .. } = frame else {
                panic!("expected request")
            };
            assert_eq!(deadline_ms, expected);
        }
    }

    // ADR-137's positive-integer floor rejects only zero in the u64 domain.
    let raw = r#"{"kind":"request","id":"op-1","ops":"stats()","deadline_ms":0}"#;
    let value: serde_json::Value = serde_json::from_str(raw).unwrap();
    for (entrypoint, result) in [
        ("raw serde", serde_json::from_str::<Frame>(raw)),
        ("Value serde", serde_json::from_value::<Frame>(value)),
    ] {
        let error = result.unwrap_err();
        assert!(
            error
                .to_string()
                .contains("deadline_ms must be a positive integer"),
            "zero deadline {entrypoint} returned an unrelated refusal: {error}"
        );
    }
}

#[test]
fn direct_and_codec_serialization_require_positive_request_deadlines() {
    let request = |deadline_ms| Frame::Request {
        id: OperationId::from("op-1"),
        ops: "stats()".to_string(),
        deadline_ms,
        namespace: None,
        actor_id: None,
        visible_namespaces: None,
    };
    for deadline_ms in [None, Some(1), Some(u64::MAX)] {
        let frame = request(deadline_ms);
        let direct = serde_json::to_vec(&frame).unwrap();
        let wire = crate::codec::encode_frame(&frame).unwrap();
        assert_eq!(direct, &wire[crate::codec::LENGTH_PREFIX_BYTES..]);
        assert_eq!(serde_json::from_slice::<Frame>(&direct).unwrap(), frame);
    }

    // Construct invalid local state directly; decode refuses this shape.
    let zero = request(Some(0));
    let direct_error = serde_json::to_vec(&zero).unwrap_err();
    assert!(
        direct_error
            .to_string()
            .contains("deadline_ms must be a positive integer"),
        "zero deadline direct serialization returned an unrelated refusal: {direct_error}"
    );
    match crate::codec::encode_frame(&zero).unwrap_err() {
        crate::codec::CodecError::InvalidFields { kind, detail } => {
            assert_eq!(kind, "request");
            assert_eq!(detail, "deadline_ms must be a positive integer");
        }
        other => panic!("zero deadline expected typed request refusal, got {other:?}"),
    }
}