zenkey-fleet 0.11.1

Fleet engine for keyspace-v2 Zenoh tooling: disciplined fan-in queries, liveliness roster, registry-slice sets, schema-aware decode, live key-tree monitoring — the shared core of zenctl and zengui
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
//! Field intelligence (#223) against a real bus — the acceptance case: a
//! fixture stream with one frozen field is flagged `field-stuck` while
//! `expect --valid-payload` and the rate floor both stay green, and the
//! seen-then-gone / never-declared paths become their findings.
//!
//! The fixture publishers send continuously through each window, so no
//! settle is needed beyond the publisher's matching badge (a fixture that
//! publishes into the void tests the void).
//! Ports are ephemeral (`util::peer_pair`), so two test runs at once
//! cannot collide.

use std::time::Duration;

use zenkey::qos::QosProfile;
use zenkey::schema::{SchemaSet, TypeSchema};
use zenkey_fleet::report::ExpectVerdict;
use zenkey_fleet::{ExpectSpec, FieldSpec, declare_publication, run_expect, run_field};

mod util;
use util::peer_pair;

const ORIGIN: &str = "h-adadadadadad";
const KEY: &str = "v1/h-adadadadadad/state/demo/health";

const SLICE: &str = r#"
[registry]
version = "1.0"
app = "t"
convention = 1
[producer]
name = "demo"
[[subject]]
path = "health"
class = "state"
type = "Health"
ttl_s = 1
"#;

fn health_schema() -> SchemaSet {
    SchemaSet::builder("t")
        .entry(
            "Health",
            TypeSchema::json_schema(serde_json::json!({
                "type": "object",
                "properties": {
                    "temperature_c": {"type": "number"},
                    "seq": {"type": "number"},
                    "opt": {"type": "number"},
                    // An adjacently-tagged enum behind a `$ref` into `$defs`
                    // — what `schemars` emits, and what #384 misread.
                    "value": {"$ref": "#/$defs/Reading"},
                },
                "$defs": {
                    "Reading": {
                        "oneOf": [
                            {"type": "object",
                             "required": ["type", "value"],
                             "properties": {
                                 "type": {"const": "counter", "type": "string"},
                                 "value": {"type": "integer"}}},
                            {"type": "object",
                             "required": ["type", "value"],
                             "properties": {
                                 "type": {"const": "gauge", "type": "string"},
                                 "value": {"type": "number"}}},
                        ],
                    },
                },
            })),
        )
        .build()
}

/// Serve `@rpc/demo/describe` for the fixture origin, so validity is
/// checkable and `field-new` has a declared surface to judge against.
async fn serve_describe(session: &zenoh::Session) -> zenoh::query::Queryable<()> {
    let key = format!("v1/{ORIGIN}/@rpc/demo/describe");
    let payload = health_schema().to_json();
    let reply_key = key.clone();
    session
        .declare_queryable(&key)
        .callback(move |query| {
            let q = query.clone();
            let reply_key = reply_key.clone();
            let payload = payload.clone();
            tokio::spawn(async move {
                q.reply(reply_key, payload).await.unwrap();
            });
        })
        .await
        .expect("describe queryable")
}

