exfiltrate 0.4.0

An embeddable debug tool for Rust.
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Live-state providers, and the `snapshot` command that drives them.
//!
//! # Why this is not the log path
//!
//! A recorder answers *what just happened*. A provider answers *what exists
//! now*: which tasks are live, how deep a queue is, what a routing table
//! contains. Reconstructing the second from the first fails in exactly the
//! cases where you need it — after records were dropped, or when the
//! interesting state never emitted anything because it never changed.
//!
//! # What a subsystem has to do
//!
//! Implement [`Provider`] and call [`add_provider`]. Nothing else. In
//! particular a subsystem does **not** register a command, so twelve
//! subsystems do not produce twelve slightly different command shapes; they
//! all appear under `snapshot --subsystem <name>`.
//!
//! This layer has no dependency on `logwise` — neither the facade nor the
//! runtime — and must not grow one. A logwise-aware provider belongs in a crate
//! above both, such as `logwise_agent_exfiltrate`.
//!
//! # The contract a provider is held to
//!
//! * **Bounded.** [`SnapshotRequest::limit`] is the most rows the caller wants.
//!   A provider that ignores it is truncated by the registry and the result is
//!   reported `Partial` rather than silently shortened.
//! * **Cancellable.** [`SnapshotRequest::should_stop`] goes true when the
//!   client disconnected or the deadline passed. Cancellation is cooperative:
//!   nothing can preempt a provider mid-scan, so one that never checks is
//!   reported `TimedOut` after the fact rather than killed.
//! * **Non-blocking.** A provider that cannot take its lock should return
//!   [`ProviderResult::Busy`] instead of waiting. Blocking here blocks the
//!   debug server, which is the one thing that still has to work when the
//!   application is wedged.
//!
//! # Privacy and authorization
//!
//! Authorization happens on the connection, before any command runs: a peer
//! that did not satisfy the configured token (see [`crate::Config`]) never reaches
//! this code. What this layer adds is that the **default projection is
//! support-safe**, so a deployment that got its transport wrong leaks less.
//! `--view local` is the opt-in for local-only fields, and there is no way to
//! mark a field secret and have it shipped anyway — see
//! [`exfiltrate_internal::snapshot::FieldPrivacy`].

use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use exfiltrate_internal::args::{ArgKind, ArgSpec, ParsedArgs};
use exfiltrate_internal::command::{Command, CommandContext, Response};
use exfiltrate_internal::snapshot::{
    FieldPrivacy, SnapshotField, SnapshotOutcome, SnapshotResponse, SnapshotRow, SnapshotSet,
    SnapshotValue,
};
use wasm_lite_std::Mutex;
use wasm_lite_std::time::{Duration, Instant};

/// What the caller asked for.
#[derive(Debug)]
pub struct SnapshotRequest<'a> {
    selector: Option<&'a str>,
    limit: usize,
    deadline: Instant,
    cancelled: &'a AtomicBool,
}

impl<'a> SnapshotRequest<'a> {
    /// The `--id` the caller passed, if any. Its meaning is the subsystem's.
    pub fn selector(&self) -> Option<&'a str> {
        self.selector
    }

    /// The most rows worth producing. Producing more is not an error, but the
    /// extra will be discarded and the answer marked `Partial`.
    pub fn limit(&self) -> usize {
        self.limit
    }

    /// True once the caller has gone or the deadline has passed.
    ///
    /// Check it in any loop that could run long. Nothing can interrupt a
    /// provider from outside.
    pub fn should_stop(&self) -> bool {
        self.cancelled.load(Ordering::Relaxed) || Instant::now() >= self.deadline
    }
}

/// One row, built with an explicit privacy level per field.
///
/// The level is not a hint. It decides whether the value survives projection,
/// and the default view drops local-only fields.
#[derive(Clone, Debug, Default)]
pub struct Row(Vec<SnapshotField>);

impl Row {
    /// An empty row. Add fields with [`support`](Row::support) or
    /// [`local`](Row::local), which is where the privacy level is chosen.
    pub fn new() -> Row {
        Row(Vec::new())
    }

