Skip to main content

moq_json/snapshot/
encoder.rs

1//! The track-free half of snapshot publishing: values in, frame payloads out.
2
3use std::cell::RefCell;
4use std::marker::PhantomData;
5use std::sync::OnceLock;
6
7use bytes::Bytes;
8use serde::Serialize;
9use serde_json::Value;
10
11use crate::Result;
12
13/// Maximum frames (snapshot + deltas) in a single group before a new snapshot is forced.
14///
15/// Kept well below moq-net's per-group frame cap so a late joiner can always read the snapshot
16/// at frame 0 before the group is evicted.
17pub(super) const MAX_DELTA_FRAMES: usize = 256;
18
19/// What an [`Encoder`] keeps of the value it last emitted.
20///
21/// A delta is a diff against the previous value, so one has to be parsed to diff against
22/// whenever deltas are possible. With [`Config::deltas`] off none ever are, and the only question
23/// an update asks of the baseline is whether the value changed at all, which the encoded
24/// bytes answer directly. The parse is deferred in that case, and a value that is only ever
25/// published never pays for one.
26enum Baseline {
27	/// Deltas are possible, so the baseline is kept parsed and ready to diff against.
28	Parsed(Value),
29
30	/// Deltas are disabled. The emitted bytes (shared with the frame payload) stand in for the
31	/// value, parsed only if a caller reads it back.
32	Encoded {
33		bytes: Bytes,
34		parsed: OnceLock<Option<Value>>,
35	},
36}
37
38impl Baseline {
39	/// The baseline as a parsed value, parsing the encoded bytes on first use.
40	fn value(&self) -> Option<&Value> {
41		match self {
42			Self::Parsed(value) => Some(value),
43			// Serialized by us, so this parses unless the caller's `Serialize` emitted
44			// something `serde_json` will not read back.
45			Self::Encoded { bytes, parsed } => parsed.get_or_init(|| serde_json::from_slice(bytes).ok()).as_ref(),
46		}
47	}
48}
49
50/// Codec options for an [`Encoder`], and so for the [`Producer`](super::Producer) wrapping one.
51///
52/// Build from [`Default`] and override fields (the struct is `#[non_exhaustive]`, so new
53/// options stay additive), or chain [`with_deltas`](Self::with_deltas).
54///
55/// How long a group runs is not a codec option: a group grows until a joiner wants a fresh one,
56/// judged by the track's [`refresh`](moq_net::track::Info::refresh) ratio, or until it reaches
57/// the frame or byte cap.
58#[derive(Debug, Clone)]
59#[non_exhaustive]
60pub struct Config {
61	/// Whether changes ride as merge-patch deltas in the open group.
62	///
63	/// `false` makes every change its own single-frame snapshot group, identical on the wire to a
64	/// plain "one JSON blob per group" track, so refresh never applies.
65	///
66	/// Defaults to `true`.
67	pub deltas: bool,
68
69	/// The most bytes a group may hold, snapshot and deltas together.
70	///
71	/// A delta that would pass it rolls a fresh snapshot instead, and a snapshot past it is refused
72	/// with [`FrameTooLarge`](moq_net::Error::FrameTooLarge). Lowering it lets a test reach the limit
73	/// without megabytes of JSON; a value above 32 MiB, what moq-net's group cache holds, is clamped
74	/// to it.
75	///
76	/// Defaults to 32 MiB.
77	pub max_group_bytes: u64,
78}
79
80impl Config {
81	/// Set [`deltas`](Self::deltas) (a builder, since the struct is `#[non_exhaustive]`).
82	pub fn with_deltas(mut self, deltas: bool) -> Self {
83		self.deltas = deltas;
84		self
85	}
86
87	/// Set [`max_group_bytes`](Self::max_group_bytes).
88	pub fn with_max_group_bytes(mut self, max_group_bytes: u64) -> Self {
89		self.max_group_bytes = max_group_bytes;
90		self
91	}
92}
93
94impl Default for Config {
95	fn default() -> Self {
96		Self {
97			deltas: true,
98			max_group_bytes: crate::MAX_GROUP_BYTES,
99		}
100	}
101}
102
103/// One encoded frame, and the group boundary it implies.
104#[derive(Clone, Debug)]
105pub struct Encoded {
106	/// The frame payload: a full JSON snapshot or a merge patch.
107	pub payload: Bytes,
108
109	/// Whether this frame is a full snapshot, which must open a new group.
110	///
111	/// `true` means the caller writes it as the first frame of a fresh group; `false` means it is a
112	/// merge patch that must be appended to the group the last snapshot opened. Mapping straight onto
113	/// [`moq_mux::container::Frame::keyframe`] is the point of the name.
114	///
115	/// The encoder decides this for an [`update`](Encoder::update): a value that sets a field to JSON
116	/// null, or whose root isn't an object, cannot be expressed as a merge patch at all, and the
117	/// group's frame and byte caps force a snapshot independently of what the caller wanted. A caller
118	/// asks for one with [`snapshot`](Encoder::snapshot).
119	///
120	/// [`moq_mux::container::Frame::keyframe`]: https://docs.rs/moq-mux/latest/moq_mux/container/struct.Frame.html
121	pub keyframe: bool,
122}
123
124/// An encoded frame the caller has not yet acknowledged writing.
125///
126/// Returned by [`Encoder::update`]. Read [`payload`](Encoded::payload) and
127/// [`keyframe`](Encoded::keyframe) through the [`Deref`](std::ops::Deref) to [`Encoded`], write the
128/// frame, then [`commit`](Self::commit).
129///
130/// The frame's value is staged until commit, so dropping it uncommitted leaves
131/// [`Encoder::value`] at the last value that reached the wire, and [`Encoder::reset`]s so the next
132/// frame is a fresh snapshot rather than a delta against a group no consumer received. The group
133/// state is a recovery, not a rollback: a consumer may hold a group the dropped frame was meant
134/// for, so a snapshot is the only sound way back. Forgetting to commit
135/// a frame that *was* written therefore costs one redundant snapshot and leaves the value a step
136/// behind, but never corrupts the stream.
137#[must_use = "the frame must be written and committed, or dropped to resynchronize the encoder"]
138pub struct Pending<'a, T> {
139	encoder: &'a mut Encoder<T>,
140	encoded: Encoded,
141	edit: Option<Edit>,
142}
143
144/// The baseline change staged behind a [`Pending`] frame.
145enum Edit {
146	/// A snapshot replaces the baseline.
147	Snapshot(Baseline),
148	/// A delta folds this merge patch into the baseline.
149	Delta(Bytes),
150	/// A snapshot restating the baseline as it is, which changes nothing.
151	Restate,
152}
153
154impl<T> Pending<'_, T> {
155	/// Acknowledge that the frame reached the wire, applying its value to the baseline.
156	///
157	/// Only call this once the write has actually succeeded. Committing a frame that failed to write
158	/// is the one thing that corrupts the stream.
159	pub fn commit(mut self) {
160		let edit = self.edit.take().expect("pending edit");
161		self.encoder.commit(edit);
162	}
163}
164
165impl<T> std::ops::Deref for Pending<'_, T> {
166	type Target = Encoded;
167
168	fn deref(&self) -> &Encoded {
169		&self.encoded
170	}
171}
172
173impl<T> Drop for Pending<'_, T> {
174	fn drop(&mut self) {
175		if self.edit.is_some() {
176			self.encoder.reset();
177		}
178	}
179}
180
181/// Encodes a JSON value into frame payloads, choosing snapshots and deltas automatically.
182///
183/// The track-free core of [`Producer`](super::Producer): it decides *what bytes go in a frame* and
184/// *where the group boundaries fall*, and leaves writing them to the caller. Reach for it when
185/// something else already owns the track, for example a
186/// [`moq_mux::container::Producer`](https://docs.rs/moq-mux/latest/moq_mux/container/struct.Producer.html)
187/// that is also managing a timeline and a catalog estimate:
188///
189/// ```ignore
190/// if let Some(frame) = encoder.update(&value)? {
191///     container.write(moq_mux::container::Frame {
192///         timestamp,
193///         decode: None,
194///         duration: None,
195///         payload: frame.payload.clone(),
196///         keyframe: frame.keyframe,
197///     })?; // an early return here drops `frame`, resetting the encoder
198///     frame.commit();
199/// }
200/// ```
201///
202/// Frames must reach the wire in the order they were encoded, and a frame with
203/// [`keyframe`](Encoded::keyframe) set must open a new group: the merge patches depend on it. [`update`](Self::update) hands back a [`Pending`]
204/// rather than a bare [`Encoded`] so a frame that never reaches the wire can't silently desync the
205/// encoder: dropping it uncommitted [`reset`](Self::reset)s, and the next value is encoded as a
206/// fresh snapshot. Committing a frame you failed to write is the one way to corrupt the stream.
207///
208/// If the caller cuts a group for its own reasons (a `cut`, `seek`, or discontinuity), call
209/// [`reset`](Self::reset) directly so the next value opens the new group with a snapshot. To open
210/// one right away, such as when a joiner wants a fresh group (see
211/// [`Demand::wanted`](moq_net::track::Demand::wanted)), call [`snapshot`](Self::snapshot).
212pub struct Encoder<T> {
213	config: Config,
214
215	/// The last committed value, the baseline every delta is diffed against. `None` until the first
216	/// snapshot commits, which is what makes that first [`update`](Self::update) a keyframe.
217	last: Option<Baseline>,
218
219	/// Reused key buffers for comparing unchanged fields without per-update allocations, and the
220	/// memoized root entries that let an unchanged entry skip the baseline walk.
221	scratch: RefCell<crate::diff::Scratch>,
222
223	/// Bytes charged to the current group, snapshot included.
224	group_bytes: u64,
225
226	/// Frames emitted into the current group, snapshot included.
227	group_frames: usize,
228
229	/// [`Config::max_group_bytes`], clamped to moq-net's cache limit.
230	max_group_bytes: u64,
231
232	/// Whether the next frame has to be a full snapshot, because a frame was lost or the caller cut
233	/// the group. Kept separate from [`last`](Self::last) so a resync doesn't erase the value: that
234	/// field is also what [`Producer::modify`](super::Producer::modify) seeds an edit from, and dropping
235	/// it there would publish a document with every other field missing.
236	resync: bool,
237
238	_marker: PhantomData<fn(T)>,
239}
240
241impl<T> Encoder<T> {
242	/// Create an encoder with a cold baseline, so the first [`update`](Self::update) is a snapshot.
243	pub fn new(config: Config) -> Self {
244		Self {
245			max_group_bytes: config.max_group_bytes.min(crate::MAX_GROUP_BYTES),
246			config,
247			last: None,
248			scratch: RefCell::new(crate::diff::Scratch::memoized()),
249			group_bytes: 0,
250			group_frames: 0,
251			resync: false,
252			_marker: PhantomData,
253		}
254	}
255
256	/// The last committed value, or `None` before the first snapshot commits.
257	///
258	/// This is the baseline the next delta is diffed against, which is what a caller editing the
259	/// value in place needs to start from. A frame dropped uncommitted never reached the wire, so its
260	/// value never lands here.
261	///
262	/// With deltas disabled the baseline is held as the encoded bytes, so the first call parses
263	/// them; the result is cached, and callers that never read the value never pay for it.
264	pub fn value(&self) -> Option<&Value> {
265		self.last.as_ref()?.value()
266	}
267
268	/// Force the next [`update`](Self::update) to emit a full snapshot, even for an unchanged value.
269	///
270	/// Call this whenever the caller closes the current group behind the encoder's back (a
271	/// `cut`, a `seek`, a discontinuity). Without it the next value may be encoded as a delta
272	/// against a baseline that the new group doesn't carry.
273	///
274	/// [`value`](Self::value) survives: the snapshot republishes it in full anyway, and it is what a
275	/// caller editing in place starts from.
276	pub fn reset(&mut self) {
277		self.group_bytes = 0;
278		self.group_frames = 0;
279		self.resync = true;
280	}
281
282	/// Restate the last committed value as a full snapshot, which must open a new group.
283	///
284	/// For a caller that opens groups itself: call it when a joiner wants a fresh group, such as when
285	/// [`Demand::wanted`](moq_net::track::Demand::wanted) passes the largest group written. The new
286	/// group restates the value without the deltas before it, though that joiner still reads the
287	/// cached group first. Returns `None` before the first value,
288	/// when there is nothing to restate. The frame is a [`Pending`] like any other.
289	pub fn snapshot(&mut self) -> Result<Option<Pending<'_, T>>> {
290		let bytes = match &self.last {
291			None => return Ok(None),
292			// A delta-free baseline is the emitted bytes already.
293			Some(Baseline::Encoded { bytes, .. }) => bytes.clone(),
294			Some(Baseline::Parsed(value)) => Bytes::from(serde_json::to_vec(value)?),
295		};
296		// A baseline built by patches was never held to the budget as one snapshot.
297		self.check_snapshot(&bytes)?;
298		let encoded = self.snapshot_encoded(bytes);
299		Ok(Some(Pending {
300			encoder: self,
301			encoded,
302			edit: Some(Edit::Restate),
303		}))
304	}
305
306	/// Apply a frame's staged value to the baseline once the frame reached the wire.
307	fn commit(&mut self, edit: Edit) {
308		match edit {
309			Edit::Snapshot(last) => {
310				self.last = Some(last);
311				// Seeded from the snapshot rather than a diff, so no root entry is memoized against it yet.
312				self.scratch.get_mut().clear_memo();
313			}
314			Edit::Delta(patch) => {
315				// Reaching a delta means `delta_allowed`, which means deltas are on, which is what keeps
316				// the baseline parsed.
317				let Some(Baseline::Parsed(last)) = self.last.as_mut() else {
318					unreachable!("a parsed snapshot precedes any delta")
319				};
320				crate::merge::apply_generated_bytes(last, &patch)
321					.expect("the diff serializer emits a valid merge patch");
322				self.scratch.get_mut().commit_memo();
323			}
324			Edit::Restate => {}
325		}
326	}
327
328	/// Encode an already-serialized value as a full snapshot, staging it as the new baseline.
329	fn snapshot_staged(&mut self, snapshot: Bytes) -> Result<(Encoded, Edit)> {
330		// With deltas possible, read the baseline back out of those same bytes rather than
331		// serializing `value` a second time, so the baseline IS the emitted snapshot by
332		// construction. A `Serialize` impl reading a clock or interior mutable state would otherwise
333		// seed the baseline with a value no consumer ever received, and every later delta would
334		// rebase them onto it. `T` is also only visited once, which is what a caller with an
335		// expensive or effectful `Serialize` pays for.
336		//
337		// That trades a second walk of `T` for a parse of the bytes, so it is not automatically
338		// cheaper than `to_value` (see the `baseline` benchmark); consistency is the reason. With
339		// deltas off there is no diff to rebase and no reason to pay it at all.
340		//
341		// Every fallible step runs before any state changes, so a failure leaves the encoder exactly
342		// as it was rather than half-advanced with no frame to show for it. The size check runs
343		// first, so a value no reader could hold costs no parse.
344		self.check_snapshot(&snapshot)?;
345		let last = if self.config.deltas {
346			Baseline::Parsed(serde_json::from_slice(&snapshot)?)
347		} else {
348			// No delta will ever diff against this, so hold the bytes instead. They are the same
349			// allocation the payload carries, so the baseline costs a refcount.
350			Baseline::Encoded {
351				bytes: snapshot.clone(),
352				parsed: OnceLock::new(),
353			}
354		};
355
356		let encoded = self.snapshot_encoded(snapshot);
357		Ok((encoded, Edit::Snapshot(last)))
358	}
359
360	/// Refuse a snapshot past the group budget before anything is published, so the previous value
361	/// stays readable rather than superseded by a frame moq-net would refuse on write.
362	fn check_snapshot(&self, snapshot: &[u8]) -> Result<()> {
363		match snapshot.len() as u64 > self.max_group_bytes {
364			true => Err(moq_net::Error::FrameTooLarge.into()),
365			false => Ok(()),
366		}
367	}
368
369	/// Encode an already-serialized value as a full snapshot, opening a new group.
370	fn snapshot_encoded(&mut self, snapshot: Bytes) -> Encoded {
371		self.group_bytes = snapshot.len() as u64;
372		self.group_frames = 1;
373		self.resync = false;
374
375		Encoded {
376			payload: snapshot,
377			keyframe: true,
378		}
379	}
380}
381
382impl<T: Serialize> Encoder<T> {
383	/// Encode a new value, as a snapshot or a delta.
384	///
385	/// Returns `None` when the value is unchanged from the last one committed, so nothing needs to be
386	/// written. Otherwise the frame comes back as a [`Pending`] the caller writes and then
387	/// [`commit`](Pending::commit)s; dropping it uncommitted resynchronizes the encoder.
388	pub fn update(&mut self, value: &T) -> Result<Option<Pending<'_, T>>> {
389		Ok(self.encode(value)?.map(|(encoded, edit)| Pending {
390			encoder: self,
391			encoded,
392			edit: Some(edit),
393		}))
394	}
395
396	/// Encode a new value into a bare frame and the baseline change it stages, advancing the group.
397	///
398	/// The state change is what [`Pending`] guards, so this stays private: every caller goes through
399	/// [`update`](Self::update) and has to say whether the frame reached the wire.
400	fn encode(&mut self, value: &T) -> Result<Option<(Encoded, Edit)>> {
401		// A lost frame, or a group the caller cut, leaves the consumer's state unknown. Re-seed with a
402		// full snapshot even when the value is unchanged, since the frame that carried it may never
403		// have landed.
404		if self.resync {
405			return self.encode_snapshot(value).map(Some);
406		}
407
408		// With deltas disabled there is nothing to diff, so the only question is whether the value
409		// changed: compare the encodings rather than parsing a baseline to diff against. The bytes
410		// are handed straight to the snapshot when it did change, so an update still serializes
411		// `T` exactly once.
412		if let Some(Baseline::Encoded { bytes, .. }) = self.last.as_ref() {
413			let bytes = bytes.clone();
414			let next = crate::strict::to_vec(value, 0)?;
415			if next.as_slice() == bytes.as_ref() {
416				return Ok(None);
417			}
418			return self.snapshot_staged(Bytes::from(next)).map(Some);
419		}
420
421		// The first update has no baseline to diff against, so it seeds the stream with a snapshot.
422		let Some(Baseline::Parsed(last)) = self.last.as_ref() else {
423			return self.encode_snapshot(value).map(Some);
424		};
425
426		// Diff without building a full `Value` for the new value first. `T` is written with the same
427		// `serde_json` writer a snapshot uses, and the diff reads those bytes entry by entry, so
428		// nothing past this line is compiled per `T`.
429		// A delta nests no deeper than the value it patches, so checking the value covers the delta.
430		crate::strict::to_writer(self.scratch.get_mut().next_buffer(), value, 0)?;
431		let crate::diff::PatchBytes { patch, forced_snapshot } =
432			crate::diff::serialized(last, &self.scratch).map_err(crate::Error::Json)?;
433
434		// An empty object patch with no forced null means the value is unchanged: encode nothing.
435		if !forced_snapshot && patch.is_empty() {
436			self.scratch.get_mut().commit_memo();
437			return Ok(None);
438		}
439
440		// A forced snapshot (a genuine null, or a non-object root) or a full group starts a
441		// new group; otherwise the change rides as a delta in the open one.
442		if forced_snapshot || !self.delta_allowed() {
443			return self.encode_snapshot(value).map(Some);
444		}
445
446		// A delta is only readable while the group still holds the snapshot it applies to.
447		// Admitting a patch that pushes the group past that budget would abort it
448		// (`GroupTooLarge`), leaving a late subscriber with no value. Roll a fresh snapshot
449		// instead, which is cheap next to losing the value.
450		let payload = Bytes::from(patch);
451		let charge = payload.len() as u64;
452		if self.group_bytes + charge > self.max_group_bytes {
453			self.reset();
454			return self.encode_snapshot(value).map(Some);
455		}
456
457		self.group_bytes += charge;
458		self.group_frames += 1;
459
460		// The patch folds into the baseline on commit, so a frame that never reaches the wire leaves
461		// the baseline at the last value consumers received.
462		let encoded = Encoded {
463			payload: payload.clone(),
464			keyframe: false,
465		};
466		Ok(Some((encoded, Edit::Delta(payload))))
467	}
468
469	/// Whether the current change may ride as a delta in the open group: deltas are on and the group
470	/// is under its frame cap. The byte cap is checked once the delta is encoded.
471	fn delta_allowed(&self) -> bool {
472		self.config.deltas && self.group_frames > 0 && self.group_frames < MAX_DELTA_FRAMES
473	}
474
475	/// Encode a full snapshot of `value`, opening a new group and staging it as the baseline.
476	fn encode_snapshot(&mut self, value: &T) -> Result<(Encoded, Edit)> {
477		// Serialize directly from `value` so the snapshot frame preserves the type's own field order,
478		// keeping the wire bytes identical to serializing `T` straight to a frame.
479		let snapshot = crate::strict::to_vec(value, 0)?;
480		self.snapshot_staged(Bytes::from(snapshot))
481	}
482}
483
484#[cfg(test)]
485mod test {
486	use super::*;
487	use serde_json::json;
488
489	// Mirror the JS generator: bounded JSON trees and edits to a persistent object.
490	fn property_key() -> impl proptest::strategy::Strategy<Value = String> {
491		use proptest::prelude::*;
492		prop_oneof![
493			proptest::sample::select(vec![
494				"a",
495				"b",
496				"c",
497				"",
498				"__proto__",
499				"constructor",
500				"prototype",
501				"\0",
502				"雪"
503			])
504			.prop_map(str::to_owned),
505			"[ -~]{0,8}",
506		]
507	}
508
509	fn property_value() -> proptest::strategy::BoxedStrategy<Value> {
510		use proptest::prelude::*;
511		let leaf = prop_oneof![
512			Just(Value::Null),
513			any::<bool>().prop_map(Value::Bool),
514			(-1_000_000i32..=1_000_000).prop_map(|n| Value::from(f64::from(n) / 4.0)),
515			prop_oneof!["[ -~]{0,16}", Just("雪\0".to_owned())].prop_map(Value::String),
516		];
517		leaf.prop_recursive(4, 64, 4, |inner| {
518			prop_oneof![
519				proptest::collection::vec(inner.clone(), 0..5).prop_map(Value::Array),
520				proptest::collection::btree_map(property_key(), inner, 0..5)
521					.prop_map(|map| Value::Object(map.into_iter().collect())),
522			]
523		})
524		.boxed()
525	}
526
527	#[derive(Clone, Debug)]
528	struct PropertyStep {
529		value: Value,
530		reset: bool,
531		/// Restate the previous value with [`Encoder::snapshot`] before this step.
532		restate: bool,
533	}
534
535	fn property_sequence() -> proptest::strategy::BoxedStrategy<Vec<PropertyStep>> {
536		use proptest::prelude::*;
537		let roots = proptest::collection::vec((property_value(), 0u8..16), 1..33).prop_map(|steps| {
538			steps
539				.into_iter()
540				.map(|(value, reset)| PropertyStep {
541					value,
542					reset: reset == 0,
543					restate: reset == 1,
544				})
545				.collect()
546		});
547		let edits = proptest::collection::vec((property_key(), property_value(), any::<bool>(), 0u8..16), 1..33)
548			.prop_map(|steps| {
549				let mut current = serde_json::Map::new();
550				steps
551					.into_iter()
552					.map(|(key, value, remove, reset)| {
553						if remove {
554							current.remove(&key);
555						} else {
556							current.insert(key, value);
557						}
558						PropertyStep {
559							value: Value::Object(current.clone()),
560							reset: reset == 0,
561							restate: reset == 1,
562						}
563					})
564					.collect()
565			});
566		prop_oneof![roots, edits].boxed()
567	}
568
569	#[test]
570	fn snapshot_codec_property_reconstructs_each_json_value() {
571		use proptest::prelude::*;
572		use proptest::test_runner::{Config as PropertyConfig, RngSeed, TestRunner};
573		let setting = |name: &str, fallback: u32, min: u32| {
574			let value = std::env::var(name).map_or(fallback, |value| {
575				value.parse::<u32>().expect("integer property setting")
576			});
577			assert!(
578				(min..=i32::MAX as u32).contains(&value),
579				"{name} outside supported range"
580			);
581			value
582		};
583		let seed = setting("MOQ_JSON_SEED", 0x6d6f71, 0);
584		let cases = setting("MOQ_JSON_CASES", 256, 1);
585		eprintln!("MOQ_JSON_SEED={seed} MOQ_JSON_CASES={cases}");
586		let mut runner = TestRunner::new(PropertyConfig {
587			cases,
588			rng_seed: RngSeed::Fixed(u64::from(seed)),
589			rng_algorithm: proptest::test_runner::RngAlgorithm::XorShift,
590			failure_persistence: None,
591			..Default::default()
592		});
593		let sequence = (any::<bool>(), property_sequence());
594		runner
595			.run(&sequence, |(deltas, steps)| {
596				let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(deltas));
597				let mut decoder = super::super::Decoder::<Value>::new(super::super::consumer::Config::default());
598				for (index, step) in steps.iter().enumerate() {
599					if step.reset {
600						encoder.reset();
601					}
602					if step.restate {
603						let previous = decoder.decode().unwrap();
604						match encoder.snapshot().unwrap() {
605							Some(frame) => {
606								prop_assert!(frame.keyframe);
607								decoder.snapshot(&frame.payload).unwrap();
608								frame.commit();
609							}
610							None => prop_assert!(index == 0, "a value was encoded before step {}", index),
611						}
612						prop_assert_eq!(decoder.decode().unwrap(), previous, "restate before step {}", index);
613					}
614					if let Some(frame) = encoder.update(&step.value).unwrap() {
615						if frame.keyframe {
616							decoder.snapshot(&frame.payload).unwrap();
617						} else {
618							decoder.delta(&frame.payload).unwrap();
619						}
620						frame.commit();
621					}
622					prop_assert_eq!(decoder.decode().unwrap(), Some(step.value.clone()), "step {}", index);
623				}
624				Ok(())
625			})
626			.unwrap();
627	}
628
629	#[test]
630	fn duplicate_serialized_keys_are_refused() {
631		use serde::ser::SerializeMap;
632		struct Duplicate {
633			duplicate: bool,
634		}
635		impl Serialize for Duplicate {
636			fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
637				let mut map = serializer.serialize_map(Some(2 + usize::from(self.duplicate)))?;
638				map.serialize_entry("a", &1)?;
639				map.serialize_entry("b", &2)?;
640				if self.duplicate {
641					map.serialize_entry("a", &3)?;
642				}
643				map.end()
644			}
645		}
646		let mut encoder = Encoder::<Duplicate>::new(Config::default());
647		encoder
648			.update(&Duplicate { duplicate: false })
649			.unwrap()
650			.unwrap()
651			.commit();
652		let err = encoder.update(&Duplicate { duplicate: true }).err().expect("refused");
653		assert!(err.to_string().contains("duplicate JSON object key"));
654	}
655
656	/// Encode a sequence of values, committing each frame, and return `(keyframe, payload_len)` per
657	/// emitted frame.
658	fn encode(config: Config, values: &[Value]) -> Vec<(bool, usize)> {
659		let mut encoder = Encoder::<Value>::new(config);
660		let mut out = Vec::new();
661		for value in values {
662			if let Some(frame) = encoder.update(value).unwrap() {
663				out.push((frame.keyframe, frame.payload.len()));
664				frame.commit();
665			}
666		}
667		out
668	}
669
670	/// Encode one value and commit it, returning the frame.
671	fn commit(encoder: &mut Encoder<Value>, value: &Value) -> Option<Encoded> {
672		let frame = encoder.update(value).unwrap()?;
673		let encoded = Encoded {
674			payload: frame.payload.clone(),
675			keyframe: frame.keyframe,
676		};
677		frame.commit();
678		Some(encoded)
679	}
680
681	#[test]
682	fn first_update_is_a_keyframe() {
683		let frames = encode(Config::default(), &[json!({ "a": 1 })]);
684		assert_eq!(frames.len(), 1);
685		assert!(frames[0].0);
686	}
687
688	#[test]
689	fn unchanged_value_encodes_nothing() {
690		let frames = encode(Config::default(), &[json!({ "a": 1 }), json!({ "a": 1 })]);
691		assert_eq!(frames.len(), 1);
692	}
693
694	#[test]
695	fn changes_ride_as_deltas() {
696		let frames = encode(
697			Config::default().with_deltas(true),
698			&[
699				json!({ "a": 1, "b": 1 }),
700				json!({ "a": 1, "b": 2 }),
701				json!({ "a": 1, "b": 3 }),
702			],
703		);
704		assert_eq!(frames.iter().map(|f| f.0).collect::<Vec<_>>(), vec![true, false, false]);
705	}
706
707	/// Without a joiner asking, a group runs on to the caps however much the deltas outweigh the
708	/// snapshot.
709	#[test]
710	fn deltas_never_roll_on_their_own() {
711		let big = "x".repeat(1024);
712		let values: Vec<Value> = (0..32).map(|n| json!({ "n": n, "pad": format!("{n}{big}") })).collect();
713		let frames = encode(Config::default(), &values);
714		assert_eq!(frames.iter().filter(|f| f.0).count(), 1);
715	}
716
717	/// `snapshot` restates the retained value as a keyframe, and the next change is a delta in the
718	/// group it opens.
719	#[test]
720	fn snapshot_restates_the_retained_value() {
721		for deltas in [true, false] {
722			let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(deltas));
723			assert!(encoder.snapshot().unwrap().is_none(), "nothing to restate yet");
724
725			commit(&mut encoder, &json!({ "a": 1 })).unwrap();
726			commit(&mut encoder, &json!({ "a": 2 })).unwrap();
727
728			let frame = encoder.snapshot().unwrap().unwrap();
729			assert!(frame.keyframe);
730			let mut decoder = super::super::Decoder::<Value>::new(super::super::consumer::Config::default());
731			decoder.snapshot(&frame.payload).unwrap();
732			frame.commit();
733			assert_eq!(decoder.decode().unwrap(), Some(json!({ "a": 2 })));
734
735			let next = commit(&mut encoder, &json!({ "a": 3 })).unwrap();
736			assert_eq!(next.keyframe, !deltas, "deltas={deltas}");
737			match next.keyframe {
738				true => decoder.snapshot(&next.payload).unwrap(),
739				false => decoder.delta(&next.payload).unwrap(),
740			}
741			assert_eq!(decoder.decode().unwrap(), Some(json!({ "a": 3 })));
742		}
743	}
744
745	/// A restatement that never reached the wire resynchronizes like any other lost frame.
746	#[test]
747	fn an_uncommitted_snapshot_resynchronizes() {
748		let mut encoder = Encoder::<Value>::new(Config::default());
749		commit(&mut encoder, &json!({ "a": 1 })).unwrap();
750		drop(encoder.snapshot().unwrap().unwrap());
751		assert!(commit(&mut encoder, &json!({ "a": 2 })).unwrap().keyframe);
752	}
753
754	#[test]
755	fn deltas_off_forces_a_keyframe_per_change() {
756		let frames = encode(
757			Config::default().with_deltas(false),
758			&[json!({ "a": 1 }), json!({ "a": 2 })],
759		);
760		assert_eq!(frames.iter().map(|f| f.0).collect::<Vec<_>>(), vec![true, true]);
761	}
762
763	/// Deltas off keeps the baseline as bytes rather than a parsed value, so the unchanged check
764	/// runs on the encoding. It still has to suppress a republish, or every stats tick would
765	/// re-emit an identical frame.
766	#[test]
767	fn deltas_off_still_skips_an_unchanged_value() {
768		let frames = encode(
769			Config::default().with_deltas(false),
770			&[json!({ "a": 1 }), json!({ "a": 1 }), json!({ "a": 1 })],
771		);
772		assert_eq!(frames.len(), 1);
773	}
774
775	/// Field order is part of the encoding, so a byte baseline only answers "unchanged" correctly
776	/// because `T` serializes deterministically. Same keys, different values, must still emit.
777	#[test]
778	fn deltas_off_detects_a_change_under_the_same_keys() {
779		let frames = encode(
780			Config::default().with_deltas(false),
781			&[json!({ "a": 1, "b": 2 }), json!({ "a": 1, "b": 3 })],
782		);
783		assert_eq!(frames.len(), 2);
784	}
785
786	/// The byte baseline is parsed on demand, so `value` (and so `Producer::modify`, which seeds an
787	/// edit from it) keeps working with deltas off. Dropping the baseline instead would make
788	/// `modify` start from `T::default()` and publish a document with every other field missing.
789	#[test]
790	fn deltas_off_still_exposes_the_value() {
791		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(false));
792		assert_eq!(encoder.value(), None);
793
794		commit(&mut encoder, &json!({ "a": 1, "b": 2 })).unwrap();
795		assert_eq!(encoder.value(), Some(&json!({ "a": 1, "b": 2 })));
796
797		commit(&mut encoder, &json!({ "a": 1, "b": 3 })).unwrap();
798		assert_eq!(encoder.value(), Some(&json!({ "a": 1, "b": 3 })));
799	}
800
801	/// A value the caller might reasonably expect to be a delta, but that merge patch can't express:
802	/// setting a field to JSON null reads as a key deletion. The encoder has to override the caller
803	/// here, which is why `keyframe` is a return value rather than a parameter.
804	#[test]
805	fn a_null_field_forces_a_keyframe() {
806		let frames = encode(
807			Config::default().with_deltas(true),
808			&[json!({ "a": 1, "b": 1 }), json!({ "a": 1, "b": null })],
809		);
810		assert_eq!(frames.iter().map(|f| f.0).collect::<Vec<_>>(), vec![true, true]);
811	}
812
813	/// Same story for a root that isn't an object: there is no recursive merge patch for it.
814	#[test]
815	fn a_non_object_root_forces_a_keyframe() {
816		let frames = encode(
817			Config::default().with_deltas(true),
818			&[json!({ "a": 1 }), json!([1, 2, 3])],
819		);
820		assert_eq!(frames.iter().map(|f| f.0).collect::<Vec<_>>(), vec![true, true]);
821	}
822
823	#[test]
824	fn frame_cap_forces_a_keyframe() {
825		let values: Vec<Value> = (0..=MAX_DELTA_FRAMES).map(|n| json!({ "n": n })).collect();
826		let frames = encode(Config::default().with_deltas(true), &values);
827
828		// The snapshot plus MAX_DELTA_FRAMES - 1 deltas fill the group, then the cap rolls it.
829		assert_eq!(frames.len(), MAX_DELTA_FRAMES + 1);
830		assert_eq!(frames.iter().filter(|f| f.0).count(), 2);
831		assert!(frames[MAX_DELTA_FRAMES].0);
832	}
833
834	/// A caller that cuts the group behind the encoder's back has to say so, or the next value would
835	/// be a delta against a window and a baseline the new group never carried.
836	#[test]
837	fn reset_forces_the_next_update_to_be_a_keyframe() {
838		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(true));
839		assert!(commit(&mut encoder, &json!({ "a": 1 })).unwrap().keyframe);
840		assert!(!commit(&mut encoder, &json!({ "a": 2 })).unwrap().keyframe);
841
842		encoder.reset();
843		assert!(commit(&mut encoder, &json!({ "a": 3 })).unwrap().keyframe);
844	}
845
846	/// A frame the caller never wrote must not leave the encoder emitting deltas against a baseline
847	/// no consumer received. Dropping the [`Pending`] uncommitted is what a failed write looks like,
848	/// and it has to resynchronize on its own: a caller cannot be relied on to remember.
849	#[test]
850	fn an_uncommitted_frame_resynchronizes_the_encoder() {
851		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(true));
852		commit(&mut encoder, &json!({ "a": 1 })).unwrap();
853
854		// The caller wrote this one and said so, so the next value can still ride as a delta.
855		commit(&mut encoder, &json!({ "a": 2 })).unwrap();
856
857		// This one fails to write, so the caller drops it without committing.
858		drop(encoder.update(&json!({ "a": 3 })).unwrap().expect("a delta"));
859
860		// The next value opens a new group with a full snapshot rather than patching a state the
861		// consumer never reached.
862		let recovered = commit(&mut encoder, &json!({ "a": 4 })).expect("a resynchronizing snapshot");
863		assert!(recovered.keyframe);
864		assert_eq!(
865			serde_json::from_slice::<Value>(&recovered.payload).unwrap(),
866			json!({ "a": 4 }),
867			"the snapshot carries the whole value, not a patch"
868		);
869	}
870
871	/// The same recovery when the very first frame is lost: the encoder must not treat the value as
872	/// already published and skip it as unchanged.
873	#[test]
874	fn an_uncommitted_first_frame_is_reencoded() {
875		let mut encoder = Encoder::<Value>::new(Config::default());
876		drop(encoder.update(&json!({ "a": 1 })).unwrap().expect("a snapshot"));
877
878		let retried = commit(&mut encoder, &json!({ "a": 1 })).expect("the same value, re-encoded");
879		assert!(retried.keyframe);
880	}
881
882	/// A reset value is republished even when it matches the last one encoded: the new group has to
883	/// open with a snapshot, so "unchanged" can't mean "write nothing" there.
884	#[test]
885	fn reset_republishes_an_unchanged_value() {
886		let mut encoder = Encoder::<Value>::new(Config::default());
887		commit(&mut encoder, &json!({ "a": 1 })).unwrap();
888
889		encoder.reset();
890		assert!(
891			commit(&mut encoder, &json!({ "a": 1 }))
892				.expect("a fresh snapshot")
893				.keyframe
894		);
895	}
896
897	/// A delta is only readable while its group still holds the snapshot, so one that would push the
898	/// group past its byte budget rolls a fresh snapshot instead of joining it.
899	#[test]
900	fn a_delta_past_the_budget_rolls_a_snapshot() {
901		let value = json!({ "v": "x".repeat(1000) });
902		let patched = json!({ "v": "y".repeat(1000) });
903
904		let budget = (serde_json::to_vec(&value).unwrap().len() + 500) as u64;
905		let mut encoder = Encoder::<Value>::new(Config::default().with_max_group_bytes(budget));
906		assert!(commit(&mut encoder, &value).unwrap().keyframe);
907		let rolled = commit(&mut encoder, &patched).expect("a rolled snapshot");
908		assert!(
909			rolled.keyframe,
910			"a 1 KB patch must not ride in a group with 500 bytes left"
911		);
912		assert_eq!(
913			serde_json::from_slice::<Value>(&rolled.payload).unwrap(),
914			patched,
915			"the snapshot carries the whole value, not a patch"
916		);
917
918		// The rolled group is charged afresh, so a small change rides as a delta again.
919		let next = commit(&mut encoder, &json!({ "v": "y".repeat(1000), "q": 1 })).unwrap();
920		assert!(!next.keyframe);
921	}
922
923	/// A snapshot past the budget is refused before its baseline is parsed, with or without deltas.
924	#[test]
925	fn a_snapshot_past_the_budget_is_refused() {
926		for deltas in [false, true] {
927			let config = Config::default().with_deltas(deltas).with_max_group_bytes(100);
928			let mut encoder = Encoder::<Value>::new(config);
929			assert!(
930				matches!(
931					encoder.update(&json!({ "v": "x".repeat(1000) })),
932					Err(crate::Error::Net(moq_net::Error::FrameTooLarge))
933				),
934				"deltas {deltas}"
935			);
936			assert!(
937				encoder.value().is_none(),
938				"a refused snapshot leaves the encoder as it was"
939			);
940		}
941	}
942
943	/// A budget above moq-net's cache limit is clamped to it.
944	#[test]
945	fn the_budget_is_clamped_to_the_cache_limit() {
946		let encoder = Encoder::<Value>::new(Config::default().with_max_group_bytes(u64::MAX));
947		assert_eq!(encoder.max_group_bytes, crate::MAX_GROUP_BYTES);
948	}
949
950	/// A value whose serialization changes on every call, standing in for a `Serialize` impl backed by
951	/// a clock, an atomic, or interior mutable state.
952	struct Ticking(std::cell::Cell<u32>);
953
954	impl serde::Serialize for Ticking {
955		fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
956			use serde::ser::SerializeMap;
957
958			let n = self.0.get();
959			self.0.set(n + 1);
960
961			let mut map = serializer.serialize_map(Some(1))?;
962			map.serialize_entry("n", &n)?;
963			map.end()
964		}
965	}
966
967	/// The snapshot frame and the baseline must come from a single pass over the value. Serializing
968	/// twice costs a second traversal, and for a value like this one it seeds the baseline with
969	/// something no consumer ever received, so every later delta rebases them onto a phantom state.
970	#[test]
971	fn a_snapshot_serializes_its_value_once() {
972		let value = Ticking(std::cell::Cell::new(0));
973		let mut encoder = Encoder::<Ticking>::new(Config::default());
974		let payload = {
975			let frame = encoder.update(&value).unwrap().expect("a snapshot");
976			let payload = frame.payload.clone();
977			frame.commit();
978			payload
979		};
980
981		assert_eq!(value.0.get(), 1, "the value should be serialized exactly once");
982
983		let emitted: Value = serde_json::from_slice(&payload).unwrap();
984		assert_eq!(emitted, json!({ "n": 0 }));
985		assert_eq!(encoder.value(), Some(&emitted), "the baseline must be what was emitted");
986	}
987
988	/// A root entry the memo has not seen yet is diffed from the bytes the memo recorded, not
989	/// serialized again: a second pass could disagree with the first, leaving the memo describing a
990	/// value the baseline never held.
991	#[test]
992	fn a_delta_serializes_each_entry_once() {
993		let value = std::collections::BTreeMap::from([("row", Ticking(std::cell::Cell::new(0)))]);
994		let mut encoder = Encoder::new(Config::default().with_deltas(true));
995		encoder.update(&value).unwrap().expect("a snapshot").commit();
996
997		let frame = encoder.update(&value).unwrap().expect("a delta");
998		assert!(!frame.keyframe);
999		let emitted: Value = serde_json::from_slice(&frame.payload).unwrap();
1000		frame.commit();
1001
1002		assert_eq!(
1003			value["row"].0.get(),
1004			2,
1005			"each update should serialize the entry exactly once"
1006		);
1007		assert_eq!(emitted, json!({ "row": { "n": 1 } }));
1008		assert_eq!(encoder.value(), Some(&emitted), "the baseline must be what was emitted");
1009	}
1010
1011	/// A key repeated below the root is refused whether the memo meets it in a new entry or in a
1012	/// value replaced wholesale, as the value diff refuses it. Letting one into the memo would pair
1013	/// the repeats by position, where the consumer keeps the last.
1014	#[test]
1015	fn a_repeated_nested_key_is_refused_through_the_memo() {
1016		use serde::ser::SerializeMap;
1017
1018		/// `{"row": {"o": ..}}`, where `o` is `1` or an object that repeats a key.
1019		struct Doc {
1020			repeat: bool,
1021		}
1022		struct Row<'a>(&'a Doc);
1023		struct Repeat;
1024
1025		impl Serialize for Repeat {
1026			fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1027				let mut map = serializer.serialize_map(Some(2))?;
1028				map.serialize_entry("x", &1)?;
1029				map.serialize_entry("x", &2)?;
1030				map.end()
1031			}
1032		}
1033		impl Serialize for Row<'_> {
1034			fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1035				let mut map = serializer.serialize_map(Some(1))?;
1036				match self.0.repeat {
1037					true => map.serialize_entry("o", &Repeat)?,
1038					false => map.serialize_entry("o", &1)?,
1039				}
1040				map.end()
1041			}
1042		}
1043		impl Serialize for Doc {
1044			fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1045				let mut map = serializer.serialize_map(Some(1))?;
1046				map.serialize_entry("row", &Row(self))?;
1047				map.end()
1048			}
1049		}
1050
1051		let config = Config::default().with_deltas(true);
1052		let (plain, repeat) = (Doc { repeat: false }, Doc { repeat: true });
1053
1054		// A new entry: the first diff after a snapshot has nothing memoized yet.
1055		let mut encoder = Encoder::<Doc>::new(config.clone());
1056		encoder.update(&plain).unwrap().expect("a snapshot").commit();
1057		let err = encoder.update(&repeat).err().expect("refused");
1058		assert!(err.to_string().contains("duplicate JSON object key"), "{err}");
1059
1060		// A memoized entry whose scalar becomes an object.
1061		let mut encoder = Encoder::<Doc>::new(config);
1062		encoder.update(&plain).unwrap().expect("a snapshot").commit();
1063		assert!(encoder.update(&plain).unwrap().is_none(), "unchanged, now memoized");
1064		let err = encoder.update(&repeat).err().expect("refused");
1065		assert!(err.to_string().contains("duplicate JSON object key"), "{err}");
1066	}
1067
1068	/// A root object whose entries serialize in the order given, sorted or not.
1069	struct Rows(Vec<(String, Value)>);
1070
1071	impl Serialize for Rows {
1072		fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
1073			serializer.collect_map(self.0.iter().map(|(key, value)| (key, value)))
1074		}
1075	}
1076
1077	/// A deterministic xorshift, so a failure replays.
1078	struct Rng(u64);
1079
1080	impl Rng {
1081		fn below(&mut self, n: u64) -> u64 {
1082			self.0 ^= self.0 << 13;
1083			self.0 ^= self.0 >> 7;
1084			self.0 ^= self.0 << 17;
1085			self.0 % n
1086		}
1087
1088		/// A row value covering what the memo has to get right: nested objects that gain and lose
1089		/// keys, values that change type, nulls in and out of arrays, and strings that look like JSON.
1090		fn row(&mut self) -> Value {
1091			let strings = ["plain", "q\"uote", "back\\slash", "},{\"x\":1", "null", "a:b,c"];
1092			let mut row = serde_json::Map::new();
1093			row.insert(
1094				"n".into(),
1095				match self.below(30) {
1096					0 => Value::Null,
1097					n => json!(n % 4),
1098				},
1099			);
1100			if self.below(4) > 0 {
1101				row.insert("s".into(), json!(strings[self.below(strings.len() as u64) as usize]));
1102			}
1103			let mut nested = serde_json::Map::new();
1104			nested.insert("a".into(), json!(self.below(3)));
1105			if self.below(3) == 0 {
1106				nested.insert("b".into(), json!([self.below(2), null]));
1107			}
1108			if self.below(40) == 0 {
1109				nested.insert("c".into(), Value::Null);
1110			}
1111			row.insert("o".into(), Value::Object(nested));
1112			row.insert(
1113				"t".into(),
1114				match self.below(5) {
1115					0 => json!({ "k": self.below(2) }),
1116					1 => json!({}),
1117					2 => json!([{ "k": null }]),
1118					3 => json!(1.5 + self.below(2) as f64),
1119					_ => json!("t"),
1120				},
1121			);
1122			if self.below(60) == 0 {
1123				row.insert("z".into(), Value::Null);
1124			}
1125			Value::Object(row)
1126		}
1127	}
1128
1129	/// The memo is a shortcut past the value diff, so it must never change a frame: every payload and
1130	/// keyframe has to match an encoder diffing without it, through inserts, deletions, reorders,
1131	/// shape changes, forced snapshots, and group rolls. Without the memo the value is diffed as a
1132	/// parsed `Value`, whose keys are sorted, so a delta from a root that stops ascending lists its
1133	/// entries in another order and is compared as the patch it parses to.
1134	#[test]
1135	fn memo_matches_the_value_diff() {
1136		for seed in 1..=3 {
1137			let config = Config::default().with_deltas(true);
1138			let mut memoized = Encoder::<Rows>::new(config.clone());
1139			let mut plain = Encoder::<Rows>::new(config);
1140			plain.scratch = RefCell::new(crate::diff::Scratch::default());
1141
1142			// Seed 2's keys need escaping, which the memoized encoder reads back out of its bytes.
1143			let key = |i: u64| match seed {
1144				2 => format!("r\"o\\w\n\u{e9}-{i:03}"),
1145				_ => format!("row-{i:03}"),
1146			};
1147			let mut rng = Rng(0x9E37_79B9_7F4A_7C15 ^ seed);
1148			let mut rows: Vec<(String, Value)> = (0..40).map(|i| (key(i), rng.row())).collect();
1149			let mut emitted = 0;
1150			for tick in 0..400 {
1151				for row in rows.iter_mut() {
1152					if rng.below(4) == 0 {
1153						row.1 = rng.row();
1154					}
1155				}
1156				if rng.below(3) == 0 {
1157					let index = rng.below(rows.len() as u64) as usize;
1158					rows.remove(index);
1159				}
1160				if rng.below(3) == 0 {
1161					rows.push((key(40 + rng.below(40)), rng.row()));
1162				}
1163				rows.sort_by(|a, b| a.0.cmp(&b.0));
1164				rows.dedup_by(|a, b| a.0 == b.0);
1165				// Now and then, a root that stops ascending.
1166				if seed == 3 && rng.below(10) == 0 {
1167					let (a, b) = (
1168						rng.below(rows.len() as u64) as usize,
1169						rng.below(rows.len() as u64) as usize,
1170					);
1171					rows.swap(a, b);
1172				}
1173
1174				let value = Rows(rows.clone());
1175				let want = plain.update(&value).unwrap().map(|frame| {
1176					let encoded = (*frame).clone();
1177					frame.commit();
1178					encoded
1179				});
1180				let got = memoized.update(&value).unwrap().map(|frame| {
1181					let encoded = (*frame).clone();
1182					frame.commit();
1183					encoded
1184				});
1185				match (want, got) {
1186					(None, None) => {}
1187					(Some(want), Some(got)) => {
1188						assert_eq!(got.keyframe, want.keyframe, "seed {seed} tick {tick}: keyframe");
1189						if got.keyframe || seed != 3 {
1190							assert_eq!(got.payload, want.payload, "seed {seed} tick {tick}: payload");
1191						} else {
1192							let parse = |payload: &[u8]| serde_json::from_slice::<Value>(payload).unwrap();
1193							assert_eq!(
1194								parse(&got.payload),
1195								parse(&want.payload),
1196								"seed {seed} tick {tick}: patch"
1197							);
1198						}
1199						emitted += usize::from(!got.keyframe);
1200					}
1201					(want, got) => panic!("seed {seed} tick {tick}: {want:?} vs {got:?}"),
1202				}
1203				assert_eq!(memoized.value(), plain.value(), "seed {seed} tick {tick}: baseline");
1204			}
1205			assert!(emitted > 100, "seed {seed}: only {emitted} deltas exercised the memo");
1206		}
1207	}
1208
1209	#[test]
1210	fn value_tracks_the_baseline() {
1211		let mut encoder = Encoder::<Value>::new(Config::default().with_deltas(true));
1212		assert_eq!(encoder.value(), None);
1213
1214		commit(&mut encoder, &json!({ "a": 1, "b": 1 }));
1215		commit(&mut encoder, &json!({ "a": 1, "b": 2 }));
1216
1217		// The delta was folded into the baseline, so it reflects what was actually published.
1218		assert_eq!(encoder.value(), Some(&json!({ "a": 1, "b": 2 })));
1219
1220		// A frame that never reached the wire leaves the value at the last one that did.
1221		drop(encoder.update(&json!({ "a": 1, "b": 3 })).unwrap());
1222		assert_eq!(encoder.value(), Some(&json!({ "a": 1, "b": 2 })));
1223	}
1224}