Skip to main content

astrs_wire/metadata/
mod.rs

1//! [`Metadata`] — the struct that rides beside every payload.
2//!
3//! Blueprint §6.1: *"Metadata rides beside payloads as an oxicode-encoded
4//! struct (never inside the Arrow stream): `{version: u16, timestamp: Hlc,
5//! parameters: BTreeMap<Key, Parameter>}` with well-known keys `request_id,
6//! goal_id, goal_status, session_id, segment_id, seq, fin, flush` and internal
7//! keys `_schema_hash`, stripped before user delivery."*
8//!
9//! Three consequences of that one sentence shape this module:
10//!
11//! - **Beside, not inside.** Metadata is a separate oxicode struct, so a
12//!   receiver can read the correlation keys without touching the columnar
13//!   payload — which is what lets the scheduler grant queue-eviction immunity
14//!   (§11.2) before anything is decoded.
15//! - **`BTreeMap`, not `HashMap`.** Ordered iteration makes the encoding
16//!   deterministic, which is what makes recordings replayable byte-for-byte
17//!   (§14) and the protocol snapshot stable.
18//! - **Internal keys are stripped.** [`Metadata::strip_internal`] removes the
19//!   `_`-prefixed plumbing before an event reaches user code.
20//!
21//! # Examples
22//!
23//! ```
24//! use astrs_wire::{GoalStatus, Metadata, Parameter};
25//! use astrs_time::HlcTimestamp;
26//!
27//! let mut meta = Metadata::new(HlcTimestamp::new(1_700_000_000_000_000_000, 0));
28//! meta.set_request_id("req-42");
29//! meta.set_goal_status(GoalStatus::Executing);
30//! meta.insert_schema_hash("d0f9a1c3");
31//!
32//! assert!(meta.is_correlated());
33//! assert_eq!(meta.request_id(), Some("req-42"));
34//! assert_eq!(meta.goal_status(), Some(GoalStatus::Executing));
35//!
36//! // What user code sees: no `_`-prefixed plumbing.
37//! let delivered = meta.stripped();
38//! assert_eq!(delivered.schema_hash(), None);
39//! assert_eq!(delivered.request_id(), Some("req-42"));
40//! # Ok::<(), astrs_wire::IdError>(())
41//! ```
42
43pub mod keys;
44pub mod parameter;
45
46use std::collections::BTreeMap;
47use std::collections::btree_map::{Entry, Iter, Keys, Values};
48
49use astrs_time::HlcTimestamp;
50use oxicode::de::{Decode, Decoder};
51use oxicode::enc::{Encode, Encoder};
52use serde::{Deserialize, Serialize};
53
54use crate::error::codec_invalid;
55use crate::ids::ParamKey;
56
57pub use keys::GoalStatus;
58pub use parameter::Parameter;
59
60/// The metadata layout version this build writes.
61///
62/// Carried in every [`Metadata`] so a receiver can tell an old sender's
63/// metadata from a new one's without consulting the connection's protocol
64/// version — metadata outlives connections, because it is written into
65/// recordings (§14).
66pub const METADATA_VERSION: u16 = 1;
67
68/// The largest number of parameters accepted off the wire.
69///
70/// Metadata is a small correlation record, not a document store. The frame
71/// limit already bounds the total bytes; this bounds the *shape*, so a peer
72/// cannot force a receiver to build a million-entry map inside one legal
73/// frame.
74pub const MAX_PARAMETERS: usize = 1024;
75
76/// The metadata accompanying one message.
77///
78/// Deliberately **not** `#[non_exhaustive]`: `astrs-daemon`, `astrs-node-api`
79/// and the recorder all build these with struct literals, and the field set is
80/// pinned by the blueprint.
81///
82/// # Examples
83///
84/// ```
85/// use astrs_wire::{Metadata, Parameter};
86/// use astrs_time::HlcTimestamp;
87///
88/// let meta = Metadata::new(HlcTimestamp::new(10, 0))
89///     .with("seq", Parameter::Integer(3))?
90///     .with("fin", Parameter::Bool(true))?;
91/// assert_eq!(meta.seq(), Some(3));
92/// assert_eq!(meta.fin(), Some(true));
93/// assert_eq!(meta.len(), 2);
94/// # Ok::<(), astrs_wire::IdError>(())
95/// ```
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97pub struct Metadata {
98    /// The metadata layout version — [`METADATA_VERSION`] for anything this
99    /// build produces.
100    pub version: u16,
101    /// The hybrid-logical-clock timestamp of the event this metadata
102    /// describes (blueprint §4.3).
103    pub timestamp: HlcTimestamp,
104    /// The key/value parameters, in key order.
105    pub parameters: BTreeMap<ParamKey, Parameter>,
106}
107
108impl Metadata {
109    /// An empty metadata record stamped at `timestamp`.
110    ///
111    /// # Examples
112    ///
113    /// ```
114    /// use astrs_wire::{METADATA_VERSION, Metadata};
115    /// use astrs_time::HlcTimestamp;
116    ///
117    /// let meta = Metadata::new(HlcTimestamp::new(1, 2));
118    /// assert_eq!(meta.version, METADATA_VERSION);
119    /// assert!(meta.is_empty());
120    /// ```
121    #[must_use]
122    pub fn new(timestamp: HlcTimestamp) -> Self {
123        Self {
124            version: METADATA_VERSION,
125            timestamp,
126            parameters: BTreeMap::new(),
127        }
128    }
129
130    /// Builder form of [`Metadata::insert`].
131    ///
132    /// # Errors
133    ///
134    /// [`crate::IdError`] if `key` is not a valid [`ParamKey`].
135    ///
136    /// # Examples
137    ///
138    /// ```
139    /// use astrs_wire::{Metadata, Parameter};
140    /// use astrs_time::HlcTimestamp;
141    ///
142    /// let meta = Metadata::new(HlcTimestamp::EPOCH).with("k", Parameter::Bool(true))?;
143    /// assert_eq!(meta.get("k").and_then(Parameter::as_bool), Some(true));
144    /// assert!(Metadata::new(HlcTimestamp::EPOCH).with("bad key", Parameter::Bool(true)).is_err());
145    /// # Ok::<(), astrs_wire::IdError>(())
146    /// ```
147    pub fn with(mut self, key: &str, value: impl Into<Parameter>) -> Result<Self, crate::IdError> {
148        self.insert(key, value)?;
149        Ok(self)
150    }
151
152    /// Inserts a parameter, returning the value it replaced.
153    ///
154    /// # Errors
155    ///
156    /// [`crate::IdError`] if `key` is not a valid [`ParamKey`].
157    ///
158    /// # Examples
159    ///
160    /// ```
161    /// use astrs_wire::{Metadata, Parameter};
162    /// use astrs_time::HlcTimestamp;
163    ///
164    /// let mut meta = Metadata::new(HlcTimestamp::EPOCH);
165    /// assert_eq!(meta.insert("seq", Parameter::Integer(1))?, None);
166    /// assert_eq!(meta.insert("seq", Parameter::Integer(2))?, Some(Parameter::Integer(1)));
167    /// # Ok::<(), astrs_wire::IdError>(())
168    /// ```
169    pub fn insert(
170        &mut self,
171        key: &str,
172        value: impl Into<Parameter>,
173    ) -> Result<Option<Parameter>, crate::IdError> {
174        Ok(self.parameters.insert(ParamKey::new(key)?, value.into()))
175    }
176
177    /// Inserts a parameter under an already-validated key.
178    ///
179    /// The infallible counterpart of [`Metadata::insert`], for call sites that
180    /// hold a [`ParamKey`].
181    pub fn insert_key(&mut self, key: ParamKey, value: impl Into<Parameter>) -> Option<Parameter> {
182        self.parameters.insert(key, value.into())
183    }
184
185    /// Looks up a parameter by key.
186    ///
187    /// # Examples
188    ///
189    /// ```
190    /// use astrs_wire::{Metadata, Parameter};
191    /// use astrs_time::HlcTimestamp;
192    ///
193    /// let meta = Metadata::new(HlcTimestamp::EPOCH).with("a", Parameter::Integer(1))?;
194    /// assert!(meta.get("a").is_some());
195    /// assert!(meta.get("b").is_none());
196    /// # Ok::<(), astrs_wire::IdError>(())
197    /// ```
198    #[must_use]
199    pub fn get(&self, key: &str) -> Option<&Parameter> {
200        self.parameters.get(key)
201    }
202
203    /// Removes a parameter, returning it.
204    pub fn remove(&mut self, key: &str) -> Option<Parameter> {
205        self.parameters.remove(key)
206    }
207
208    /// Whether a parameter with this key is present.
209    #[must_use]
210    pub fn contains_key(&self, key: &str) -> bool {
211        self.parameters.contains_key(key)
212    }
213
214    /// The entry API for the parameter map, for read-modify-write updates.
215    pub fn entry(&mut self, key: ParamKey) -> Entry<'_, ParamKey, Parameter> {
216        self.parameters.entry(key)
217    }
218
219    /// The number of parameters.
220    #[must_use]
221    pub fn len(&self) -> usize {
222        self.parameters.len()
223    }
224
225    /// Whether there are no parameters.
226    #[must_use]
227    pub fn is_empty(&self) -> bool {
228        self.parameters.is_empty()
229    }
230
231    /// Iterates the parameters in key order.
232    pub fn iter(&self) -> Iter<'_, ParamKey, Parameter> {
233        self.parameters.iter()
234    }
235
236    /// Iterates the keys in order.
237    pub fn keys(&self) -> Keys<'_, ParamKey, Parameter> {
238        self.parameters.keys()
239    }
240
241    /// Iterates the values in key order.
242    pub fn values(&self) -> Values<'_, ParamKey, Parameter> {
243        self.parameters.values()
244    }
245
246    /// Removes every AstRS-internal (`_`-prefixed) parameter in place.
247    ///
248    /// Called by the node API immediately before an `NodeEvent::Input`
249    /// is handed to user code, so application code never sees the plumbing
250    /// (blueprint §6.1).
251    ///
252    /// Returns the number of parameters removed.
253    ///
254    /// # Examples
255    ///
256    /// ```
257    /// use astrs_wire::{Metadata, Parameter};
258    /// use astrs_time::HlcTimestamp;
259    ///
260    /// let mut meta = Metadata::new(HlcTimestamp::EPOCH)
261    ///     .with("seq", Parameter::Integer(1))?
262    ///     .with("_schema_hash", Parameter::String("abc".into()))?
263    ///     .with("_trace", Parameter::String("t".into()))?;
264    ///
265    /// assert_eq!(meta.strip_internal(), 2);
266    /// assert_eq!(meta.len(), 1);
267    /// assert!(meta.contains_key("seq"));
268    /// # Ok::<(), astrs_wire::IdError>(())
269    /// ```
270    pub fn strip_internal(&mut self) -> usize {
271        let before = self.parameters.len();
272        self.parameters.retain(|key, _| !key.is_internal());
273        before - self.parameters.len()
274    }
275
276    /// A copy with the internal parameters removed.
277    ///
278    /// # Examples
279    ///
280    /// ```
281    /// use astrs_wire::{Metadata, Parameter};
282    /// use astrs_time::HlcTimestamp;
283    ///
284    /// let meta = Metadata::new(HlcTimestamp::EPOCH)
285    ///     .with("_schema_hash", Parameter::String("abc".into()))?;
286    /// assert!(meta.stripped().is_empty());
287    /// assert_eq!(meta.len(), 1, "the original is untouched");
288    /// # Ok::<(), astrs_wire::IdError>(())
289    /// ```
290    #[must_use]
291    pub fn stripped(&self) -> Self {
292        let mut copy = self.clone();
293        copy.strip_internal();
294        copy
295    }
296
297    /// Whether this message is *correlated* — carries a `request_id`,
298    /// `goal_id` or `goal_status`.
299    ///
300    /// Blueprint §11.2: correlated messages are immune to queue eviction,
301    /// because dropping a service response or a goal-status update would wedge
302    /// a client forever.
303    ///
304    /// # Examples
305    ///
306    /// ```
307    /// use astrs_wire::{Metadata, Parameter};
308    /// use astrs_time::HlcTimestamp;
309    ///
310    /// let plain = Metadata::new(HlcTimestamp::EPOCH).with("seq", Parameter::Integer(1))?;
311    /// assert!(!plain.is_correlated());
312    ///
313    /// let correlated = plain.clone().with("request_id", Parameter::String("r".into()))?;
314    /// assert!(correlated.is_correlated());
315    /// # Ok::<(), astrs_wire::IdError>(())
316    /// ```
317    #[must_use]
318    pub fn is_correlated(&self) -> bool {
319        keys::CORRELATION
320            .iter()
321            .any(|key| self.parameters.contains_key(*key))
322    }
323
324    /// Whether this message is part of a stream (`session_id` present).
325    #[must_use]
326    pub fn is_stream_chunk(&self) -> bool {
327        self.contains_key(keys::SESSION_ID)
328    }
329
330    /// Derives the metadata for a message produced *in response to* this one.
331    ///
332    /// This is the `meta.follow()` of the node API example in blueprint §9.1.
333    /// It preserves exactly the keys that must survive a hop — the correlation
334    /// keys and the stream keys — and drops everything else, including all
335    /// internal plumbing, which the sender will re-stamp for its own payload.
336    /// The timestamp is inherited so that causality is visible in a recording;
337    /// callers with a live clock should overwrite it with a fresh reading.
338    ///
339    /// # Examples
340    ///
341    /// ```
342    /// use astrs_wire::{Metadata, Parameter};
343    /// use astrs_time::HlcTimestamp;
344    ///
345    /// let incoming = Metadata::new(HlcTimestamp::new(5, 0))
346    ///     .with("request_id", Parameter::String("r-1".into()))?
347    ///     .with("seq", Parameter::Integer(9))?
348    ///     .with("user_note", Parameter::String("ignored".into()))?
349    ///     .with("_schema_hash", Parameter::String("h".into()))?;
350    ///
351    /// let outgoing = incoming.follow();
352    /// assert_eq!(outgoing.request_id(), Some("r-1"));
353    /// assert_eq!(outgoing.seq(), Some(9));
354    /// assert!(!outgoing.contains_key("user_note"));
355    /// assert!(!outgoing.contains_key("_schema_hash"));
356    /// assert_eq!(outgoing.timestamp, incoming.timestamp);
357    /// # Ok::<(), astrs_wire::IdError>(())
358    /// ```
359    #[must_use]
360    pub fn follow(&self) -> Self {
361        let parameters = self
362            .parameters
363            .iter()
364            .filter(|(key, _)| {
365                keys::is_correlation_key(key.as_str()) || keys::is_stream_key(key.as_str())
366            })
367            .map(|(key, value)| (key.clone(), value.clone()))
368            .collect();
369        Self {
370            version: METADATA_VERSION,
371            timestamp: self.timestamp,
372            parameters,
373        }
374    }
375
376    /// The `request_id`, if present.
377    #[must_use]
378    pub fn request_id(&self) -> Option<&str> {
379        self.get(keys::REQUEST_ID).and_then(Parameter::as_str)
380    }
381
382    /// Sets the `request_id`.
383    pub fn set_request_id(&mut self, id: impl Into<String>) {
384        self.set_known(keys::REQUEST_ID, Parameter::String(id.into()));
385    }
386
387    /// The `goal_id`, if present.
388    #[must_use]
389    pub fn goal_id(&self) -> Option<&str> {
390        self.get(keys::GOAL_ID).and_then(Parameter::as_str)
391    }
392
393    /// Sets the `goal_id`.
394    pub fn set_goal_id(&mut self, id: impl Into<String>) {
395        self.set_known(keys::GOAL_ID, Parameter::String(id.into()));
396    }
397
398    /// The `goal_status`, if present and recognised.
399    ///
400    /// A status code this build does not know yields `None`; the raw integer
401    /// is still readable through [`Metadata::get`].
402    #[must_use]
403    pub fn goal_status(&self) -> Option<GoalStatus> {
404        self.get(keys::GOAL_STATUS)
405            .and_then(Parameter::as_integer)
406            .and_then(GoalStatus::from_i64)
407    }
408
409    /// Sets the `goal_status`.
410    pub fn set_goal_status(&mut self, status: GoalStatus) {
411        self.set_known(keys::GOAL_STATUS, Parameter::Integer(status.as_i64()));
412    }
413
414    /// The `session_id`, if present.
415    #[must_use]
416    pub fn session_id(&self) -> Option<&str> {
417        self.get(keys::SESSION_ID).and_then(Parameter::as_str)
418    }
419
420    /// Sets the `session_id`.
421    pub fn set_session_id(&mut self, id: impl Into<String>) {
422        self.set_known(keys::SESSION_ID, Parameter::String(id.into()));
423    }
424
425    /// The `segment_id`, if present.
426    #[must_use]
427    pub fn segment_id(&self) -> Option<i64> {
428        self.get(keys::SEGMENT_ID).and_then(Parameter::as_integer)
429    }
430
431    /// Sets the `segment_id`.
432    pub fn set_segment_id(&mut self, segment: i64) {
433        self.set_known(keys::SEGMENT_ID, Parameter::Integer(segment));
434    }
435
436    /// The `seq`, if present.
437    #[must_use]
438    pub fn seq(&self) -> Option<i64> {
439        self.get(keys::SEQ).and_then(Parameter::as_integer)
440    }
441
442    /// Sets the `seq`.
443    pub fn set_seq(&mut self, seq: i64) {
444        self.set_known(keys::SEQ, Parameter::Integer(seq));
445    }
446
447    /// The `fin` flag, if present.
448    #[must_use]
449    pub fn fin(&self) -> Option<bool> {
450        self.get(keys::FIN).and_then(Parameter::as_bool)
451    }
452
453    /// Sets the `fin` flag.
454    pub fn set_fin(&mut self, fin: bool) {
455        self.set_known(keys::FIN, Parameter::Bool(fin));
456    }
457
458    /// The `flush` flag, if present.
459    #[must_use]
460    pub fn flush(&self) -> Option<bool> {
461        self.get(keys::FLUSH).and_then(Parameter::as_bool)
462    }
463
464    /// Sets the `flush` flag.
465    pub fn set_flush(&mut self, flush: bool) {
466        self.set_known(keys::FLUSH, Parameter::Bool(flush));
467    }
468
469    /// The internal `_schema_hash`, if present.
470    #[must_use]
471    pub fn schema_hash(&self) -> Option<&str> {
472        self.get(keys::SCHEMA_HASH).and_then(Parameter::as_str)
473    }
474
475    /// Stamps the internal `_schema_hash`.
476    ///
477    /// Set by the sending side from `astrs-data`'s `SchemaHash` so receivers
478    /// can cache decoded schemas and detect type drift cheaply (§6.1).
479    pub fn insert_schema_hash(&mut self, hash: impl Into<String>) {
480        self.set_known(keys::SCHEMA_HASH, Parameter::String(hash.into()));
481    }
482
483    /// Inserts under a well-known key.
484    ///
485    /// Every constant in [`keys`] is a valid [`ParamKey`] by construction —
486    /// asserted by a test in that module — so this cannot fail; the `if let`
487    /// keeps the function total without a panic path.
488    fn set_known(&mut self, key: &str, value: Parameter) {
489        if let Ok(key) = ParamKey::new(key) {
490            self.parameters.insert(key, value);
491        }
492    }
493
494    /// Bitwise equality, so that metadata carrying a `NaN` float compares
495    /// equal to itself.
496    ///
497    /// See [`Parameter::bitwise_eq`].
498    #[must_use]
499    pub fn bitwise_eq(&self, other: &Self) -> bool {
500        self.version == other.version
501            && self.timestamp == other.timestamp
502            && self.parameters.len() == other.parameters.len()
503            && self
504                .parameters
505                .iter()
506                .zip(other.parameters.iter())
507                .all(|((lk, lv), (rk, rv))| lk == rk && lv.bitwise_eq(rv))
508    }
509}
510
511impl Default for Metadata {
512    /// Empty metadata stamped at [`HlcTimestamp::EPOCH`].
513    fn default() -> Self {
514        Self::new(HlcTimestamp::EPOCH)
515    }
516}
517
518impl<'a> IntoIterator for &'a Metadata {
519    type Item = (&'a ParamKey, &'a Parameter);
520    type IntoIter = Iter<'a, ParamKey, Parameter>;
521
522    fn into_iter(self) -> Self::IntoIter {
523        self.parameters.iter()
524    }
525}
526
527impl Encode for Metadata {
528    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), oxicode::error::Error> {
529        self.version.encode(encoder)?;
530        self.timestamp.encode(encoder)?;
531        self.parameters.encode(encoder)
532    }
533}
534
535impl Decode for Metadata {
536    /// Not generic over `oxicode`'s decode context: the fields this reads
537    /// (`HlcTimestamp`, `Parameter`) are `#[derive(Decode)]` types, and the
538    /// derive emits context-free implementations.
539    fn decode<D: Decoder<Context = ()>>(decoder: &mut D) -> Result<Self, oxicode::error::Error> {
540        let version = u16::decode(decoder)?;
541        let timestamp = HlcTimestamp::decode(decoder)?;
542        let parameters = BTreeMap::<ParamKey, Parameter>::decode(decoder)?;
543        if parameters.len() > MAX_PARAMETERS {
544            return Err(codec_invalid(format!(
545                "metadata carries {} parameters, over the {MAX_PARAMETERS} limit",
546                parameters.len()
547            )));
548        }
549        Ok(Self {
550            version,
551            timestamp,
552            parameters,
553        })
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
560
561    use super::*;
562    use crate::codec::{WireDecode, WireEncode};
563
564    fn sample() -> Metadata {
565        let mut meta = Metadata::new(HlcTimestamp::new(1_700_000_000_000_000_000, 3));
566        meta.set_request_id("req-1");
567        meta.set_goal_id("goal-1");
568        meta.set_goal_status(GoalStatus::Executing);
569        meta.set_session_id("sess-1");
570        meta.set_segment_id(2);
571        meta.set_seq(7);
572        meta.set_fin(false);
573        meta.set_flush(true);
574        meta.insert_schema_hash("0123abcd");
575        meta
576    }
577
578    #[test]
579    fn every_well_known_key_is_a_valid_param_key() {
580        for key in keys::WELL_KNOWN {
581            assert!(ParamKey::new(*key).is_ok(), "{key} must be a valid key");
582        }
583    }
584
585    #[test]
586    fn typed_accessors_round_trip_through_the_map() {
587        let meta = sample();
588        assert_eq!(meta.request_id(), Some("req-1"));
589        assert_eq!(meta.goal_id(), Some("goal-1"));
590        assert_eq!(meta.goal_status(), Some(GoalStatus::Executing));
591        assert_eq!(meta.session_id(), Some("sess-1"));
592        assert_eq!(meta.segment_id(), Some(2));
593        assert_eq!(meta.seq(), Some(7));
594        assert_eq!(meta.fin(), Some(false));
595        assert_eq!(meta.flush(), Some(true));
596        assert_eq!(meta.schema_hash(), Some("0123abcd"));
597        assert_eq!(meta.len(), keys::WELL_KNOWN.len());
598    }
599
600    #[test]
601    fn absent_keys_read_as_none() {
602        let meta = Metadata::default();
603        assert_eq!(meta.request_id(), None);
604        assert_eq!(meta.goal_id(), None);
605        assert_eq!(meta.goal_status(), None);
606        assert_eq!(meta.session_id(), None);
607        assert_eq!(meta.segment_id(), None);
608        assert_eq!(meta.seq(), None);
609        assert_eq!(meta.fin(), None);
610        assert_eq!(meta.flush(), None);
611        assert_eq!(meta.schema_hash(), None);
612        assert!(meta.is_empty());
613        assert_eq!(meta.timestamp, HlcTimestamp::EPOCH);
614    }
615
616    #[test]
617    fn a_wrongly_typed_well_known_key_reads_as_none() {
618        let mut meta = Metadata::default();
619        meta.insert(keys::SEQ, Parameter::String("three".into()))
620            .unwrap();
621        assert_eq!(meta.seq(), None, "a string seq must not coerce");
622        assert!(meta.contains_key(keys::SEQ));
623    }
624
625    #[test]
626    fn an_unknown_goal_status_code_reads_as_none() {
627        let mut meta = Metadata::default();
628        meta.insert(keys::GOAL_STATUS, Parameter::Integer(99))
629            .unwrap();
630        assert_eq!(meta.goal_status(), None);
631        assert!(meta.is_correlated(), "the key is still a correlation key");
632    }
633
634    #[test]
635    fn insert_replaces_and_reports_the_old_value() {
636        let mut meta = Metadata::default();
637        assert_eq!(meta.insert("k", Parameter::Integer(1)).unwrap(), None);
638        assert_eq!(
639            meta.insert("k", Parameter::Integer(2)).unwrap(),
640            Some(Parameter::Integer(1))
641        );
642        assert_eq!(meta.get("k"), Some(&Parameter::Integer(2)));
643        assert_eq!(meta.remove("k"), Some(Parameter::Integer(2)));
644        assert_eq!(meta.remove("k"), None);
645    }
646
647    #[test]
648    fn invalid_keys_are_refused() {
649        let mut meta = Metadata::default();
650        assert!(meta.insert("bad key", Parameter::Bool(true)).is_err());
651        assert!(meta.insert("", Parameter::Bool(true)).is_err());
652        assert!(meta.is_empty());
653        assert!(
654            Metadata::default()
655                .with("also/bad", Parameter::Bool(true))
656                .is_err()
657        );
658    }
659
660    #[test]
661    fn insert_key_takes_a_validated_key() {
662        let mut meta = Metadata::default();
663        let key = ParamKey::new("k").unwrap();
664        assert_eq!(meta.insert_key(key.clone(), Parameter::Bool(true)), None);
665        assert_eq!(
666            meta.insert_key(key, Parameter::Bool(false)),
667            Some(Parameter::Bool(true))
668        );
669    }
670
671    #[test]
672    fn strip_internal_removes_only_underscore_keys() {
673        let mut meta = sample();
674        meta.insert("_trace", Parameter::String("t".into()))
675            .unwrap();
676        let before = meta.len();
677        let removed = meta.strip_internal();
678        assert_eq!(removed, 2, "_schema_hash and _trace");
679        assert_eq!(meta.len(), before - 2);
680        assert!(meta.keys().all(|key| !key.is_internal()));
681        assert_eq!(meta.request_id(), Some("req-1"));
682        assert_eq!(meta.strip_internal(), 0, "stripping again is a no-op");
683    }
684
685    #[test]
686    fn stripped_leaves_the_original_alone() {
687        let meta = sample();
688        let stripped = meta.stripped();
689        assert!(stripped.schema_hash().is_none());
690        assert!(meta.schema_hash().is_some());
691        assert_eq!(stripped.len() + 1, meta.len());
692    }
693
694    #[test]
695    fn correlation_detection_matches_the_key_set() {
696        assert!(!Metadata::default().is_correlated());
697        for key in keys::CORRELATION {
698            let mut meta = Metadata::default();
699            meta.insert(key, Parameter::String("x".into())).unwrap();
700            assert!(meta.is_correlated(), "{key} must make a message correlated");
701        }
702        for key in keys::STREAM {
703            let mut meta = Metadata::default();
704            meta.insert(key, Parameter::Integer(1)).unwrap();
705            assert!(!meta.is_correlated(), "{key} must not");
706        }
707    }
708
709    #[test]
710    fn stream_chunk_detection() {
711        assert!(!Metadata::default().is_stream_chunk());
712        let mut meta = Metadata::default();
713        meta.set_session_id("s");
714        assert!(meta.is_stream_chunk());
715    }
716
717    #[test]
718    fn follow_keeps_correlation_and_stream_keys_only() {
719        let mut source = sample();
720        source.insert("user", Parameter::Integer(1)).unwrap();
721        let derived = source.follow();
722
723        for key in keys::CORRELATION.iter().chain(keys::STREAM.iter()) {
724            assert!(derived.contains_key(key), "{key} must survive follow()");
725        }
726        assert!(!derived.contains_key("user"));
727        assert!(!derived.contains_key(keys::SCHEMA_HASH));
728        assert_eq!(derived.timestamp, source.timestamp);
729        assert_eq!(derived.version, METADATA_VERSION);
730    }
731
732    #[test]
733    fn follow_of_empty_metadata_is_empty() {
734        let derived = Metadata::new(HlcTimestamp::new(4, 1)).follow();
735        assert!(derived.is_empty());
736        assert_eq!(derived.timestamp, HlcTimestamp::new(4, 1));
737    }
738
739    #[test]
740    fn codec_round_trips_the_full_sample() {
741        let meta = sample();
742        let bytes = meta.encode_to_vec().unwrap();
743        assert_eq!(bytes.len(), meta.encode_size_hint().unwrap());
744        assert_eq!(Metadata::decode_exact(&bytes).unwrap(), meta);
745    }
746
747    #[test]
748    fn codec_round_trips_empty_metadata_cheaply() {
749        let meta = Metadata::default();
750        let bytes = meta.encode_to_vec().unwrap();
751        // version (varint 1) + timestamp + empty-map length.
752        assert!(
753            bytes.len() <= 8,
754            "empty metadata cost {} bytes",
755            bytes.len()
756        );
757        assert_eq!(Metadata::decode_exact(&bytes).unwrap(), meta);
758    }
759
760    #[test]
761    fn encoding_is_deterministic_regardless_of_insertion_order() {
762        let mut forwards = Metadata::new(HlcTimestamp::new(1, 1));
763        let mut backwards = Metadata::new(HlcTimestamp::new(1, 1));
764        for key in ["a", "b", "c", "d"] {
765            forwards.insert(key, Parameter::String(key.into())).unwrap();
766        }
767        for key in ["d", "c", "b", "a"] {
768            backwards
769                .insert(key, Parameter::String(key.into()))
770                .unwrap();
771        }
772        assert_eq!(
773            forwards.encode_to_vec().unwrap(),
774            backwards.encode_to_vec().unwrap()
775        );
776    }
777
778    #[test]
779    fn decoding_rejects_an_invalid_parameter_key() {
780        let forged = (
781            METADATA_VERSION,
782            HlcTimestamp::EPOCH,
783            BTreeMap::from([("bad key".to_owned(), Parameter::Bool(true))]),
784        )
785            .encode_to_vec()
786            .unwrap();
787        assert!(Metadata::decode_exact(&forged).is_err());
788    }
789
790    #[test]
791    fn decoding_rejects_too_many_parameters() {
792        let mut oversized = BTreeMap::new();
793        for index in 0..=MAX_PARAMETERS {
794            oversized.insert(format!("k{index}"), Parameter::Integer(index as i64));
795        }
796        let forged = (METADATA_VERSION, HlcTimestamp::EPOCH, oversized)
797            .encode_to_vec()
798            .unwrap();
799        assert!(Metadata::decode_exact(&forged).is_err());
800    }
801
802    #[test]
803    fn a_future_metadata_version_still_decodes() {
804        // Forward compatibility: an unknown layout version is carried, not
805        // rejected, so a newer sender's metadata survives an old recorder.
806        let forged = (
807            METADATA_VERSION + 7,
808            HlcTimestamp::new(9, 0),
809            BTreeMap::<ParamKey, Parameter>::new(),
810        )
811            .encode_to_vec()
812            .unwrap();
813        let decoded = Metadata::decode_exact(&forged).unwrap();
814        assert_eq!(decoded.version, METADATA_VERSION + 7);
815    }
816
817    #[test]
818    fn bitwise_equality_covers_nan_parameters() {
819        let mut left = Metadata::new(HlcTimestamp::new(1, 0));
820        left.insert("f", Parameter::Float(f64::NAN)).unwrap();
821        let right = left.clone();
822        assert_ne!(left, right, "PartialEq cannot see NaN as equal");
823        assert!(left.bitwise_eq(&right));
824
825        let mut other = Metadata::new(HlcTimestamp::new(2, 0));
826        other.insert("f", Parameter::Float(f64::NAN)).unwrap();
827        assert!(!left.bitwise_eq(&other), "timestamps differ");
828    }
829
830    #[test]
831    fn iteration_is_in_key_order() {
832        let mut meta = Metadata::default();
833        for key in ["z", "a", "m"] {
834            meta.insert(key, Parameter::Integer(0)).unwrap();
835        }
836        let order: Vec<_> = meta.keys().map(ParamKey::as_str).collect();
837        assert_eq!(order, vec!["a", "m", "z"]);
838        assert_eq!(meta.values().count(), 3);
839        assert_eq!(meta.iter().count(), 3);
840        assert_eq!((&meta).into_iter().count(), 3);
841    }
842
843    #[test]
844    fn entry_supports_read_modify_write() {
845        let mut meta = Metadata::default();
846        let key = ParamKey::new("counter").unwrap();
847        meta.entry(key.clone()).or_insert(Parameter::Integer(0));
848        if let Some(Parameter::Integer(value)) = meta.parameters.get_mut(&key) {
849            *value += 5;
850        }
851        assert_eq!(meta.get("counter").and_then(Parameter::as_integer), Some(5));
852    }
853
854    #[test]
855    fn serde_round_trips() {
856        let meta = sample();
857        let json = serde_json::to_string(&meta).unwrap();
858        assert_eq!(serde_json::from_str::<Metadata>(&json).unwrap(), meta);
859        assert!(json.contains("\"version\""));
860        assert!(json.contains("\"timestamp\""));
861        assert!(json.contains("\"parameters\""));
862    }
863}