xfa-layout-engine 1.0.0-beta.5

Box-model and pagination layout engine for XFA forms. Experimental — part of the PDFluent XFA stack, under active development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
//! Decision-trace channel for XFA observability.
//!
//! This module is part of M1 (Observability Foundation). It exists so that
//! XFA fidelity debugging can record *why* the engine made a particular
//! layout decision, separate from *what* the resulting layout looks like
//! (the latter is captured by [`crate::ir`]).
//!
//! ## Design constraints
//!
//! - **Off by default.** No global state. The trace channel is enabled
//!   only inside a [`with_sink`] scope. When no sink is installed,
//!   [`emit`] is a single thread-local read returning a `None` and
//!   compiles to a small handful of instructions.
//! - **No new dependencies.** Plain Rust, `std` only. No `tracing` or
//!   `serde` involvement at this layer.
//! - **Frozen vocabulary.** [`Phase`] and [`Reason`] are enums with
//!   stable string tags; renames are breaking and require a taxonomy
//!   bump (see migration policy in source comments).
//! - **Determinism-friendly.** Events are accumulated in insertion order
//!   inside a [`RecordingSink`], with no `HashMap`/`HashSet` involvement.
//!
//! ## Out of scope (M1 v1)
//!
//! - Wiring trace emit calls from the engine's hot phases (bind, occur,
//!   presence, paginate, suppress) into production layout code paths.
//!   v1 ships the taxonomy, the sink trait, and **demonstration emit
//!   sites** under tests. Engine wiring lands in a follow-up wave that
//!   is allowed to perturb existing call sites.
//! - Streaming output to disk, file rotation, or telemetry. The diff CLI
//!   in `xfa-test-runner` reads the in-memory `RecordingSink` events
//!   serialised once at the end of a run.
//! - JSON/Serde derives. Output is via the small `to_canonical_json`
//!   helpers below.

pub mod sites;

use std::cell::RefCell;
use std::fmt::Write;
use std::rc::Rc;
use std::sync::{Arc, Mutex, OnceLock};

/// The phase in which a trace event was emitted.
///
/// ## Stability policy
///
/// Variants are added at the end of the enum to preserve existing tag
/// strings. Renames or removals require a coordinated update across
/// every consumer in the same change.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Phase {
    /// Data binding — matching template subforms to dataset records.
    Bind,
    /// Instance materialisation under `occur`.
    Occur,
    /// Presence resolution (`presence="visible|hidden|inactive|invisible"`).
    Presence,
    /// Measurement of intrinsic content (text width/height).
    Measure,
    /// Pagination decisions (page break, defer, suppress).
    Paginate,
    /// Page suppression (drop empty data-bound pages, etc.).
    Suppress,
    /// SOM resolution.
    Resolve,
    /// Final emit/serialize step.
    Emit,
    /// Pipeline-level fallback: the XFA flatten path could not produce
    /// output and the caller has been served a non-XFA passthrough
    /// instead. Emitted from `pdf-xfa::flatten` when the inner XFA
    /// attempt errors or times out.
    Fallback,
}

impl Phase {
    /// Stable string tag; never rename without a taxonomy bump.
    pub fn tag(self) -> &'static str {
        match self {
            Phase::Bind => "bind",
            Phase::Occur => "occur",
            Phase::Presence => "presence",
            Phase::Measure => "measure",
            Phase::Paginate => "paginate",
            Phase::Suppress => "suppress",
            Phase::Resolve => "resolve",
            Phase::Emit => "emit",
            Phase::Fallback => "fallback",
        }
    }
}

