dora-core 1.2.0

`dora` goal is to be a low latency, composable, and distributed data flow.
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
//! `@schema` reassembly for `dora topic`: rebuilding the self-describing Arrow
//! IPC stream of each output sample a node publishes on zenoh, with the cache
//! that lets a late watcher decode schema-once batches.
//!
//! The daemon's debug subscriber uses this to feed `dora topic`. It lives here
//! so that a CLI subscribing to zenoh directly can rebuild the same frames
//! (dora-rs/dora#4025).

use std::sync::Arc;

/// Cached `@schema` bytes (keyed by their FNV-1a hash, most-recent last) for
/// one debug-watched output, shared between the `@schema` subscriber callback
/// and the data task. Retains several schemas — mirroring the node receive
/// path's `InputDecoder` retention — so an output that interleaves schemas
/// (e.g. schema-once batches of schema A between large full streams of schema
/// B) doesn't have its schema-once schema clobbered, and a stale `@schema`
/// history-query result arriving after an in-band prime can't evict the
/// fresher schema (both stay retained).
pub type DebugSchemaCache = Arc<std::sync::Mutex<Vec<(u64, Vec<u8>)>>>;

/// Retention bound for [`DebugSchemaCache`], matching the node receive path's
/// `InputDecoder` (see `MAX_RETAINED_SCHEMAS` in dora-node-api's `ipc_encode`).
pub const MAX_DEBUG_SCHEMAS: usize = 8;

/// Remember `schema` for `hash` in the debug cache (most-recent last), evicting
/// the oldest entry beyond [`MAX_DEBUG_SCHEMAS`]. An already-retained hash is
/// moved to the back without re-copying its bytes.
pub fn retain_debug_schema(cache: &mut Vec<(u64, Vec<u8>)>, hash: u64, schema: &[u8]) {
    if let Some(pos) = cache.iter().position(|(h, _)| *h == hash) {
        let entry = cache.remove(pos);
        cache.push(entry);
        return;
    }
    cache.push((hash, schema.to_vec()));
    if cache.len() > MAX_DEBUG_SCHEMAS {
        cache.remove(0);
    }
}

/// Remember a schema block received on an output's `@schema` key. It is keyed
/// by its FNV-1a hash, the hash the producer tags its schema-once batches with
/// (see [`crate::schema_once::schema_block_and_hash`]).
pub fn retain_published_schema(cache: &mut Vec<(u64, Vec<u8>)>, schema: &[u8]) {
    retain_debug_schema(cache, dora_message::metadata::fnv1a(schema), schema);
}

/// Rebuild a self-describing Arrow IPC stream for a `dora topic` debug frame.
///
/// Small node→node outputs travel as schema-once batches: the schema is
/// published once on the `@schema` subtopic and each data sample carries only
/// the schema-less record batch (`DoraNode::publish_schema_once`). The
/// `dora topic` decoder expects a full self-describing stream, so for such a
/// batch we prepend the retained schema block — concatenation reconstructs the
/// exact original stream (`schema_block ++ batch_slice == full_stream`).
///
/// Returns `None` (drop the inspection frame) when the batch is schema-once but
/// no schema matching its `SCHEMA_HASH` has been retained yet — a transient,
/// inspection-only gap. A full self-describing payload (no `SCHEMA_HASH`) is
/// forwarded as-is.
pub fn rebuild_debug_topic_stream(
    cache: &mut Vec<(u64, Vec<u8>)>,
    parameters: &dora_message::metadata::MetadataParameters,
    payload: &[u8],
) -> Option<Vec<u8>> {
    use dora_message::metadata::{SCHEMA_HASH, get_integer_param};

    match get_integer_param(parameters, SCHEMA_HASH) {
        Some(hash) => {
            // Only rebuild with the schema matching this batch's hash —
            // otherwise wait for the right `@schema` rather than emit a stream
            // the CLI would decode against the wrong (stale/future) schema.
            let (_, schema) = cache.iter().find(|(h, _)| *h == hash as u64)?;
            let mut full = Vec::with_capacity(schema.len() + payload.len());
            full.extend_from_slice(schema);
            full.extend_from_slice(payload);
            Some(full)
        }
        None => {
            prime_debug_schema(cache, parameters, payload);
            Some(payload.to_vec())
        }
    }
}