    /// A value safe for any peer that reached this process — a count, a state
    /// name, an id this crate minted.
    pub fn support(mut self, name: impl Into<String>, value: impl Into<SnapshotValue>) -> Row {
        self.0.push(SnapshotField {
            name: name.into(),
            privacy: FieldPrivacy::SupportSafe,
            value: Some(value.into()),
        });
        self
    }

    /// A value derived from the application's own data — a label someone typed,
    /// a path, a URL. Withheld unless the caller asked for a local view.
    pub fn local(mut self, name: impl Into<String>, value: impl Into<SnapshotValue>) -> Row {
        self.0.push(SnapshotField {
            name: name.into(),
            privacy: FieldPrivacy::LocalOnly,
            value: Some(value.into()),
        });
        self
    }

    /// How many fields the row carries, before any view drops any of them.
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether the row carries no fields at all.
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

/// Not `#[non_exhaustive]`: the three outcomes are the contract between a
/// provider and the CLI, and a caller that wildcards them would report a
/// partial answer as a complete one.
/// What a provider produced.
#[derive(Debug)]
pub enum ProviderResult {
    /// The rows matching the selector.
    Rows(Vec<Row>),
    /// Everything it could get before it had to stop, and why.
    Partial(Vec<Row>, String),
    /// The subsystem is here but cannot answer now.
    Unavailable(String),
    /// Compiled out of this build.
    NotCompiled,
    /// Its state was locked. Return this rather than blocking.
    Busy,
}

/// A subsystem that can describe its live state.
pub trait Provider: Send + Sync + 'static {
    /// The name this appears under, as `snapshot --subsystem <name>`.
    ///
    /// A short lowercase noun: `tasks`, `executor`, `context`.
    fn subsystem(&self) -> &'static str;

    /// One line for `snapshot --list`.
    fn description(&self) -> &'static str;

    /// Produce the rows. See the module docs for the contract.
    fn snapshot(&self, request: &SnapshotRequest<'_>) -> ProviderResult;
}

static PROVIDERS: Mutex<Vec<Arc<dyn Provider>>> = Mutex::new(Vec::new());

/// Registers a provider. A second registration under the same name replaces the
/// first, so a subsystem that re-initialises does not accumulate duplicates.
pub fn add_provider<P: Provider>(provider: P) {
    let provider: Arc<dyn Provider> = Arc::new(provider);
    PROVIDERS.with_mut_sync(|providers| {
        providers.retain(|existing| existing.subsystem() != provider.subsystem());
        providers.push(provider);
    });
}

/// The subsystems currently registered.
pub fn registered() -> Vec<(&'static str, &'static str)> {
    PROVIDERS.with_sync(|providers| {
        providers
            .iter()
            .map(|provider| (provider.subsystem(), provider.description()))
            .collect()
    })
}

#[cfg(test)]
pub(crate) fn clear_providers() {
    PROVIDERS.with_mut_sync(|providers| providers.clear());
}

/// Runs one provider, enforcing everything the provider is not trusted to do
/// itself: the row limit, the deadline, panic isolation, and projection.
fn run(
    provider: &Arc<dyn Provider>,
    selector: Option<&str>,
    limit: usize,
    timeout: Duration,
    cancelled: &AtomicBool,
    local_view: bool,
) -> SnapshotResponse {
    let started = Instant::now();
    let deadline = started + timeout;
    let request = SnapshotRequest {
        selector,
        limit,
        deadline,
        cancelled,
    };

    // A provider is someone else's code. On native a panic is caught and
    // reported, because a crashing provider is a bug in that subsystem and
    // reporting it as merely "no rows" hides it. On wasm32 the profile builds
    // std with panic_abort, so there is nothing to catch -- stated rather than
    // silently different.
    #[cfg(not(target_arch = "wasm32"))]
    let produced =
        std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| provider.snapshot(&request)));
    #[cfg(target_arch = "wasm32")]
    let produced = Ok::<_, ()>(provider.snapshot(&request));

    let elapsed_ms = started.elapsed().as_millis() as u64;
    let overran = Instant::now() >= deadline;

    let (mut rows, mut outcome, mut reason) = match produced {
        Err(_) => (
            Vec::new(),
            SnapshotOutcome::Panicked,
            Some("the provider panicked; this is a bug in that subsystem".to_string()),
        ),
        Ok(ProviderResult::Rows(rows)) => (rows, SnapshotOutcome::Ready, None),
        Ok(ProviderResult::Partial(rows, why)) => (rows, SnapshotOutcome::Partial, Some(why)),
        Ok(ProviderResult::Unavailable(why)) => {
            (Vec::new(), SnapshotOutcome::Unavailable, Some(why))
        }
        Ok(ProviderResult::NotCompiled) => (
            Vec::new(),
            SnapshotOutcome::NotCompiled,
            Some("the subsystem is not compiled into this build".to_string()),
        ),
        Ok(ProviderResult::Busy) => (
            Vec::new(),
            SnapshotOutcome::Busy,
            Some("the subsystem's state was locked; retry".to_string()),
        ),
    };

    // A provider that ignored the deadline is reported, not trusted.
    if overran && outcome == SnapshotOutcome::Ready {
        outcome = SnapshotOutcome::TimedOut;
        reason = Some(format!(
            "the provider ran past its {}ms deadline; its result may be stale",
            timeout.as_millis()
        ));
    }

    // ...and one that ignored the limit is truncated here rather than
    // returning more than was asked for.
    if rows.len() > limit {
        rows.truncate(limit);
        if outcome == SnapshotOutcome::Ready {
            outcome = SnapshotOutcome::Partial;
            reason = Some(format!("truncated to the requested limit of {limit}"));
        }
    }

    let rows: Vec<SnapshotRow> = rows
        .into_iter()
        .map(|row| SnapshotRow {
            fields: row
                .0
                .into_iter()
                .map(|mut field| {
                    if field.privacy == FieldPrivacy::LocalOnly && !local_view {
                        // The slot and the policy stay; only the value goes.
                        field.value = None;
                    }
                    field
                })
                .collect(),
        })
        .collect();

    SnapshotResponse {
        subsystem: provider.subsystem().to_string(),
        outcome,
        reason,
        returned: rows.len(),
        rows,
        selector: selector.map(str::to_string),
        view: if local_view { "local" } else { "remote" }.to_string(),
        elapsed_ms,
    }
}