/// The reason behind a trace event — a closed vocabulary of decision codes.
///
/// ## Stability policy
///
/// Each variant has a stable lower-snake-case tag. Variants may be added
/// to the end of the enum without ceremony. **Tags must never be renamed**
/// because committed snapshots reference them; a rename is a taxonomy
/// bump and forces a snapshot regeneration.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Reason {
    // --- Bind ---
    /// Number of dataset records matched the template's `occur.initial`.
    DataCountMatchesInitial,
    /// Dataset record count was clamped to `occur.max`.
    DataCountClampedByOccurMax,
    /// Dataset record count was lifted to `occur.min`.
    DataCountLiftedByOccurMin,

    // --- Occur ---
    /// Subform was materialised because data was present.
    SubformMaterialisedFromData,
    /// Subform was materialised because `occur.initial > 0`.
    SubformMaterialisedFromInitial,
    /// Subform instance was suppressed because no data was bound.
    SubformSuppressedNoData,

    // --- Presence ---
    /// Node hidden by `presence="hidden"`.
    PresenceHidden,
    /// Node hidden by `presence="invisible"`.
    PresenceInvisible,
    /// Node hidden by `presence="inactive"`.
    PresenceInactive,
    /// Node visible by default or explicit `presence="visible"`.
    PresenceVisible,

    // --- Paginate ---
    /// Container fits on the current page.
    PaginateFitsCurrentPage,
    /// Container deferred to next page because of `minH`/overflow.
    PaginateDeferToNextPageMinH,
    /// Container deferred because `keep` chain forbade splitting.
    PaginateDeferToNextPageKeep,
    /// Container split across pages.
    PaginateSplit,

    // --- Suppress ---
    /// Empty data-bound page was dropped because real data binding was present elsewhere.
    SuppressEmptyDataPageDropped,
    /// Page suppression was capped by the form-DOM's page area count.
    SuppressCappedByFormDom,
    /// Static `bind=none` page was preserved.
    SuppressStaticBindNonePreserved,
    /// `suppress_empty_pages_only_when_real_data_bound` ran and decided
    /// the data-bound signal is present, so the suppression heuristic
    /// is allowed to run.
    SuppressGatedByDataBoundSignal,
    /// `suppress_empty_pages_only_when_real_data_bound` ran and decided
    /// no real data binding occurred, so the suppression heuristic stays
    /// off (e.g. blank-form output preserves all template pages).
    SuppressSkippedNoDataBoundSignal,
    /// `exclude_bind_none_fields_from_page_data_suppression`: at least
    /// one field with `<bind match="none">` was excluded from the page
    /// data-field count. Emitted at most once per flatten with the
    /// exclusion count attached to the decision string.
    BindNoneFieldExcludedFromDataCheck,
    /// `static_xfaf_excess_page_trim_with_form_dom_guard`: static XFAF
    /// surplus host pages may be trimmed under the form-DOM guard.
    StaticXfafTrimAllowed,
    /// `static_xfaf_excess_page_trim_with_form_dom_guard`: the form DOM
    /// (or the dynamic-template hint) prevented the static-trim path
    /// from firing.
    StaticXfafTrimBlocked,
    /// `ignore_invisible_server_metadata_bindings_for_data_bound_signal`:
    /// at least one binding on an invisible / hidden / inactive field
    /// was observed and ignored for purposes of the global data-bound
    /// signal. Emitted at most once per merge with the total ignored
    /// count attached to the decision string.
    InvisibleFieldBindingIgnored,
    /// `exclude_non_data_widgets_from_page_suppression`: at least one
    /// signature / button / barcode widget was excluded from the
    /// per-page data-field count. Emitted at most once per flatten
    /// with the total exclusion count attached.
    NonDataWidgetExcludedFromDataCheck,
    /// `bind_none_subform_does_not_auto_expand`: a subform with
    /// `<bind match="none">` was preserved as a single template
    /// instance instead of being auto-expanded from datasets, even
    /// though its `<occur>` would otherwise allow repetition
    /// (XFA §4.4.3). Emitted per repeating named subform when the
    /// rule actively blocks expansion.
    BindNoneSubformExpansionSkipped,

    // --- Resolve / Measure / Emit (placeholders for follow-up waves) ---
    /// Generic SOM lookup miss; node not found.
    ResolveLookupMiss,
    /// Text measurement produced a single line.
    MeasureSingleLine,
    /// Text measurement produced a wrapped multi-line block.
    MeasureWrapped,
    /// Final emit completed for a node without remarks.
    EmitOk,

    // --- Fallback ---
    /// `pdf-xfa::flatten` caught an inner-pipeline error (or
    /// timeout) and served a non-XFA passthrough to the caller via
    /// `static_fallback`. Carries a short decision summary (the
    /// underlying error or "timeout"). Critical signal for fidelity
    /// gates: a flatten that returns `Ok` *with* this event is not
    /// real XFA output.
    StaticFallbackTaken,

    // --- Generic ---
    /// Unspecified reason; for callers without a more precise tag.
    Unspecified,
}

