Skip to main content

dora_core/
debug_topic.rs

1//! `@schema` reassembly for `dora topic`: rebuilding the self-describing Arrow
2//! IPC stream of each output sample a node publishes on zenoh, with the cache
3//! that lets a late watcher decode schema-once batches.
4//!
5//! The daemon's debug subscriber uses this to feed `dora topic`. It lives here
6//! so that a CLI subscribing to zenoh directly can rebuild the same frames
7//! (dora-rs/dora#4025).
8
9use std::sync::Arc;
10
11/// Cached `@schema` bytes (keyed by their FNV-1a hash, most-recent last) for
12/// one debug-watched output, shared between the `@schema` subscriber callback
13/// and the data task. Retains several schemas — mirroring the node receive
14/// path's `InputDecoder` retention — so an output that interleaves schemas
15/// (e.g. schema-once batches of schema A between large full streams of schema
16/// B) doesn't have its schema-once schema clobbered, and a stale `@schema`
17/// history-query result arriving after an in-band prime can't evict the
18/// fresher schema (both stay retained).
19pub type DebugSchemaCache = Arc<std::sync::Mutex<Vec<(u64, Vec<u8>)>>>;
20
21/// Retention bound for [`DebugSchemaCache`], matching the node receive path's
22/// `InputDecoder` (see `MAX_RETAINED_SCHEMAS` in dora-node-api's `ipc_encode`).
23pub const MAX_DEBUG_SCHEMAS: usize = 8;
24
25/// Remember `schema` for `hash` in the debug cache (most-recent last), evicting
26/// the oldest entry beyond [`MAX_DEBUG_SCHEMAS`]. An already-retained hash is
27/// moved to the back without re-copying its bytes.
28pub fn retain_debug_schema(cache: &mut Vec<(u64, Vec<u8>)>, hash: u64, schema: &[u8]) {
29    if let Some(pos) = cache.iter().position(|(h, _)| *h == hash) {
30        let entry = cache.remove(pos);
31        cache.push(entry);
32        return;
33    }
34    cache.push((hash, schema.to_vec()));
35    if cache.len() > MAX_DEBUG_SCHEMAS {
36        cache.remove(0);
37    }
38}
39
40/// Remember a schema block received on an output's `@schema` key. It is keyed
41/// by its FNV-1a hash, the hash the producer tags its schema-once batches with
42/// (see [`crate::schema_once::schema_block_and_hash`]).
43pub fn retain_published_schema(cache: &mut Vec<(u64, Vec<u8>)>, schema: &[u8]) {
44    retain_debug_schema(cache, dora_message::metadata::fnv1a(schema), schema);
45}
46
47/// Rebuild a self-describing Arrow IPC stream for a `dora topic` debug frame.
48///
49/// Small node→node outputs travel as schema-once batches: the schema is
50/// published once on the `@schema` subtopic and each data sample carries only
51/// the schema-less record batch (`DoraNode::publish_schema_once`). The
52/// `dora topic` decoder expects a full self-describing stream, so for such a
53/// batch we prepend the retained schema block — concatenation reconstructs the
54/// exact original stream (`schema_block ++ batch_slice == full_stream`).
55///
56/// Returns `None` (drop the inspection frame) when the batch is schema-once but
57/// no schema matching its `SCHEMA_HASH` has been retained yet — a transient,
58/// inspection-only gap. A full self-describing payload (no `SCHEMA_HASH`) is
59/// forwarded as-is.
60pub fn rebuild_debug_topic_stream(
61    cache: &mut Vec<(u64, Vec<u8>)>,
62    parameters: &dora_message::metadata::MetadataParameters,
63    payload: &[u8],
64) -> Option<Vec<u8>> {
65    use dora_message::metadata::{SCHEMA_HASH, get_integer_param};
66
67    match get_integer_param(parameters, SCHEMA_HASH) {
68        Some(hash) => {
69            // Only rebuild with the schema matching this batch's hash —
70            // otherwise wait for the right `@schema` rather than emit a stream
71            // the CLI would decode against the wrong (stale/future) schema.
72            let (_, schema) = cache.iter().find(|(h, _)| *h == hash as u64)?;
73            let mut full = Vec::with_capacity(schema.len() + payload.len());
74            full.extend_from_slice(schema);
75            full.extend_from_slice(payload);
76            Some(full)
77        }
78        None => {
79            prime_debug_schema(cache, parameters, payload);
80            Some(payload.to_vec())
81        }
82    }
83}
84
85/// In-band schema priming for a full self-describing payload (no
86/// `SCHEMA_HASH`), mirroring the node receive path: such a stream carries the
87/// same schema block the producer publishes on `@schema`, so retain it here —
88/// then the schema-less batches that follow rebuild even if the `@schema`
89/// subscription missed the (single) schema emission. The producer guarantees
90/// such a full stream for the first message of every output and periodically
91/// thereafter (`DoraNode::publish_schema_once`). No-op for a schema-once batch.
92fn prime_debug_schema(
93    cache: &mut Vec<(u64, Vec<u8>)>,
94    parameters: &dora_message::metadata::MetadataParameters,
95    payload: &[u8],
96) {
97    use dora_message::metadata::{SCHEMA_HASH, carries_pattern_correlation, get_integer_param};
98
99    // Service/action messages (pattern correlation) are excluded from
100    // schema-once; don't let their per-request schemas churn the cache.
101    if get_integer_param(parameters, SCHEMA_HASH).is_none()
102        && !carries_pattern_correlation(parameters)
103        && let Some((hash, schema)) = crate::schema_once::schema_block_and_hash(payload)
104    {
105        retain_debug_schema(cache, hash, schema);
106    }
107}
108
109/// Turn one sample observed by a debug subscriber into the `(metadata, data)`
110/// of a `dora topic` frame, or `None` to drop it.
111///
112/// When no `dora topic` watcher is attached to the output (`watched ==
113/// false`), the sample is dropped *before* the payload is copied, so an idle
114/// debug-enabled dataflow does not memcpy every output into the daemon's main
115/// event loop (dora-rs/dora#3781). Schema priming still runs, so a watcher
116/// that attaches later can rebuild schema-once batches right away.
117pub fn prepare_debug_topic_frame(
118    cache: &mut Vec<(u64, Vec<u8>)>,
119    watched: bool,
120    mut metadata: dora_message::metadata::Metadata,
121    payload: &[u8],
122) -> Option<(dora_message::metadata::Metadata, Vec<u8>)> {
123    if !watched {
124        prime_debug_schema(cache, &metadata.parameters, payload);
125        return None;
126    }
127    // `None`: a schema-once batch whose schema hasn't been cached yet — drop
128    // this inspection frame (transient, recovers once `@schema` or the
129    // producer's next full-stream refresh arrives).
130    let data = rebuild_debug_topic_stream(cache, &metadata.parameters, payload)?;
131    // `data` is now always a full self-describing stream, so drop the internal
132    // wire keys — a `_schema_hash` here would contradict the rebuilt payload
133    // for any consumer applying the wire rule "hash present => schema-less
134    // batch".
135    dora_message::metadata::strip_internal_parameters(&mut metadata.parameters);
136    // Record the true on-wire size so `dora topic info` measures the
137    // schema-less batch that actually travelled, not the rebuilt stream (which
138    // prepends the schema to every frame even though it ships once). For a
139    // full self-describing frame this equals `data.len()`; for a schema-once
140    // batch it excludes the prepended schema block (dora-rs/dora#2584).
141    metadata.parameters.insert(
142        dora_message::metadata::WIRE_SIZE.to_string(),
143        dora_message::metadata::Parameter::Integer(payload.len() as i64),
144    );
145    Some((metadata, data))
146}
147
148#[cfg(test)]
149mod debug_topic_tests {
150    use super::{prepare_debug_topic_frame, rebuild_debug_topic_stream, retain_published_schema};
151    use dora_message::metadata::{
152        MetadataParameters, Parameter, SCHEMA_HASH, WIRE_SIZE, debug_frame_wire_size, fnv1a,
153        get_integer_param, strip_internal_parameters,
154    };
155
156    fn params_with_schema_hash(hash: u64) -> MetadataParameters {
157        let mut params = MetadataParameters::default();
158        params.insert(SCHEMA_HASH.to_string(), Parameter::Integer(hash as i64));
159        params
160    }
161
162    /// Wrap `msg` in an IPC message frame (continuation marker + length prefix)
163    /// so `schema_block_len` parses it like a real schema block.
164    fn framed(msg: &[u8]) -> Vec<u8> {
165        let mut out = vec![0xff, 0xff, 0xff, 0xff];
166        out.extend_from_slice(&(msg.len() as i32).to_le_bytes());
167        out.extend_from_slice(msg);
168        out
169    }
170
171    #[test]
172    fn full_stream_payload_is_forwarded_verbatim() {
173        // No SCHEMA_HASH ⇒ already a self-describing stream (large/SHM or
174        // service/action output); forward the bytes unchanged.
175        let payload = b"self-describing-stream".to_vec();
176        let mut cache = Vec::new();
177        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &payload);
178        assert_eq!(out, Some(payload));
179        assert!(
180            cache.is_empty(),
181            "an unframed payload must not prime the cache"
182        );
183    }
184
185    #[test]
186    fn schema_once_batch_is_prepended_with_cached_schema() {
187        let schema = b"SCHEMA-BLOCK".to_vec();
188        let hash = fnv1a(&schema);
189        let batch = b"schema-less-batch".to_vec();
190        let mut cache = vec![(hash, schema.clone())];
191        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
192        let mut expected = schema;
193        expected.extend_from_slice(&batch);
194        assert_eq!(out, Some(expected));
195    }
196
197    /// End-to-end guard for the `dora topic info` bandwidth fix, mirroring
198    /// [`prepare_debug_topic_frame`]:
199    /// rebuild the inspection stream, strip the internal wire keys, then stamp
200    /// the *input* payload length under `WIRE_SIZE`. The CLI reader
201    /// ([`debug_frame_wire_size`]) must then charge the schema-less on-wire
202    /// size, not the rebuilt stream — otherwise bandwidth is over-reported by
203    /// the prepended schema on every schema-once frame, worst for the
204    /// small/frequent primitives the schema-once optimization targets (#2584).
205    /// Keep this in sync with the `WIRE_SIZE` stamp in [`prepare_debug_topic_frame`].
206    #[test]
207    fn on_wire_size_excludes_prepended_schema() {
208        // --- schema-once frame: rebuilt = schema ++ batch, only batch on-wire.
209        let schema = b"SCHEMA-BLOCK".to_vec();
210        let hash = fnv1a(&schema);
211        let batch = b"schema-less-batch".to_vec();
212        let mut cache = vec![(hash, schema.clone())];
213        let mut params = params_with_schema_hash(hash);
214
215        let rebuilt =
216            rebuild_debug_topic_stream(&mut cache, &params, &batch).expect("schema cached");
217        assert_eq!(rebuilt.len(), schema.len() + batch.len());
218
219        // Replicate the daemon stamp: strip wire keys, record the input length.
220        strip_internal_parameters(&mut params);
221        assert!(
222            get_integer_param(&params, SCHEMA_HASH).is_none(),
223            "internal wire keys must be stripped before stamping"
224        );
225        params.insert(
226            WIRE_SIZE.to_string(),
227            Parameter::Integer(batch.len() as i64),
228        );
229
230        // The CLI reader charges the schema-less size, not the rebuilt stream.
231        let charged = debug_frame_wire_size(&params, Some(&rebuilt));
232        assert_eq!(charged, batch.len());
233        assert!(
234            charged < rebuilt.len(),
235            "schema-once accounting must exclude the prepended schema"
236        );
237
238        // --- full self-describing frame: rebuilt == payload, charge full len.
239        let full = b"self-describing-stream".to_vec();
240        let mut full_params = MetadataParameters::default();
241        let out = rebuild_debug_topic_stream(&mut Vec::new(), &full_params, &full)
242            .expect("full stream forwarded");
243        assert_eq!(out.len(), full.len());
244        strip_internal_parameters(&mut full_params);
245        full_params.insert(WIRE_SIZE.to_string(), Parameter::Integer(full.len() as i64));
246        assert_eq!(debug_frame_wire_size(&full_params, Some(&out)), full.len());
247    }
248
249    #[test]
250    fn schema_once_batch_dropped_when_schema_not_cached() {
251        let batch = b"schema-less-batch".to_vec();
252        let out = rebuild_debug_topic_stream(&mut Vec::new(), &params_with_schema_hash(42), &batch);
253        assert_eq!(out, None);
254    }
255
256    #[test]
257    fn schema_once_batch_dropped_on_hash_mismatch() {
258        // Retained schema is for a different hash (e.g. a stale schema
259        // mid-change): drop rather than emit a stream the CLI would decode
260        // incorrectly.
261        let schema = b"OTHER-SCHEMA".to_vec();
262        let out = rebuild_debug_topic_stream(
263            &mut vec![(999, schema)],
264            &params_with_schema_hash(42),
265            b"batch",
266        );
267        assert_eq!(out, None);
268    }
269
270    /// A full self-describing stream must prime the debug schema cache in-band
271    /// (mirroring the node receive path), so `dora topic` can rebuild the
272    /// schema-less batches that follow even when the `@schema` subscription
273    /// missed the (single) schema emission — the producer guarantees a full
274    /// stream for the first message of every output and periodically
275    /// thereafter (dora-rs/dora#2366 review).
276    #[test]
277    fn full_stream_primes_debug_schema_cache_in_band() {
278        let schema_block = framed(b"SCHEMA-FLATBUFFER");
279        let hash = fnv1a(&schema_block);
280        let batch = framed(b"BATCH-FLATBUFFER");
281        let mut full = schema_block.clone();
282        full.extend_from_slice(&batch);
283
284        // The full stream is forwarded verbatim AND primes the cache.
285        let mut cache = Vec::new();
286        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &full);
287        assert_eq!(out, Some(full.clone()));
288        assert_eq!(cache, vec![(hash, schema_block)]);
289
290        // A schema-less batch tagged with that hash now rebuilds, without any
291        // `@schema` sample ever having been received.
292        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
293        assert_eq!(out, Some(full));
294    }
295
296    /// The cache retains multiple schemas: a full stream of a different schema
297    /// (e.g. a large message interleaved with schema-once batches on the same
298    /// output) must not clobber the schema those batches reference — the node
299    /// receive path retains 8 schemas for exactly this interleave, and the
300    /// `dora topic` mirror must not silently diverge from what nodes decode.
301    #[test]
302    fn interleaved_full_stream_does_not_clobber_schema_once_schema() {
303        let schema_a = framed(b"SCHEMA-A");
304        let hash_a = fnv1a(&schema_a);
305        let batch_a = framed(b"BATCH-A");
306
307        // Prime A (as the @schema subscriber or an earlier full stream would).
308        let mut cache = vec![(hash_a, schema_a.clone())];
309
310        // A large full stream of schema B passes through on the same output...
311        let mut full_b = framed(b"SCHEMA-B");
312        full_b.extend_from_slice(&framed(b"BATCH-B"));
313        let out = rebuild_debug_topic_stream(&mut cache, &MetadataParameters::default(), &full_b);
314        assert_eq!(out, Some(full_b));
315
316        // ...and the next A-tagged schema-once batch still rebuilds.
317        let out =
318            rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash_a), &batch_a);
319        let mut expected = schema_a;
320        expected.extend_from_slice(&batch_a);
321        assert_eq!(out, Some(expected));
322    }
323
324    /// Service/action full streams (pattern-correlated) are excluded from
325    /// schema-once and must not churn the debug schema cache.
326    #[test]
327    fn pattern_correlated_stream_does_not_prime_debug_cache() {
328        let schema_block = framed(b"SCHEMA-FLATBUFFER");
329        let hash = fnv1a(&schema_block);
330
331        let mut cache = vec![(hash, schema_block.clone())];
332        let mut params = MetadataParameters::default();
333        params.insert(
334            dora_message::metadata::REQUEST_ID.to_string(),
335            Parameter::String("req-1".into()),
336        );
337        let mut service_full = framed(b"OTHER-SCHEMA");
338        service_full.extend_from_slice(&framed(b"OTHER-BATCH"));
339        let out = rebuild_debug_topic_stream(&mut cache, &params, &service_full);
340        assert_eq!(out, Some(service_full));
341        assert_eq!(
342            cache,
343            vec![(hash, schema_block)],
344            "a service reply must not churn the schema-once cache"
345        );
346    }
347
348    /// A schema received on `@schema` must be keyed by the hash the producer
349    /// tags its schema-once batches with, or none of them rebuild.
350    #[test]
351    fn published_schema_rebuilds_the_batches_tagged_with_its_hash() {
352        let schema_block = framed(b"SCHEMA-FLATBUFFER");
353        let batch = framed(b"BATCH-FLATBUFFER");
354        let mut full = schema_block.clone();
355        full.extend_from_slice(&batch);
356        let (hash, _) = crate::schema_once::schema_block_and_hash(&full).unwrap();
357
358        let mut cache = Vec::new();
359        retain_published_schema(&mut cache, &schema_block);
360        let out = rebuild_debug_topic_stream(&mut cache, &params_with_schema_hash(hash), &batch);
361        assert_eq!(out, Some(full));
362    }
363
364    fn metadata_with(parameters: MetadataParameters) -> dora_message::metadata::Metadata {
365        dora_message::metadata::Metadata::from_parameters(
366            dora_message::uhlc::HLC::default().new_timestamp(),
367            parameters,
368        )
369    }
370
371    /// With no `dora topic` watcher attached, a sample must not produce a
372    /// debug frame — no payload copy, nothing queued on the daemon's main
373    /// event channel (dora-rs/dora#3781).
374    #[test]
375    fn unwatched_sample_produces_no_frame() {
376        let mut full = framed(b"SCHEMA-FLATBUFFER");
377        full.extend_from_slice(&framed(b"BATCH-FLATBUFFER"));
378        let frame = prepare_debug_topic_frame(
379            &mut Vec::new(),
380            false,
381            metadata_with(MetadataParameters::default()),
382            &full,
383        );
384        assert!(frame.is_none());
385
386        let schema = b"SCHEMA-BLOCK".to_vec();
387        let hash = fnv1a(&schema);
388        let mut cache = vec![(hash, schema)];
389        let frame = prepare_debug_topic_frame(
390            &mut cache,
391            false,
392            metadata_with(params_with_schema_hash(hash)),
393            b"schema-less-batch",
394        );
395        assert!(frame.is_none());
396    }
397
398    /// Skipping unwatched samples must keep in-band schema priming going, so a
399    /// watcher that attaches later can rebuild schema-once batches at once.
400    #[test]
401    fn unwatched_full_stream_still_primes_schema_for_a_later_watcher() {
402        let schema_block = framed(b"SCHEMA-FLATBUFFER");
403        let hash = fnv1a(&schema_block);
404        let batch = framed(b"BATCH-FLATBUFFER");
405        let mut full = schema_block.clone();
406        full.extend_from_slice(&batch);
407
408        let mut cache = Vec::new();
409        let frame = prepare_debug_topic_frame(
410            &mut cache,
411            false,
412            metadata_with(MetadataParameters::default()),
413            &full,
414        );
415        assert!(frame.is_none());
416        assert_eq!(cache, vec![(hash, schema_block)]);
417
418        // A watcher attaches; the next schema-once batch rebuilds.
419        let (metadata, data) = prepare_debug_topic_frame(
420            &mut cache,
421            true,
422            metadata_with(params_with_schema_hash(hash)),
423            &batch,
424        )
425        .expect("watched schema-once batch with a primed schema is forwarded");
426        assert_eq!(data, full);
427        assert!(get_integer_param(&metadata.parameters, SCHEMA_HASH).is_none());
428        assert_eq!(
429            get_integer_param(&metadata.parameters, WIRE_SIZE),
430            Some(batch.len() as i64)
431        );
432    }
433}