static ARGS: &[ArgSpec] = &[
    ArgSpec::flag(
        "subsystem",
        "which subsystem to ask; comma-separated for several, omit for all",
        ArgKind::String,
    ),
    ArgSpec::flag(
        "id",
        "a selector whose meaning is the subsystem's, e.g. a task or context id",
        ArgKind::String,
    ),
    ArgSpec::flag(
        "limit",
        "the most rows to return per subsystem",
        ArgKind::Integer,
    ),
    ArgSpec::flag(
        "timeout-ms",
        "how long a single provider may take before its result is reported stale",
        ArgKind::Integer,
    ),
    ArgSpec::flag(
        "view",
        "remote is support-safe only; local additionally includes local-only fields",
        ArgKind::Enum(&["remote", "local"]),
    ),
    ArgSpec::flag(
        "list",
        "list the registered subsystems and return",
        ArgKind::Bool,
    ),
];

const DEFAULT_LIMIT: usize = 256;
const DEFAULT_TIMEOUT_MS: u64 = 250;

/// The `snapshot` command.
///
/// Public so an embedder that builds its own command surface, or a test, can
/// invoke it without going through the global registry.
#[derive(Debug)]
pub struct Snapshot;

impl Command for Snapshot {
    fn name(&self) -> &'static str {
        "snapshot"
    }

    fn short_description(&self) -> &'static str {
        "Shows live state — what exists now, rather than what just happened."
    }

    fn full_description(&self) -> &'static str {
        "Asks registered subsystems to describe their current state.\n\n\
This is the counterpart to reading logs, not a replacement for it. A log says what \
happened; this says what is there — live tasks, queue depths, routing tables. Rebuilding \
that from an event history is unreliable exactly when you need it: after records were \
dropped, or when the state you care about never emitted anything because it never changed.\n\n\
`--list` shows what is registered. With no `--subsystem`, every subsystem is asked.\n\n\
Each answer carries an outcome, and they are kept apart because they call for different \
things:\n\
  ready         everything the selector matched is here\n\
  partial       some of it; `reason` says what stopped it\n\
  unavailable   the subsystem is here but cannot answer now\n\
  not-compiled  it was compiled out of this build\n\
  busy          its state was locked; retry\n\
  panicked      the provider crashed — a bug in that subsystem\n\
  timed-out     it ran past its deadline; the result may be stale\n\n\
`--limit` and `--timeout-ms` are enforced by this command, not left to the provider: one \
that ignores them is truncated or reported rather than trusted.\n\n\
The default view is `remote`, which is support-safe only. `--view local` additionally \
shows local-only fields — values derived from the application's own data. A withheld \
field keeps its slot, so you can tell 'no such field' from 'not shown to you'."
    }

    fn args(&self) -> &'static [ArgSpec] {
        ARGS
    }

    fn execute(&self, args: Vec<String>) -> Result<Response, Response> {
        self.execute_with(args, &CommandContext::detached())
    }

    fn execute_with(
        &self,
        args: Vec<String>,
        context: &CommandContext,
    ) -> Result<Response, Response> {
        let parsed = ParsedArgs::parse(self.args(), args).map_err(Response::String)?;

        if parsed.boolean("list") {
            let listed: Vec<_> = registered()
                .into_iter()
                .map(|(name, description)| SnapshotRow {
                    fields: vec![
                        SnapshotField {
                            name: "subsystem".to_string(),
                            privacy: FieldPrivacy::SupportSafe,
                            value: Some(SnapshotValue::String(name.to_string())),
                        },
                        SnapshotField {
                            name: "description".to_string(),
                            privacy: FieldPrivacy::SupportSafe,
                            value: Some(SnapshotValue::String(description.to_string())),
                        },
                    ],
                })
                .collect();
            return Response::from_serialize(&SnapshotSet {
                snapshots: vec![SnapshotResponse {
                    subsystem: "registry".to_string(),
                    outcome: SnapshotOutcome::Ready,
                    reason: None,
                    returned: listed.len(),
                    rows: listed,
                    selector: None,
                    view: "remote".to_string(),
                    elapsed_ms: 0,
                }],
                unknown: Vec::new(),
            });
        }

        // Comma-separated rather than a repeated flag: `ParsedArgs` rejects a
        // non-variadic flag given twice, and variadic is only meaningful for a
        // positional parameter.
        let wanted: Vec<String> = parsed
            .get("subsystem")
            .map(|value| {
                value
                    .split(',')
                    .map(str::trim)
                    .filter(|name| !name.is_empty())
                    .map(str::to_string)
                    .collect()
            })
            .unwrap_or_default();
        let selector = parsed.get("id");
        let limit = parsed
            .integer("limit")
            .filter(|limit| *limit > 0)
            .map_or(DEFAULT_LIMIT, |limit| limit as usize);
        let timeout = Duration::from_millis(
            parsed
                .integer("timeout-ms")
                .filter(|ms| *ms > 0)
                .map_or(DEFAULT_TIMEOUT_MS, |ms| ms as u64),
        );
        let local_view = parsed.get("view") == Some("local");

        let providers = PROVIDERS.with_sync(|providers| providers.clone());
        let selected: Vec<_> = if wanted.is_empty() {
            providers
        } else {
            providers
                .into_iter()
                .filter(|provider| wanted.iter().any(|name| name == provider.subsystem()))
                .collect()
        };
        let unknown: Vec<String> = wanted
            .iter()
            .filter(|name| {
                !selected
                    .iter()
                    .any(|provider| provider.subsystem() == name.as_str())
            })
            .cloned()
            .collect();

        let cancelled = context.cancel_flag();
        let mut snapshots = Vec::with_capacity(selected.len());
        for provider in &selected {
            // A cancelled request stops between providers; within one, stopping
            // is the provider's own job via `should_stop`.
            context.check_cancelled()?;
            snapshots.push(run(
                provider, selector, limit, timeout, &cancelled, local_view,
            ));
        }

        Response::from_serialize(&SnapshotSet { snapshots, unknown })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use exfiltrate_internal::snapshot::SnapshotSet;
    use std::sync::atomic::AtomicU64;

    /// The registry is process-global, so cases take turns and each starts from
    /// an empty one.
    fn session() -> std::sync::MutexGuard<'static, ()> {
        static SERIALIZE: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let guard = SERIALIZE
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        clear_providers();
        guard
    }

    fn ask(args: &[&str]) -> SnapshotSet {
        let response = Snapshot
            .execute(args.iter().map(|arg| arg.to_string()).collect())
            .expect("snapshot should not fail");
        match response {
            Response::Bytes(bytes) => rmp_serde::from_slice(&bytes).expect("decode"),
            other => panic!("expected a structured response, got {other:?}"),
        }
    }

    fn only(set: &SnapshotSet) -> &SnapshotResponse {
        assert_eq!(set.snapshots.len(), 1, "{set:?}");
        &set.snapshots[0]
    }

    struct Fixed {
        name: &'static str,
        result: fn(&SnapshotRequest<'_>) -> ProviderResult,
    }

    impl Provider for Fixed {
        fn subsystem(&self) -> &'static str {
            self.name
        }
        fn description(&self) -> &'static str {
            "a test provider"
        }
        fn snapshot(&self, request: &SnapshotRequest<'_>) -> ProviderResult {
            (self.result)(request)
        }
    }

    /// The five non-`Ready` outcomes stay distinct, because they call for
    /// different responses from the caller.
    #[wasm_lite::wasm_lite_test]
    fn the_outcomes_are_distinct() {
        let _session = session();
        add_provider(Fixed {
            name: "unavailable",
            result: |_| ProviderResult::Unavailable("no window yet".to_string()),
        });
        add_provider(Fixed {
            name: "notcompiled",
            result: |_| ProviderResult::NotCompiled,
        });
        add_provider(Fixed {
            name: "busy",
            result: |_| ProviderResult::Busy,
        });

        for (subsystem, expected) in [
            ("unavailable", SnapshotOutcome::Unavailable),
            ("notcompiled", SnapshotOutcome::NotCompiled),
            ("busy", SnapshotOutcome::Busy),
        ] {
            let set = ask(&["--subsystem", subsystem]);
            let answer = only(&set);
            assert_eq!(answer.outcome, expected, "{answer:?}");
            assert!(
                answer.reason.is_some(),
                "a non-ready outcome should say why: {answer:?}"
            );
        }
    }

    /// A provider that returns more than was asked for is truncated here, and
    /// the answer says so rather than looking complete.
    #[wasm_lite::wasm_lite_test]
    fn ignoring_the_limit_is_truncated_and_reported_partial() {
        let _session = session();
        add_provider(Fixed {
            name: "greedy",
            result: |_| {
                ProviderResult::Rows((0..50).map(|n| Row::new().support("n", n as u64)).collect())
            },
        });

        let set = ask(&["--subsystem", "greedy", "--limit", "5"]);
        let answer = only(&set);
        assert_eq!(answer.returned, 5);
        assert_eq!(answer.outcome, SnapshotOutcome::Partial);
        assert!(answer.reason.as_deref().unwrap().contains("limit"));
    }

    /// A provider that reports its own truncation keeps its reason.
    #[wasm_lite::wasm_lite_test]
    fn a_self_reported_partial_keeps_its_reason() {
        let _session = session();
        add_provider(Fixed {
            name: "partial",
            result: |_| {
                ProviderResult::Partial(
                    vec![Row::new().support("n", 1u64)],
                    "one shard was locked".to_string(),
                )
            },
        });
        let set = ask(&["--subsystem", "partial"]);
        let answer = only(&set);
        assert_eq!(answer.outcome, SnapshotOutcome::Partial);
        assert_eq!(answer.reason.as_deref(), Some("one shard was locked"));
    }

    /// A provider that ignores the deadline is reported, not trusted. Nothing
    /// can preempt it, so the check is after the fact.
    #[wasm_lite::wasm_lite_test]
    fn ignoring_the_deadline_is_reported_timed_out() {
        let _session = session();
        add_provider(Fixed {
            name: "slow",
            result: |_request| {
                let start = Instant::now();
                while start.elapsed() < Duration::from_millis(30) {
                    std::hint::spin_loop();
                }
                ProviderResult::Rows(vec![Row::new().support("n", 1u64)])
            },
        });

        let set = ask(&["--subsystem", "slow", "--timeout-ms", "5"]);
        let answer = only(&set);
        assert_eq!(answer.outcome, SnapshotOutcome::TimedOut, "{answer:?}");
        assert!(answer.reason.as_deref().unwrap().contains("deadline"));
    }

    /// A well-behaved provider sees `should_stop` go true and stops itself.
    #[wasm_lite::wasm_lite_test]
    fn a_cooperative_provider_observes_the_deadline() {
        let _session = session();
        add_provider(Fixed {
            name: "cooperative",
            result: |request| {
                let mut rows = Vec::new();
                loop {
                    if request.should_stop() {
                        return ProviderResult::Partial(rows, "deadline".to_string());
                    }
                    rows.push(Row::new().support("n", rows.len() as u64));
                    // A safety net only: 5ms cannot reach this, so reaching it
                    // would mean `should_stop` is broken.
                    if rows.len() > 5_000_000 {
                        return ProviderResult::Rows(rows);
                    }
                }
            },
        });

        let set = ask(&[
            "--subsystem",
            "cooperative",
            "--timeout-ms",
            "5",
            "--limit",
            "100000",
        ]);
        let answer = only(&set);
        assert_eq!(answer.outcome, SnapshotOutcome::Partial, "{answer:?}");
        assert_eq!(answer.reason.as_deref(), Some("deadline"));
    }

    /// The whole privacy contract: a remote view is withheld the local-only
    /// value, but the field keeps its slot and its policy so the caller can
    /// tell "no such field" from "not shown to you".
    #[wasm_lite::wasm_lite_test]
    fn local_only_fields_are_withheld_from_a_remote_view() {
        let _session = session();
        add_provider(Fixed {
            name: "mixed",
            result: |_| {
                ProviderResult::Rows(vec![
                    Row::new()
                        .support("depth", 3u64)
                        .local("label", "user typed this"),
                ])
            },
        });

        let remote = ask(&["--subsystem", "mixed"]);
        let row = &only(&remote).rows[0];
        assert_eq!(only(&remote).view, "remote");
        assert_eq!(row.get("depth").unwrap().value, Some(SnapshotValue::U64(3)));
        let label = row.get("label").expect("the field keeps its slot");
        assert_eq!(label.privacy, FieldPrivacy::LocalOnly);
        assert_eq!(label.value, None, "withheld from a remote view");

        let local = ask(&["--subsystem", "mixed", "--view", "local"]);
        let row = &only(&local).rows[0];
        assert_eq!(
            row.get("label").unwrap().value,
            Some(SnapshotValue::String("user typed this".to_string()))
        );
    }

    /// A subsystem nobody registered is named back, rather than silently
    /// producing an empty answer that looks like "nothing there".
    #[wasm_lite::wasm_lite_test]
    fn an_unknown_subsystem_is_reported() {
        let _session = session();
        add_provider(Fixed {
            name: "known",
            result: |_| ProviderResult::Rows(Vec::new()),
        });
        let set = ask(&["--subsystem", "known,nope"]);
        assert_eq!(set.unknown, vec!["nope".to_string()]);
        assert_eq!(set.snapshots.len(), 1);
    }

    /// Re-registering a subsystem replaces it, so a component that
    /// re-initialises does not accumulate duplicates.
    #[wasm_lite::wasm_lite_test]
    fn registering_twice_replaces_rather_than_duplicates() {
        let _session = session();
        add_provider(Fixed {
            name: "dup",
            result: |_| ProviderResult::Rows(vec![Row::new().support("v", 1u64)]),
        });
        add_provider(Fixed {
            name: "dup",
            result: |_| ProviderResult::Rows(vec![Row::new().support("v", 2u64)]),
        });
        assert_eq!(registered().len(), 1);
        let set = ask(&["--subsystem", "dup"]);
        assert_eq!(
            only(&set).rows[0].get("v").unwrap().value,
            Some(SnapshotValue::U64(2))
        );
    }

    /// The selector is passed through to the provider unchanged; its meaning is
    /// the subsystem's.
    #[wasm_lite::wasm_lite_test]
    fn the_selector_reaches_the_provider_and_is_echoed() {
        let _session = session();
        add_provider(Fixed {
            name: "select",
            result: |request| {
                ProviderResult::Rows(vec![
                    Row::new().support("saw", request.selector().unwrap_or("<none>")),
                ])
            },
        });
        let set = ask(&["--subsystem", "select", "--id", "task-7"]);
        let answer = only(&set);
        assert_eq!(answer.selector.as_deref(), Some("task-7"));
        assert_eq!(
            answer.rows[0].get("saw").unwrap().value,
            Some(SnapshotValue::String("task-7".to_string()))
        );
    }

    /// State changing underneath a provider yields a coherent bounded answer
    /// rather than a torn one: the provider reads a consistent value per row and
    /// the registry bounds the result.
    ///
    /// `(worker)` because it joins the writer, and a blocking join is
    /// `Atomics.wait`, which traps on the browser main thread.
    #[wasm_lite::wasm_lite_test(worker)]
    fn concurrent_mutation_still_yields_a_coherent_answer() {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let _session = session();
        COUNTER.store(0, Ordering::SeqCst);

        add_provider(Fixed {
            name: "mutating",
            result: |request| {
                let mut rows = Vec::new();
                for _ in 0..64 {
                    if request.should_stop() {
                        return ProviderResult::Partial(rows, "stopped".to_string());
                    }
                    // Each row observes one atomic read; the value may differ
                    // between rows, which is what a live snapshot means.
                    rows.push(Row::new().support("seen", COUNTER.load(Ordering::SeqCst)));
                }
                ProviderResult::Rows(rows)
            },
        });

        // `std::thread::spawn` is unsupported on wasm32; threads go through
        // wasm_lite_std there.
        #[cfg(not(target_arch = "wasm32"))]
        let writer = std::thread::spawn(|| {
            for _ in 0..10_000 {
                COUNTER.fetch_add(1, Ordering::SeqCst);
            }
        });
        #[cfg(target_arch = "wasm32")]
        let writer = wasm_lite_std::spawn(|| {
            for _ in 0..10_000 {
                COUNTER.fetch_add(1, Ordering::SeqCst);
            }
        });
        let set = ask(&["--subsystem", "mutating", "--limit", "64"]);
        writer.join().expect("writer");

        let answer = only(&set);
        assert!(answer.returned <= 64);
        for row in &answer.rows {
            // Every row is well-formed: the field is present and is a number.
            assert!(matches!(
                row.get("seen").unwrap().value,
                Some(SnapshotValue::U64(_))
            ));
        }
    }

    /// `--list` names what is registered without running anything.
    #[wasm_lite::wasm_lite_test]
    fn list_names_the_registered_subsystems() {
        let _session = session();
        add_provider(Fixed {
            name: "listed",
            result: |_| panic!("--list must not run providers"),
        });
        let set = ask(&["--list"]);
        let answer = only(&set);
        assert_eq!(answer.subsystem, "registry");
        assert!(
            answer
                .rows
                .iter()
                .any(|row| row.get("subsystem").unwrap().value
                    == Some(SnapshotValue::String("listed".to_string()))),
            "{answer:?}"
        );
    }

    /// A cancelled request stops instead of asking every provider.
    #[wasm_lite::wasm_lite_test]
    fn a_cancelled_request_stops() {
        let _session = session();
        add_provider(Fixed {
            name: "never",
            result: |_| panic!("a cancelled request must not reach a provider"),
        });
        let context = CommandContext::new(Arc::new(AtomicBool::new(true)), Arc::new(|_| Ok(())));
        assert!(Snapshot.execute_with(Vec::new(), &context).is_err());
    }

    /// A provider that panics is reported as a bug in that subsystem, not as an
    /// empty result.
    ///
    /// Native only: the wasm32 profile builds std with `panic_abort`, so there
    /// is nothing to catch. That difference is stated in `run` rather than
    /// silently tolerated.
    #[cfg(not(target_arch = "wasm32"))]
    #[test]
    fn a_panicking_provider_is_reported_not_swallowed() {
        let _session = session();
        add_provider(Fixed {
            name: "boom",
            result: |_| panic!("deliberate provider panic"),
        });
        // The default hook would print the panic; quiet it for this one case.
        let previous = std::panic::take_hook();
        std::panic::set_hook(Box::new(|_| {}));
        let set = ask(&["--subsystem", "boom"]);
        std::panic::set_hook(previous);

        let answer = only(&set);
        assert_eq!(answer.outcome, SnapshotOutcome::Panicked);
        assert!(answer.reason.as_deref().unwrap().contains("bug"));
        assert!(answer.rows.is_empty());
    }
}