impl Reason {
    /// Stable string tag; never rename without a taxonomy bump.
    pub fn tag(self) -> &'static str {
        match self {
            Reason::DataCountMatchesInitial => "data_count_matches_initial",
            Reason::DataCountClampedByOccurMax => "data_count_clamped_by_occur_max",
            Reason::DataCountLiftedByOccurMin => "data_count_lifted_by_occur_min",
            Reason::SubformMaterialisedFromData => "subform_materialised_from_data",
            Reason::SubformMaterialisedFromInitial => "subform_materialised_from_initial",
            Reason::SubformSuppressedNoData => "subform_suppressed_no_data",
            Reason::PresenceHidden => "presence_hidden",
            Reason::PresenceInvisible => "presence_invisible",
            Reason::PresenceInactive => "presence_inactive",
            Reason::PresenceVisible => "presence_visible",
            Reason::PaginateFitsCurrentPage => "paginate_fits_current_page",
            Reason::PaginateDeferToNextPageMinH => "paginate_defer_to_next_page_min_h",
            Reason::PaginateDeferToNextPageKeep => "paginate_defer_to_next_page_keep",
            Reason::PaginateSplit => "paginate_split",
            Reason::SuppressEmptyDataPageDropped => "suppress_empty_data_page_dropped",
            Reason::SuppressCappedByFormDom => "suppress_capped_by_form_dom",
            Reason::SuppressStaticBindNonePreserved => "suppress_static_bind_none_preserved",
            Reason::SuppressGatedByDataBoundSignal => "suppress_gated_by_data_bound_signal",
            Reason::SuppressSkippedNoDataBoundSignal => "suppress_skipped_no_data_bound_signal",
            Reason::BindNoneFieldExcludedFromDataCheck => {
                "bind_none_field_excluded_from_data_check"
            }
            Reason::StaticXfafTrimAllowed => "static_xfaf_trim_allowed",
            Reason::StaticXfafTrimBlocked => "static_xfaf_trim_blocked",
            Reason::InvisibleFieldBindingIgnored => "invisible_field_binding_ignored",
            Reason::NonDataWidgetExcludedFromDataCheck => {
                "non_data_widget_excluded_from_data_check"
            }
            Reason::BindNoneSubformExpansionSkipped => "bind_none_subform_expansion_skipped",
            Reason::ResolveLookupMiss => "resolve_lookup_miss",
            Reason::MeasureSingleLine => "measure_single_line",
            Reason::MeasureWrapped => "measure_wrapped",
            Reason::EmitOk => "emit_ok",
            Reason::StaticFallbackTaken => "static_fallback_taken",
            Reason::Unspecified => "unspecified",
        }
    }
}

/// One trace event.
///
/// Optional fields use `None` rather than empty strings so the canonical
/// JSON output emits `null` cleanly. Numeric `input` and `output` summaries
/// are constrained to `i64` to stay deterministic across platforms.
#[derive(Debug, Clone, PartialEq)]
pub struct TraceEvent {
    /// Phase in which the event fired.
    pub phase: Phase,
    /// Reason describing the decision.
    pub reason: Reason,
    /// Optional SOM path of the node the decision applies to.
    pub som: Option<String>,
    /// Optional human-readable input summary (e.g. `"available_h=267.3"`).
    pub input: Option<String>,
    /// Optional human-readable decision summary (e.g. `"defer_to_next_page"`).
    pub decision: Option<String>,
    /// Optional source-module hint (e.g. `"layout::paginate"`); cheap to
    /// produce and useful when grepping traces.
    pub source: Option<String>,
}

impl TraceEvent {
    /// Construct a minimal event with just phase + reason.
    pub fn new(phase: Phase, reason: Reason) -> Self {
        Self {
            phase,
            reason,
            som: None,
            input: None,
            decision: None,
            source: None,
        }
    }

    /// Builder: set the SOM path.
    pub fn with_som(mut self, som: impl Into<String>) -> Self {
        self.som = Some(som.into());
        self
    }

    /// Builder: set the input summary.
    pub fn with_input(mut self, input: impl Into<String>) -> Self {
        self.input = Some(input.into());
        self
    }