/// In-band schema priming for a full self-describing payload (no
/// `SCHEMA_HASH`), mirroring the node receive path: such a stream carries the
/// same schema block the producer publishes on `@schema`, so retain it here —
/// then the schema-less batches that follow rebuild even if the `@schema`
/// subscription missed the (single) schema emission. The producer guarantees
/// such a full stream for the first message of every output and periodically
/// thereafter (`DoraNode::publish_schema_once`). No-op for a schema-once batch.
fn prime_debug_schema(
    cache: &mut Vec<(u64, Vec<u8>)>,
    parameters: &dora_message::metadata::MetadataParameters,
    payload: &[u8],
) {
    use dora_message::metadata::{SCHEMA_HASH, carries_pattern_correlation, get_integer_param};

    // Service/action messages (pattern correlation) are excluded from
    // schema-once; don't let their per-request schemas churn the cache.
    if get_integer_param(parameters, SCHEMA_HASH).is_none()
        && !carries_pattern_correlation(parameters)
        && let Some((hash, schema)) = crate::schema_once::schema_block_and_hash(payload)
    {
        retain_debug_schema(cache, hash, schema);
    }
}

/// Turn one sample observed by a debug subscriber into the `(metadata, data)`
/// of a `dora topic` frame, or `None` to drop it.
///
/// When no `dora topic` watcher is attached to the output (`watched ==
/// false`), the sample is dropped *before* the payload is copied, so an idle
/// debug-enabled dataflow does not memcpy every output into the daemon's main
/// event loop (dora-rs/dora#3781). Schema priming still runs, so a watcher
/// that attaches later can rebuild schema-once batches right away.
pub fn prepare_debug_topic_frame(
    cache: &mut Vec<(u64, Vec<u8>)>,
    watched: bool,
    mut metadata: dora_message::metadata::Metadata,
    payload: &[u8],
) -> Option<(dora_message::metadata::Metadata, Vec<u8>)> {
    if !watched {
        prime_debug_schema(cache, &metadata.parameters, payload);
        return None;
    }
    // `None`: a schema-once batch whose schema hasn't been cached yet — drop
    // this inspection frame (transient, recovers once `@schema` or the
    // producer's next full-stream refresh arrives).
    let data = rebuild_debug_topic_stream(cache, &metadata.parameters, payload)?;
    // `data` is now always a full self-describing stream, so drop the internal
    // wire keys — a `_schema_hash` here would contradict the rebuilt payload
    // for any consumer applying the wire rule "hash present => schema-less
    // batch".
    dora_message::metadata::strip_internal_parameters(&mut metadata.parameters);
    // Record the true on-wire size so `dora topic info` measures the
    // schema-less batch that actually travelled, not the rebuilt stream (which
    // prepends the schema to every frame even though it ships once). For a
    // full self-describing frame this equals `data.len()`; for a schema-once
    // batch it excludes the prepended schema block (dora-rs/dora#2584).
    metadata.parameters.insert(
        dora_message::metadata::WIRE_SIZE.to_string(),
        dora_message::metadata::Parameter::Integer(payload.len() as i64),
    );
    Some((metadata, data))
}

#[cfg(test)]
mod debug_topic_tests {
    use super::{prepare_debug_topic_frame, rebuild_debug_topic_stream, retain_published_schema};
    use dora_message::metadata::{
        MetadataParameters, Parameter, SCHEMA_HASH, WIRE_SIZE, debug_frame_wire_size, fnv1a,
        get_integer_param, strip_internal_parameters,
    };

    fn params_with_schema_hash(hash: u64) -> MetadataParameters {
        let mut params = MetadataParameters::default();
        params.insert(SCHEMA_HASH.to_string(), Parameter::Integer(hash as i64));
        params
    }

    /// Wrap `msg` in an IPC message frame (continuation marker + length prefix)
    /// so `schema_block_len` parses it like a real schema block.
    fn framed(msg: &[u8]) -> Vec<u8> {
        let mut out = vec![0xff, 0xff, 0xff, 0xff];
        out.extend_from_slice(&(msg.len() as i32).to_le_bytes());
        out.extend_from_slice(msg);
        out
    }