/// Publish one JSON document per 100ms tick until dropped, each body built
/// from the tick counter.
fn keep_publishing(
    publication: zenkey_fleet::Publication,
    body: impl Fn(u64) -> serde_json::Value + Send + 'static,
) -> tokio::task::JoinHandle<()> {
    tokio::spawn(async move {
        for i in 0..200u64 {
            let bytes = serde_json::to_vec(&body(i)).expect("fixture body");
            if publication.send(bytes, None).await.is_err() {
                break;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    })
}

fn store_of() -> zenkey_fleet::model::decode::SchemaStore {
    zenkey_fleet::model::decode::SchemaStore::new("", Duration::from_millis(500))
}

fn slices_of() -> zenkey_fleet::SliceSet {
    zenkey_fleet::SliceSet::from_slices(vec![zenkey::parse_slice(SLICE).expect("fixture slice")])
}

/// The #223 acceptance case: `temperature_c` frozen while `seq` moves — the
/// frozen field is flagged `field-stuck` (window and ttl stated), the moving
/// one is not, and the same stream passes `expect --valid-payload` with a
/// rate floor: exactly the failure mode every per-sample check renders green.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_frozen_field_is_flagged_while_validity_and_rate_stay_green() {
    let (a, b) = peer_pair().await;
    let slices = slices_of();
    let _describe = serve_describe(&a).await;

    let publication = declare_publication(&a, KEY, QosProfile::Transition, None)
        .await
        .expect("declare");
    let matching = publication.matching_events().await.expect("events");

    let field = tokio::spawn({
        let b = b.clone();
        let slices = slices.clone();
        async move {
            let spec = FieldSpec {
                selector: KEY.to_string(),
                window: Duration::from_secs(4),
                max_paths: 64,
            };
            run_field(
                &zenkey_fleet::Fleet::new(&b, ""),
                Some(&slices),
                &store_of(),
                &spec,
            )
            .await
        }
    });
    // The field window's subscriber raises the badge; then publish into it.
    assert!(
        tokio::time::timeout(util::SETTLE, matching.recv())
            .await
            .expect("matching within 5s")
            .expect("listener alive")
    );
    let publisher = keep_publishing(
        publication,
        |i| serde_json::json!({"temperature_c": 21.5, "seq": i}),
    );

    let report = field.await.expect("join").expect("run_field");
    assert!(report.samples > 20, "the window saw the stream: {report:?}");
    assert_eq!(report.dropped, 0);
    assert_eq!(report.paths, 2);
    assert_eq!(report.paths_dropped, 0, "nothing hit the bound");

    let stuck: Vec<_> = report
        .findings
        .iter()
        .filter(|f| f.check == zenkey_fleet::report::CheckId::FieldStuck)
        .collect();
    assert_eq!(stuck.len(), 1, "{:?}", report.findings);
    assert_eq!(stuck[0].subject, format!("{KEY} · temperature_c"));
    assert!(
        stuck[0].evidence.contains("ttl_s 1s"),
        "the ttl it is long relative to is stated: {}",
        stuck[0].evidence
    );
    assert!(
        stuck[0].evidence.contains("not a verdict"),
        "{}",
        stuck[0].evidence
    );
    assert!(
        report
            .findings
            .iter()
            .all(|f| !(f.check == zenkey_fleet::report::CheckId::FieldStuck
                && f.subject.ends_with("· seq"))),
        "the moving field is not stuck"
    );
    assert!(
        report
            .findings
            .iter()
            .all(|f| f.check != zenkey_fleet::report::CheckId::FieldNew),
        "both paths are declared by the served schema: {:?}",
        report.findings
    );

    // The same stream is green to every per-sample check: valid payloads at
    // a healthy rate — which is why #223 exists.
    let expect = ExpectSpec {
        selector: KEY.to_string(),
        within: Duration::from_secs(2),
        valid_payload: true,
        rate_min: Some(1.0),
        ..ExpectSpec::default()
    };
    let report = run_expect(
        &zenkey_fleet::Fleet::new(&b, ""),
        Some(&slices),
        &store_of(),
        &expect,
    )
    .await
    .expect("run_expect");
    assert_eq!(
        report.verdict,
        ExpectVerdict::Met,
        "validity and rate stay green over the frozen field: {:?}",
        report.unmet
    );

    publisher.abort();
}

/// The other two findings on one stream: `opt` present early then absent —
/// `field-vanished`, invisible to validation because the schema declares it
/// optional — and `extra`, a path the served schema never declared —
/// `field-new`, schema drift at field granularity.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn vanished_and_undeclared_paths_become_their_findings() {
    let (a, b) = peer_pair().await;
    let slices = slices_of();
    let _describe = serve_describe(&a).await;

    let publication = declare_publication(&a, KEY, QosProfile::Transition, None)
        .await
        .expect("declare");
    let matching = publication.matching_events().await.expect("events");

    let field = tokio::spawn({
        let b = b.clone();
        let slices = slices.clone();
        async move {
            let spec = FieldSpec {
                selector: KEY.to_string(),
                window: Duration::from_secs(3),
                max_paths: 64,
            };
            run_field(
                &zenkey_fleet::Fleet::new(&b, ""),
                Some(&slices),
                &store_of(),
                &spec,
            )
            .await
        }
    });
    assert!(
        tokio::time::timeout(util::SETTLE, matching.recv())
            .await
            .expect("matching within 5s")
            .expect("listener alive")
    );
    let publisher = keep_publishing(publication, |i| {
        if i < 5 {
            serde_json::json!({"seq": i, "opt": 1})
        } else {
            serde_json::json!({"seq": i, "extra": "x"})
        }
    });

    let report = field.await.expect("join").expect("run_field");
    publisher.abort();

    let vanished: Vec<_> = report
        .findings
        .iter()
        .filter(|f| f.check == zenkey_fleet::report::CheckId::FieldVanished)
        .collect();
    assert_eq!(vanished.len(), 1, "{:?}", report.findings);
    assert_eq!(vanished[0].subject, format!("{KEY} · opt"));
    assert!(
        vanished[0].evidence.contains("absent from the last"),
        "{}",
        vanished[0].evidence
    );

    let new: Vec<_> = report
        .findings
        .iter()
        .filter(|f| f.check == zenkey_fleet::report::CheckId::FieldNew)
        .collect();
    assert_eq!(new.len(), 1, "{:?}", report.findings);
    assert_eq!(new[0].subject, format!("{KEY} · extra"));
    assert!(new[0].evidence.contains("Health"), "{}", new[0].evidence);
    // `seq` moved and stayed declared: never a finding.
    assert!(
        report
            .findings
            .iter()
            .all(|f| !f.subject.ends_with("· seq")),
        "{:?}",
        report.findings
    );
}