    /// Builder: set the decision summary.
    pub fn with_decision(mut self, decision: impl Into<String>) -> Self {
        self.decision = Some(decision.into());
        self
    }

    /// Builder: set the source-module hint.
    pub fn with_source(mut self, source: impl Into<String>) -> Self {
        self.source = Some(source.into());
        self
    }
}

/// Implemented by anything that wants to receive trace events.
///
/// Implementations must be cheap when called; emit sites in the engine
/// are designed for `~one indirect call` overhead when a sink is
/// installed.
pub trait Sink {
    /// Receive a single event. Implementations should not perform I/O
    /// or take locks that risk contention with engine work.
    fn record(&self, event: TraceEvent);
}

/// A no-op sink. Default when no sink is installed.
#[derive(Debug, Clone, Copy, Default)]
pub struct NoopSink;

impl Sink for NoopSink {
    fn record(&self, _event: TraceEvent) {}
}

/// A simple recording sink that accumulates events in insertion order.
///
/// Backed by a `Mutex<Vec<TraceEvent>>` so the sink is `Send + Sync` and
/// can be shared across threads via `Arc<RecordingSink>` and installed
/// through [`with_global_sink`] / [`set_global_sink`]. The single-thread
/// `Rc<RecordingSink>` path through [`with_sink`] continues to work and
/// pays only the Mutex acquisition cost when an event is recorded
/// (still zero-cost when no sink is installed).
#[derive(Debug, Default)]
pub struct RecordingSink {
    events: Mutex<Vec<TraceEvent>>,
}

impl RecordingSink {
    /// Create a fresh recording sink.
    pub fn new() -> Self {
        Self::default()
    }

    /// Snapshot the recorded events.
    pub fn events(&self) -> Vec<TraceEvent> {
        self.events
            .lock()
            .expect("trace sink mutex poisoned")
            .clone()
    }

    /// Number of events recorded so far.
    pub fn len(&self) -> usize {
        self.events.lock().expect("trace sink mutex poisoned").len()
    }

    /// Whether no events have been recorded.
    pub fn is_empty(&self) -> bool {
        self.events
            .lock()
            .expect("trace sink mutex poisoned")
            .is_empty()
    }

    /// Render all events to canonical JSON.
    pub fn to_canonical_json(&self) -> String {
        events_to_canonical_json(&self.events.lock().expect("trace sink mutex poisoned"))
    }
}

impl Sink for RecordingSink {
    fn record(&self, event: TraceEvent) {
        self.events
            .lock()
            .expect("trace sink mutex poisoned")
            .push(event);
    }
}

// --- Thread-local sink slot --------------------------------------------------
//
// The current sink is stored as an `Rc<dyn Sink>` per thread. Installing a
// sink is a clone of the `Rc`; emission is one thread-local read plus a
// single virtual call. When no sink is installed, emission costs one
// thread-local read and an `Option::is_some` branch.

thread_local! {
    static CURRENT_SINK: RefCell<Option<Rc<dyn Sink>>> = const { RefCell::new(None) };
}

/// Install `sink` for the duration of `f`, then restore the previous sink.
///
/// Pass `sink` by value (typically `Rc::new(RecordingSink::new())` or a
/// clone of an existing `Rc`); the caller can keep their own `Rc` to read
/// recorded events after the scope ends.
///
/// Panics inside `f` propagate; the previous sink is restored via `Drop`
/// of an internal guard. Recursive emission inside `Sink::record` is
/// undefined behaviour: do not call [`emit`] from inside a sink.
pub fn with_sink<R>(sink: Rc<dyn Sink>, f: impl FnOnce() -> R) -> R {
    let prev = CURRENT_SINK.with(|cell| cell.borrow_mut().replace(sink));

    struct Guard {
        prev: Option<Rc<dyn Sink>>,
    }
    impl Drop for Guard {
        fn drop(&mut self) {
            CURRENT_SINK.with(|cell| {
                *cell.borrow_mut() = self.prev.take();
            });
        }
    }
    let _guard = Guard { prev };
    f()
}

// --- Global (cross-thread) sink slot ----------------------------------------
//
// The thread-local slot above covers in-thread tracing. Some engine code
// paths (notably `pdf_xfa::flatten_xfa_to_pdf`) run inside a
// `std::thread::spawn`ed worker, so a thread-local sink installed by the
// caller is invisible to that worker. The global slot below is an
// `Arc<dyn Sink + Send + Sync>` that any thread can reach. The trade-off
// is one extra atomic-loadable lock on every emit when a global sink is
// installed.