    #[test]
    fn full_stream_payload_is_forwarded_verbatim() {
        // No SCHEMA_HASH ⇒ already a self-describing stream (large/SHM or
        // service/action output); forward the bytes unchanged.
        let payload = b"self-describing-stream".to_vec();
        let mut cache = Vec::new();
        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &payload);
        assert_eq!(out, Some(payload));
        assert!(
            cache.is_empty(),
            "an unframed payload must not prime the cache"
        );
    }

    #[test]
    fn schema_once_batch_is_prepended_with_cached_schema() {
        let schema = b"SCHEMA-BLOCK".to_vec();
        let hash = fnv1a(&schema);
        let batch = b"schema-less-batch".to_vec();
        let mut cache = vec![(hash, schema.clone())];
        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
        let mut expected = schema;
        expected.extend_from_slice(&batch);
        assert_eq!(out, Some(expected));
    }

    /// End-to-end guard for the `dora topic info` bandwidth fix, mirroring
    /// [`prepare_debug_topic_frame`]:
    /// rebuild the inspection stream, strip the internal wire keys, then stamp
    /// the *input* payload length under `WIRE_SIZE`. The CLI reader
    /// ([`debug_frame_wire_size`]) must then charge the schema-less on-wire
    /// size, not the rebuilt stream — otherwise bandwidth is over-reported by
    /// the prepended schema on every schema-once frame, worst for the
    /// small/frequent primitives the schema-once optimization targets (#2584).
    /// Keep this in sync with the `WIRE_SIZE` stamp in [`prepare_debug_topic_frame`].
    #[test]
    fn on_wire_size_excludes_prepended_schema() {
        // --- schema-once frame: rebuilt = schema ++ batch, only batch on-wire.
        let schema = b"SCHEMA-BLOCK".to_vec();
        let hash = fnv1a(&schema);
        let batch = b"schema-less-batch".to_vec();
        let mut cache = vec![(hash, schema.clone())];
        let mut params = params_with_schema_hash(hash);

        let rebuilt =
            rebuild_debug_topic_stream(&mut cache, &params, &batch).expect("schema cached");
        assert_eq!(rebuilt.len(), schema.len() + batch.len());

        // Replicate the daemon stamp: strip wire keys, record the input length.
        strip_internal_parameters(&mut params);
        assert!(
            get_integer_param(&params, SCHEMA_HASH).is_none(),
            "internal wire keys must be stripped before stamping"
        );
        params.insert(
            WIRE_SIZE.to_string(),
            Parameter::Integer(batch.len() as i64),
        );

        // The CLI reader charges the schema-less size, not the rebuilt stream.
        let charged = debug_frame_wire_size(&params, Some(&rebuilt));
        assert_eq!(charged, batch.len());
        assert!(
            charged < rebuilt.len(),
            "schema-once accounting must exclude the prepended schema"
        );

        // --- full self-describing frame: rebuilt == payload, charge full len.
        let full = b"self-describing-stream".to_vec();
        let mut full_params = MetadataParameters::default();
        let out = rebuild_debug_topic_stream(&mut Vec::new(), &full_params, &full)
            .expect("full stream forwarded");
        assert_eq!(out.len(), full.len());
        strip_internal_parameters(&mut full_params);
        full_params.insert(WIRE_SIZE.to_string(), Parameter::Integer(full.len() as i64));
        assert_eq!(debug_frame_wire_size(&full_params, Some(&out)), full.len());
    }

    #[test]
    fn schema_once_batch_dropped_when_schema_not_cached() {
        let batch = b"schema-less-batch".to_vec();
        let out = rebuild_debug_topic_stream(&mut Vec::new(), &params_with_schema_hash(42), &batch);
        assert_eq!(out, None);
    }

    #[test]
    fn schema_once_batch_dropped_on_hash_mismatch() {
        // Retained schema is for a different hash (e.g. a stale schema
        // mid-change): drop rather than emit a stream the CLI would decode
        // incorrectly.
        let schema = b"OTHER-SCHEMA".to_vec();
        let out = rebuild_debug_topic_stream(
            &mut vec![(999, schema)],
            &params_with_schema_hash(42),
            b"batch",
        );
        assert_eq!(out, None);
    }

    /// A full self-describing stream must prime the debug schema cache in-band
    /// (mirroring the node receive path), so `dora topic` can rebuild the
    /// schema-less batches that follow even when the `@schema` subscription
    /// missed the (single) schema emission — the producer guarantees a full
    /// stream for the first message of every output and periodically
    /// thereafter (dora-rs/dora#2366 review).
    #[test]
    fn full_stream_primes_debug_schema_cache_in_band() {
        let schema_block = framed(b"SCHEMA-FLATBUFFER");
        let hash = fnv1a(&schema_block);
        let batch = framed(b"BATCH-FLATBUFFER");
        let mut full = schema_block.clone();
        full.extend_from_slice(&batch);

        // The full stream is forwarded verbatim AND primes the cache.
        let mut cache = Vec::new();
        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &full);
        assert_eq!(out, Some(full.clone()));
        assert_eq!(cache, vec![(hash, schema_block)]);

        // A schema-less batch tagged with that hash now rebuilds, without any
        // `@schema` sample ever having been received.
        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
        assert_eq!(out, Some(full));
    }

    /// The cache retains multiple schemas: a full stream of a different schema
    /// (e.g. a large message interleaved with schema-once batches on the same
    /// output) must not clobber the schema those batches reference — the node
    /// receive path retains 8 schemas for exactly this interleave, and the
    /// `dora topic` mirror must not silently diverge from what nodes decode.
    #[test]
    fn interleaved_full_stream_does_not_clobber_schema_once_schema() {
        let schema_a = framed(b"SCHEMA-A");
        let hash_a = fnv1a(&schema_a);
        let batch_a = framed(b"BATCH-A");

        // Prime A (as the @schema subscriber or an earlier full stream would).
        let mut cache = vec![(hash_a, schema_a.clone())];

        // A large full stream of schema B passes through on the same output...
        let mut full_b = framed(b"SCHEMA-B");
        full_b.extend_from_slice(&framed(b"BATCH-B"));
        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &full_b);
        assert_eq!(out, Some(full_b));

        // ...and the next A-tagged schema-once batch still rebuilds.
        let out =
            rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash_a), &batch_a);
        let mut expected = schema_a;
        expected.extend_from_slice(&batch_a);
        assert_eq!(out, Some(expected));
    }

    /// Service/action full streams (pattern-correlated) are excluded from
    /// schema-once and must not churn the debug schema cache.
    #[test]
    fn pattern_correlated_stream_does_not_prime_debug_cache() {
        let schema_block = framed(b"SCHEMA-FLATBUFFER");
        let hash = fnv1a(&schema_block);

        let mut cache = vec![(hash, schema_block.clone())];
        let mut params = MetadataParameters::default();
        params.insert(
            dora_message::metadata::REQUEST_ID.to_string(),
            Parameter::String("req-1".into()),
        );
        let mut service_full = framed(b"OTHER-SCHEMA");
        service_full.extend_from_slice(&framed(b"OTHER-BATCH"));
        let out = rebuild_debug_topic_stream(&mut cache, &params, &service_full);
        assert_eq!(out, Some(service_full));
        assert_eq!(
            cache,
            vec![(hash, schema_block)],
            "a service reply must not churn the schema-once cache"
        );
    }

    /// A schema received on `@schema` must be keyed by the hash the producer
    /// tags its schema-once batches with, or none of them rebuild.
    #[test]
    fn published_schema_rebuilds_the_batches_tagged_with_its_hash() {
        let schema_block = framed(b"SCHEMA-FLATBUFFER");
        let batch = framed(b"BATCH-FLATBUFFER");
        let mut full = schema_block.clone();
        full.extend_from_slice(&batch);
        let (hash, _) = crate::schema_once::schema_block_and_hash(&full).unwrap();

        let mut cache = Vec::new();
        retain_published_schema(&mut cache, &schema_block);
        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
        assert_eq!(out, Some(full));
    }

    fn metadata_with(parameters: MetadataParameters) -> dora_message::metadata::Metadata {
        dora_message::metadata::Metadata::from_parameters(
            dora_message::uhlc::HLC::default().new_timestamp(),
            parameters,
        )
    }

    /// With no `dora topic` watcher attached, a sample must not produce a
    /// debug frame — no payload copy, nothing queued on the daemon's main
    /// event channel (dora-rs/dora#3781).
    #[test]
    fn unwatched_sample_produces_no_frame() {
        let mut full = framed(b"SCHEMA-FLATBUFFER");
        full.extend_from_slice(&framed(b"BATCH-FLATBUFFER"));
        let frame = prepare_debug_topic_frame(
            &mut Vec::new(),
            false,
            metadata_with(MetadataParameters::default()),
            &full,
        );
        assert!(frame.is_none());

        let schema = b"SCHEMA-BLOCK".to_vec();
        let hash = fnv1a(&schema);
        let mut cache = vec![(hash, schema)];
        let frame = prepare_debug_topic_frame(
            &mut cache,
            false,
            metadata_with(params_with_schema_hash(hash)),
            b"schema-less-batch",
        );
        assert!(frame.is_none());
    }

    /// Skipping unwatched samples must keep in-band schema priming going, so a
    /// watcher that attaches later can rebuild schema-once batches at once.
    #[test]
    fn unwatched_full_stream_still_primes_schema_for_a_later_watcher() {
        let schema_block = framed(b"SCHEMA-FLATBUFFER");
        let hash = fnv1a(&schema_block);
        let batch = framed(b"BATCH-FLATBUFFER");
        let mut full = schema_block.clone();
        full.extend_from_slice(&batch);

        let mut cache = Vec::new();
        let frame = prepare_debug_topic_frame(
            &mut cache,
            false,
            metadata_with(MetadataParameters::default()),
            &full,
        );
        assert!(frame.is_none());
        assert_eq!(cache, vec![(hash, schema_block)]);

        // A watcher attaches; the next schema-once batch rebuilds.
        let (metadata, data) = prepare_debug_topic_frame(
            &mut cache,
            true,
            metadata_with(params_with_schema_hash(hash)),
            &batch,
        )
        .expect("watched schema-once batch with a primed schema is forwarded");
        assert_eq!(data, full);
        assert!(get_integer_param(&metadata.parameters, SCHEMA_HASH).is_none());
        assert_eq!(
            get_integer_param(&metadata.parameters, WIRE_SIZE),
            Some(batch.len() as i64)
        );
    }
}