/// #384, end to end: a producer publishing a tagged enum — through the real
/// `describe` fetch and the real `SchemaStore`, not a hand-built
/// `DeclaredPaths` — produces **no** `field-new`.
///
/// This is pinned here rather than only as a unit test because the unit
/// level is not where the defect showed: the walker was self-consistent, and
/// what was wrong was the surface it handed the judge. A ZenSight baseline
/// run saw 141 warnings in a 15s window over four producers, every one of
/// them a field its own served schema requires — enough noise to make
/// `doctor --fail-on warning` unusable, which is the check defeating itself.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_tagged_enums_fields_are_not_reported_as_drift() {
    let (a, b) = peer_pair().await;
    let slices = slices_of();
    let _describe = serve_describe(&a).await;

    let publication = declare_publication(&a, KEY, QosProfile::Transition, None)
        .await
        .expect("declare");
    let matching = publication.matching_events().await.expect("events");

    let field = tokio::spawn({
        let b = b.clone();
        let slices = slices.clone();
        async move {
            let spec = FieldSpec {
                selector: KEY.to_string(),
                window: Duration::from_secs(3),
                max_paths: 64,
            };
            run_field(
                &zenkey_fleet::Fleet::new(&b, ""),
                Some(&slices),
                &store_of(),
                &spec,
            )
            .await
        }
    });
    assert!(
        tokio::time::timeout(util::SETTLE, matching.recv())
            .await
            .expect("matching within 5s")
            .expect("listener alive")
    );
    // Conforming traffic: every field here is one the served schema declares,
    // `value.type`/`value.value` inside the `oneOf` included.
    let publisher = keep_publishing(
        publication,
        |i| serde_json::json!({"seq": i, "value": {"type": "gauge", "value": i as f64 / 10.0}}),
    );

    let report = field.await.expect("join").expect("run_field");
    publisher.abort();

    let new: Vec<_> = report
        .findings
        .iter()
        .filter(|f| f.check == zenkey_fleet::report::CheckId::FieldNew)
        .collect();
    assert!(
        new.is_empty(),
        "a tagged enum's own fields are declared by its schema, not drift: {new:?}"
    );
    // And the walker did not simply go blind: the paths were observed, and a
    // genuinely undeclared one would still be caught (the sibling test above
    // holds that end).
    let observed: Vec<&str> = report.rows.iter().map(|r| r.path.as_str()).collect();
    assert!(
        observed.contains(&"value.type") && observed.contains(&"value.value"),
        "the fields were seen, and judged clean rather than unseen: {observed:?}"
    );
}

/// The doctor half: `--for` runs the same judges, so the frozen field
/// is a `field-stuck` finding under the stable check-id vocabulary — which is
/// what makes `zenctl watchdog --rule 'doctor field-stuck'` a thing.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_doctor_listen_phase_flags_the_frozen_field() {
    let (a, b) = peer_pair().await;
    let local = zenkey::parse_slice(SLICE).expect("fixture slice");

    let publication = declare_publication(&a, KEY, QosProfile::Transition, None)
        .await
        .expect("declare");
    let publisher = keep_publishing(
        publication,
        |i| serde_json::json!({"temperature_c": 21.5, "seq": i}),
    );

    let report = zenkey_fleet::run_doctor(
        &zenkey_fleet::Fleet::new(&b, ""),
        Some(&zenkey_fleet::SliceSet::from_slices(vec![local.clone()])),
        &zenkey_fleet::DoctorSpec {
            deep: false,
            sample: None,
            timeout: Duration::from_millis(500),
            listen: Some(Duration::from_secs(4)),
        },
    )
    .await
    .expect("run_doctor");
    publisher.abort();

    let stuck: Vec<_> = report
        .findings
        .iter()
        .filter(|f| f.check == zenkey_fleet::report::CheckId::FieldStuck)
        .collect();
    assert_eq!(stuck.len(), 1, "{:?}", report.findings);
    assert_eq!(stuck[0].subject, format!("{KEY} · temperature_c"));
    // Nothing served a describe here, so `field-new` has no declared surface
    // to judge against — unjudgeable is not new (O4).
    assert!(
        report
            .findings
            .iter()
            .all(|f| f.check != zenkey_fleet::report::CheckId::FieldNew)
    );
}