type GlobalSink = Arc<dyn Sink + Send + Sync>;

fn global_slot() -> &'static Mutex<Option<GlobalSink>> {
    static SLOT: OnceLock<Mutex<Option<GlobalSink>>> = OnceLock::new();
    SLOT.get_or_init(|| Mutex::new(None))
}

/// Install a `Send + Sync` sink in the cross-thread global slot.
///
/// Replaces any previously installed global sink. Pass an `Arc` cloned
/// from the caller-owned instance so the caller can still read recorded
/// events.
pub fn set_global_sink(sink: GlobalSink) {
    *global_slot().lock().expect("trace global sink poisoned") = Some(sink);
}

/// Clear the global sink slot.
pub fn clear_global_sink() {
    *global_slot().lock().expect("trace global sink poisoned") = None;
}

/// Install `sink` in the global slot for the duration of `f`, then restore
/// the previous global sink. Emits from any thread (including worker
/// threads `f` spawns) reach this sink. Single-thread callers should prefer
/// the cheaper [`with_sink`] API.
pub fn with_global_sink<R>(sink: GlobalSink, f: impl FnOnce() -> R) -> R {
    let prev = {
        let mut guard = global_slot().lock().expect("trace global sink poisoned");
        guard.replace(sink)
    };

    struct Guard {
        prev: Option<GlobalSink>,
    }
    impl Drop for Guard {
        fn drop(&mut self) {
            *global_slot().lock().expect("trace global sink poisoned") = self.prev.take();
        }
    }
    let _guard = Guard { prev };
    f()
}

/// Emit one event to the current thread-local sink, if any, and then to
/// the global sink, if any. Cheap when neither is installed: one
/// thread-local read, one atomic-protected lock read, and two
/// `Option::is_some` checks.
pub fn emit(event: TraceEvent) {
    // Thread-local has priority for cheap single-threaded callers.
    let mut consumed = false;
    CURRENT_SINK.with(|cell| {
        if let Some(sink) = cell.borrow().as_ref() {
            sink.record(event.clone());
            consumed = true;
        }
    });
    // Global slot fires on every emit when set. This also catches emits
    // from worker threads where the thread-local slot is None.
    if let Ok(guard) = global_slot().lock() {
        if let Some(sink) = guard.as_ref() {
            // If both thread-local and global are set on the same thread,
            // we still emit to the global sink — tests installing a global
            // for cross-thread coverage want to see every event.
            let _ = consumed;
            sink.record(event);
        }
    }
}

/// Convenience: emit a `Phase + Reason` event with no extra fields.
pub fn emit_simple(phase: Phase, reason: Reason) {
    emit(TraceEvent::new(phase, reason));
}

/// Render a slice of events to canonical JSON (alphabetical keys, fixed
/// ordering, two-space indent).
pub fn events_to_canonical_json(events: &[TraceEvent]) -> String {
    let mut out = String::new();
    out.push_str("[\n");
    let last = events.len().saturating_sub(1);
    for (i, e) in events.iter().enumerate() {
        out.push_str("  {\n");
        write_kv_optional(&mut out, "decision", e.decision.as_deref());
        write_kv_optional(&mut out, "input", e.input.as_deref());
        write_kv(&mut out, "phase", e.phase.tag());
        write_kv(&mut out, "reason", e.reason.tag());
        write_kv_optional(&mut out, "som", e.som.as_deref());
        write_kv_optional_last(&mut out, "source", e.source.as_deref());
        out.push_str("  }");
        if i != last {
            out.push(',');
        }
        out.push('\n');
    }
    out.push_str("]\n");
    out
}

fn write_json_string(out: &mut String, s: &str) {
    out.push('"');
    for c in s.chars() {
        match c {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            '\u{08}' => out.push_str("\\b"),
            '\u{0C}' => out.push_str("\\f"),
            c if (c as u32) < 0x20 => {
                let _ = write!(out, "\\u{:04x}", c as u32);
            }
            c => out.push(c),
        }
    }
    out.push('"');
}

fn write_kv(out: &mut String, key: &str, value: &str) {
    out.push_str("    \"");
    out.push_str(key);
    out.push_str("\": ");
    write_json_string(out, value);
    out.push_str(",\n");
}

fn write_kv_optional(out: &mut String, key: &str, value: Option<&str>) {
    out.push_str("    \"");
    out.push_str(key);
    out.push_str("\": ");
    match value {
        Some(s) => write_json_string(out, s),
        None => out.push_str("null"),
    }
    out.push_str(",\n");
}

fn write_kv_optional_last(out: &mut String, key: &str, value: Option<&str>) {
    out.push_str("    \"");
    out.push_str(key);
    out.push_str("\": ");
    match value {
        Some(s) => write_json_string(out, s),
        None => out.push_str("null"),
    }
    out.push('\n');
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn no_sink_means_no_record() {
        // emit() outside any with_sink scope must be a no-op (and not panic).
        emit_simple(Phase::Bind, Reason::Unspecified);
    }

    #[test]
    fn recording_sink_collects_events() {
        let sink: Rc<RecordingSink> = Rc::new(RecordingSink::new());
        with_sink(sink.clone(), || {
            emit_simple(Phase::Bind, Reason::DataCountMatchesInitial);
            emit(TraceEvent::new(Phase::Paginate, Reason::PaginateSplit).with_som("form1.subform"));
        });
        assert_eq!(sink.len(), 2);
        let evs = sink.events();
        assert_eq!(evs[0].phase, Phase::Bind);
        assert_eq!(evs[1].som.as_deref(), Some("form1.subform"));
    }

    #[test]
    fn nested_with_sink_restores() {
        let outer: Rc<RecordingSink> = Rc::new(RecordingSink::new());
        let inner: Rc<RecordingSink> = Rc::new(RecordingSink::new());
        with_sink(outer.clone(), || {
            emit_simple(Phase::Bind, Reason::Unspecified);
            with_sink(inner.clone(), || {
                emit_simple(Phase::Paginate, Reason::PaginateSplit);
            });
            emit_simple(Phase::Suppress, Reason::SuppressEmptyDataPageDropped);
        });
        assert_eq!(outer.len(), 2);
        assert_eq!(inner.len(), 1);
        assert_eq!(inner.events()[0].phase, Phase::Paginate);
    }

    #[test]
    fn canonical_json_is_byte_stable() {
        let sink: Rc<RecordingSink> = Rc::new(RecordingSink::new());
        with_sink(sink.clone(), || {
            emit(
                TraceEvent::new(Phase::Bind, Reason::DataCountMatchesInitial)
                    .with_som("a")
                    .with_input("n=3")
                    .with_decision("ok"),
            );
            emit_simple(Phase::Paginate, Reason::PaginateSplit);
        });
        let a = sink.to_canonical_json();
        let b = sink.to_canonical_json();
        assert_eq!(a, b);
    }

    #[test]
    fn phase_tags_are_stable() {
        // This test exists to lock the public string vocabulary. Editing
        // any of these RHS strings is a taxonomy bump and requires a
        // coordinated update across snapshots.
        assert_eq!(Phase::Bind.tag(), "bind");
        assert_eq!(Phase::Occur.tag(), "occur");
        assert_eq!(Phase::Presence.tag(), "presence");
        assert_eq!(Phase::Measure.tag(), "measure");
        assert_eq!(Phase::Paginate.tag(), "paginate");
        assert_eq!(Phase::Suppress.tag(), "suppress");
        assert_eq!(Phase::Resolve.tag(), "resolve");
        assert_eq!(Phase::Emit.tag(), "emit");
    }

    #[test]
    fn reason_tags_are_stable_subset() {
        // Lock the five M1.6 hot-phase reasons explicitly.
        assert_eq!(
            Reason::DataCountMatchesInitial.tag(),
            "data_count_matches_initial"
        );
        assert_eq!(
            Reason::SubformMaterialisedFromData.tag(),
            "subform_materialised_from_data"
        );
        assert_eq!(Reason::PresenceVisible.tag(), "presence_visible");
        assert_eq!(Reason::PaginateSplit.tag(), "paginate_split");
        assert_eq!(
            Reason::SuppressEmptyDataPageDropped.tag(),
            "suppress_empty_data_page_dropped"
        );
    }
}