ignition-core 1.1.0

Core library for ign: config, profiles, gateway client, actions, error taxonomy
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
//! Log actions (02-04, HLTH-03/04): the poll-based TAIL loop — serde
//! models and a sink OUT, no printing (ARCHITECTURE.md layering: the
//! Phase-6 TUI rides this same layer).
//!
//! There is NO server push for gateway logs (02-RESEARCH Don't-Hand-Roll
//! table): `GET /logs?startTime=<epoch-ms>` IS the tail primitive. The
//! loop polls through the shared [`crate::poll`] engine (×1.5 adaptive
//! backoff, Network/GatewayRestarting retried, Auth never) — the same
//! engine 02-05's `wait` reuses.
//!
//! Cursor semantics (plan key_link): start at `since` (or 0 = the
//! whole buffer); every page advances the cursor to the max timestamp
//! seen; the next query sends `startTime = cursor + 1` — no overlap,
//! no gaps. Entries are sorted client-side so the stream order is
//! timestamp order regardless of the server's page ordering.
//!
//! `deadline: None` = run until Ctrl-C (the process default kill —
//! research: keep Ctrl-C simple, README-documented); `Some(d)` ends
//! GRACEFULLY: the poll's deadline expiry maps to `Ok` (exit 0 — the
//! entries already streamed through the sink).

use std::path::Path;
use std::sync::Mutex;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use serde::Serialize;

use crate::client::logs::{LogDownload, LogEntry, LogQuery, LoggerInfo};
// Public re-export: the list action's return type is the wire-faithful
// page — callers (and ActionOutput) name it via the action module.
use crate::client::GatewayApi;
pub use crate::client::logs::LogPage;
use crate::client::query::ListEnvelope;
use crate::error::CoreError;
use crate::poll::{self, PollConfig, PollState};

/// `ign logs download` output model.
#[derive(Debug, Serialize)]
pub struct DownloadResult {
    /// Path of the file written.
    pub file: String,
    /// Bytes written.
    pub bytes: usize,
    /// Response content type (`application/x-sqlite3` — verified).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub content_type: Option<String>,
}

/// `ign logs loggers set` output model.
#[derive(Debug, Serialize)]
pub struct SetLevelResult {
    /// The logger that was changed.
    pub logger: String,
    /// The level it now carries (uppercase wire form).
    pub level: String,
}

/// `ign logs loggers reset` output model.
#[derive(Debug, Serialize)]
pub struct ResetResult {
    /// Always `true` — the reset reset every custom level.
    pub reset: bool,
}

/// The logger registry page (`ign logs loggers`).
pub type LoggersEnvelope = ListEnvelope<LoggerInfo>;

/// `ign logs` (no `--follow`): newest entries first. The query always
/// sorts `desc(timestamp)` and carries an explicit `limit` — together
/// they make "the recent log entries" (must-have truth #1) without a
/// `--since` window guess: `--limit 200` = the NEWEST 200, not the
/// oldest.
pub async fn list_logs(
    api: &dyn GatewayApi,
    logger: Option<&str>,
    min_level: Option<&str>,
    since_ms: Option<i64>,
    limit: i64,
) -> Result<LogPage, CoreError> {
    let query = LogQuery {
        start_time: since_ms,
        logger: logger.map(str::to_string),
        min_level: min_level.map(str::to_string),
        limit,
        sort_by: Some("desc(timestamp)".to_string()),
        ..LogQuery::default()
    };
    api.logs(&query).await
}

/// `ign logs loggers`: the logger registry, explicit `limit` (must-have
/// truth #5 — even the registry never rides the unlimited default),
/// optional substring `search`.
pub async fn loggers(
    api: &dyn GatewayApi,
    search: Option<&str>,
) -> Result<ListEnvelope<LoggerInfo>, CoreError> {
    let query = crate::client::query::ListQuery {
        limit: crate::client::logs::DEFAULT_LOG_LIMIT,
        search: search.map(str::to_string),
        ..Default::default()
    };
    api.loggers(&query).await
}

/// `ign logs loggers set <name> <LEVEL>`. Confirmation guarding belongs
/// to the CALLER (the CLI refuses without `--yes` before any API
/// construction) — the action is the obedient arm.
pub async fn set_logger_level(
    api: &dyn GatewayApi,
    logger: &str,
    level: &str,
) -> Result<SetLevelResult, CoreError> {
    api.set_logger_level(logger, level).await?;
    Ok(SetLevelResult {
        logger: logger.to_string(),
        level: level.to_string(),
    })
}

/// `ign logs loggers reset` — same guard contract as set.
pub async fn reset_logger_levels(api: &dyn GatewayApi) -> Result<ResetResult, CoreError> {
    api.reset_logger_levels().await?;
    Ok(ResetResult { reset: true })
}

/// The download filename: `-o FILE` wins, then the gateway's
/// `Content-Disposition` name, then `<stem>-logs-<unix_ts>.idb` — NEVER
/// `.zip` (Pitfall 7: the archive is SQLite).
fn download_filename(
    output: Option<&Path>,
    download: &LogDownload,
    stem: &str,
    now_secs: i64,
) -> String {
    if let Some(output) = output {
        return output.display().to_string();
    }
    if let Some(filename) = download.filename.as_deref().filter(|name| !name.is_empty()) {
        return filename.to_string();
    }
    format!("{stem}-logs-{now_secs}.idb")
}

/// `ign logs download` — fetch the `.idb` archive and write it EXACTLY
/// as received (no transformation, no extraction). `stem` names the
/// gateway for the fallback filename (the CLI passes the profile name).
pub async fn download(
    api: &dyn GatewayApi,
    output: Option<&Path>,
    fallback_stem: &str,
) -> Result<DownloadResult, CoreError> {
    let fetched = api.logs_download().await?;
    let now_secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|since| since.as_secs() as i64)
        .unwrap_or_default();
    let file = download_filename(output, &fetched, fallback_stem, now_secs);
    std::fs::write(&file, &fetched.bytes)
        .map_err(|err| CoreError::Internal(format!("cannot write log archive {file}: {err}")))?;
    Ok(DownloadResult {
        bytes: fetched.bytes.len(),
        content_type: fetched.content_type,
        file,
    })
}

/// Parse `--since`: an absolute `EPOCH_MS` value or a relative span
/// `Nms` / `Ns` / `Nmin` / `Nh` (resolved against `now_ms`). Returned
/// as a plain `String` error so clap can surface it as a usage-class
/// parse failure (exit 2) — validation happens at arg-parse time, not
/// deep in dispatch.
pub fn parse_since(spec: &str, now_ms: i64) -> Result<i64, String> {
    let spec = spec.trim();
    // Order matters: "ms" before bare "s"; "min" between them.
    for (suffix, unit_ms) in [
        ("ms", 1_i64),
        ("min", 60_000),
        ("h", 3_600_000),
        ("s", 1_000),
    ] {
        if let Some(digits) = spec.strip_suffix(suffix)
            && let Ok(count) = digits.parse::<i64>()
            && count >= 0
        {
            return Ok(now_ms - count * unit_ms);
        }
    }
    // Absolute epoch-ms (also covers "0" = the whole buffer).
    match spec.parse::<i64>() {
        Ok(epoch_ms) if epoch_ms >= 0 => Ok(epoch_ms),
        _ => Err(format!(
            "invalid --since {spec:?}: expected EPOCH-MS or a relative span like 500ms, 30s, 5min, 2h"
        )),
    }
}

/// `ign logs --follow` result — how much streamed before the tail
/// ended. (Ctrl-C never reaches here: the process default kill emits
/// no envelope at all, README-documented.)
#[derive(Debug, Default, Serialize)]
pub struct TailResult {
    /// Entries delivered to the sink.
    pub streamed: usize,
}

/// The tail loop's probe scratch: the cursor (epoch ms) and the sink.
/// Owned by [`poll`], lent fresh to every probe call.
struct TailState<'a> {
    /// Max timestamp delivered so far (-1 before the first page).
    cursor: i64,
    /// Receives each entry as it arrives (the action stays
    /// printer-free — the dispatch owns stdout). `+ Send` so the tail
    /// future can cross `tokio::spawn` on the multi-thread runtime
    /// (06-01: the TUI's logs worker; the rig.rs sinks set this
    /// convention first).
    sink: &'a mut (dyn FnMut(&LogEntry) + Send),
}

/// Stream new log entries to `sink` as they arrive. The action is
/// printer-free — the dispatch owns stdout (human lines or NDJSON).
///
/// Every query carries an explicit limit ([`LogQuery::default`] —
/// Pitfall 9); a page larger than the limit still advances the cursor
/// correctly (cursor = max timestamp seen, so the next poll resumes
/// exactly past it).
pub async fn tail(
    api: &dyn GatewayApi,
    logger: Option<&str>,
    min_level: Option<&str>,
    since_ms: Option<i64>,
    interval: Duration,
    deadline: Option<Duration>,
    sink: &mut (dyn FnMut(&LogEntry) + Send),
) -> Result<TailResult, CoreError> {
    // -1 so the FIRST query's start_time = cursor + 1 = since exactly
    // (or 0 when no --since — the whole buffer).
    let state = TailState {
        cursor: since_ms.unwrap_or(0) - 1,
        sink,
    };
    // The stream count lives OUTSIDE the poll call (the probe bumps it
    // through a shared borrow; poll consumes the state). A `Mutex` (not
    // `Cell`) so the probe future is Send — the 06-02 TUI spawns tails.
    let streamed = Mutex::new(0usize);

    let cfg = PollConfig {
        subject: "log tail (GET /data/api/v1/logs)".to_string(),
        interval,
        deadline: deadline.unwrap_or(Duration::MAX),
        ..PollConfig::default()
    };

    let outcome = poll::poll(cfg, state, |state| {
        Box::pin(async {
            let query = LogQuery {
                start_time: Some(state.cursor + 1),
                logger: logger.map(str::to_string),
                min_level: min_level.map(str::to_string),
                ..LogQuery::default()
            };
            let page = api.logs(&query).await?;
            let mut entries = page.items;
            // Timestamp order regardless of server page ordering.
            entries.sort_by_key(|entry| entry.timestamp);
            let observation = entries
                .last()
                .map(|last| format!("{} entries, latest at {}", entries.len(), last.timestamp));
            for entry in &entries {
                (state.sink)(entry);
            }
            if let Some(last) = entries.last() {
                state.cursor = last.timestamp;
            }
            *streamed.lock().expect("streamed count") += entries.len();
            Ok(PollState::<()>::Pending(observation))
        })
    })
    .await;

    match outcome {
        // The probe never reports Done (T = ()) — the only Ok is
        // unreachable; kept for match totality.
        Ok(()) => Ok(TailResult {
            streamed: *streamed.lock().expect("streamed count"),
        }),
        // Deadline expiry = GRACEFUL end (exit 0): poll retries genuine
        // Network errors until the deadline, so a None-source Network
        // error IS the timeout. The entries already streamed.
        Err(CoreError::Network { source: None, .. }) => Ok(TailResult {
            streamed: *streamed.lock().expect("streamed count"),
        }),
        Err(err) => Err(err),
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;
    use std::time::Duration;

    use super::{download_filename, parse_since, tail};
    use crate::client::GatewayApi;
    use crate::client::logs::{LogDownload, LogEntry, LogQuery};
    use crate::client::query::{ListEnvelope, ListMetadata};
    use crate::error::CoreError;

    /// `--since` accepts EPOCH-MS and every relative suffix, parsed
    /// against a fixed now; junk is a usage-class String error.
    #[test]
    fn parse_since_accepts_epoch_and_relative_spans() {
        const NOW: i64 = 1_787_346_747_022;
        assert_eq!(parse_since("1787346747022", NOW), Ok(1787346747022));
        assert_eq!(parse_since("0", NOW), Ok(0));
        assert_eq!(parse_since("500ms", NOW), Ok(NOW - 500));
        assert_eq!(parse_since("30s", NOW), Ok(NOW - 30_000));
        assert_eq!(parse_since("5min", NOW), Ok(NOW - 300_000));
        assert_eq!(parse_since("2h", NOW), Ok(NOW - 7_200_000));
        // suffix order matters: "ms" before bare "s"
        assert_eq!(parse_since("1s", NOW), Ok(NOW - 1_000));
        assert!(parse_since("banana", NOW).is_err());
        assert!(
            parse_since("-5s", NOW).is_err(),
            "negative spans are invalid"
        );
        assert!(parse_since("", NOW).is_err());
    }

    /// Filename precedence: `-o FILE` > Content-Disposition > the
    /// `<stem>-logs-<ts>.idb` fallback — and NEVER a `.zip` (Pitfall 7).
    #[test]
    fn download_filename_precedence() {
        let fetched = LogDownload {
            bytes: Vec::new(),
            filename: Some("GW_Ignition_logs_20260822-0307.idb".into()),
            content_type: Some("application/x-sqlite3".into()),
        };
        assert_eq!(
            download_filename(
                Some(std::path::Path::new("/tmp/out.idb")),
                &fetched,
                "dev",
                1000
            ),
            "/tmp/out.idb",
            "-o wins"
        );
        assert_eq!(
            download_filename(None, &fetched, "dev", 1000),
            "GW_Ignition_logs_20260822-0307.idb",
            "Content-Disposition name second"
        );
        let anonymous = LogDownload {
            bytes: Vec::new(),
            filename: None,
            content_type: None,
        };
        assert_eq!(
            download_filename(None, &anonymous, "dev", 1_787_346_747),
            "dev-logs-1787346747.idb",
            "fallback = <stem>-logs-<unix_ts>.idb — never .zip"
        );
    }

    /// A scripted double: serves `pages` in order (then empty pages
    /// forever) and records every query it saw.
    #[derive(Default)]
    struct TailRig {
        pages: Mutex<std::collections::VecDeque<Vec<LogEntry>>>,
        queries: Mutex<Vec<LogQuery>>,
    }

    fn entry(timestamp: i64, message: &str) -> LogEntry {
        LogEntry {
            timestamp,
            logger_name: "GatewayManager".into(),
            level: "INFO".into(),
            message: message.into(),
            stack: Vec::new(),
            mdc: Default::default(),
            extra: Default::default(),
        }
    }

    #[async_trait::async_trait]
    impl GatewayApi for TailRig {
        async fn bundle_generate(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_status(
            &self,
        ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn bundle_download(
            &self,
            _out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_list(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<
            crate::client::query::ListEnvelope<crate::client::tags::TagProviderRecord>,
            CoreError,
        > {
            unreachable!("not part of this action")
        }
        async fn tag_provider_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::tags::TagProviderRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_create(
            &self,
            _body: &[crate::client::tags::TagProviderCreate],
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn tag_provider_delete(
            &self,
            _name: &str,
            _signature: &str,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_status_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn banners(&self) -> Result<crate::client::trial::BannerSet, CoreError> {
            unreachable!("not part of this action")
        }
        async fn trial_reset_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_download(
            &self,
            _out: &std::path::Path,
            _backup_type: crate::client::backup::BackupType,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn backup_restore(&self, _gwbk: &std::path::Path) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_history(
            &self,
            _limit: Option<u32>,
            _search: Option<&str>,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamHistoryItem>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_definitions(
            &self,
        ) -> Result<crate::client::query::ListEnvelope<crate::client::eam::EamTaskRecord>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn eam_task_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::eam::EamTaskRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_create(&self, _definition: &serde_json::Value) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_force(&self, _owner: &str, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_suspend(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_resume(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_cancel(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_tasks_scheduled(
            &self,
            _running: bool,
        ) -> Result<Vec<crate::client::eam::EamScheduledTask>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_modify(
            &self,
            _definition: &serde_json::Value,
        ) -> Result<Option<crate::client::eam::ModifyOutcome>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn eam_task_delete(
            &self,
            _name: &str,
            _signature: &str,
            _confirm: bool,
        ) -> Result<crate::client::eam::DeleteOutcome, CoreError> {
            unreachable!("not part of this action")
        }
        async fn api_call(
            &self,
            _call: &crate::client::apicall::ApiCallRequest,
        ) -> Result<crate::client::apicall::ApiCallData, CoreError> {
            unreachable!("not part of this action")
        }
        async fn license_status(
            &self,
        ) -> Result<crate::client::license::LicenseStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn redundancy_status(
            &self,
        ) -> Result<crate::client::redundancy::RedundancyStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn gan_status(&self) -> Result<crate::client::gan::GanStatusWire, CoreError> {
            unreachable!("not part of this action")
        }
        async fn logs(&self, filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError> {
            self.queries.lock().unwrap().push(filter.clone());
            let items = self.pages.lock().unwrap().pop_front().unwrap_or_default();
            Ok(ListEnvelope {
                metadata: ListMetadata {
                    total: items.len() as i64,
                    matching: items.len() as i64,
                    limit: 200,
                    offset: 0,
                },
                items,
            })
        }
        async fn gateway_info(&self) -> Result<crate::client::version::GatewayInfo, CoreError> {
            unreachable!("not part of this action")
        }
        async fn overview(&self) -> Result<crate::client::status::Overview, CoreError> {
            unreachable!("not part of this action")
        }
        async fn status_ping(&self) -> Result<crate::client::status::StatusPing, CoreError> {
            unreachable!("not part of this action")
        }
        async fn modules(
            &self,
            _quarantined: bool,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::status::ModuleInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_current(
            &self,
        ) -> Result<crate::client::metrics::CurrentGauges, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_historic(
            &self,
        ) -> Result<crate::client::metrics::PerformanceCharts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn metrics_threads(&self) -> Result<crate::client::metrics::ThreadCounts, CoreError> {
            unreachable!("not part of this action")
        }
        async fn designers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::DesignerInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn perspective_sessions(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::PerspectiveSession>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn vision_clients(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::sessions::VisionClient>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn terminate_perspective_session(
            &self,
            _id: &str,
            _message: Option<&str>,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn terminate_vision_client(&self, _id: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn prune_designer(&self, _id: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn database_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn opc_connections(
            &self,
        ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
        {
            unreachable!("not part of this action")
        }
        async fn logs_download(&self) -> Result<crate::client::logs::LogDownload, CoreError> {
            unreachable!("not part of this action")
        }
        async fn loggers(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<ListEnvelope<crate::client::logs::LoggerInfo>, CoreError> {
            unreachable!("not part of this action")
        }
        async fn set_logger_level(&self, _logger: &str, _level: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn reset_logger_levels(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn restart(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn scan_projects(&self) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn security_properties(
            &self,
        ) -> Result<crate::client::restart::SecurityProperties, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_status(&self, _route: &str) -> Result<u16, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_call(
            &self,
            _project: &str,
            _route: &str,
            _body: &serde_json::Value,
            _extra_headers: &[(&str, &str)],
        ) -> Result<serde_json::Value, CoreError> {
            unreachable!("not part of this action")
        }
        async fn webdev_route_probe(
            &self,
            _project: &str,
            _route: &str,
            _extra_headers: &[(&str, &str)],
        ) -> Result<crate::client::webdev::RouteProbe, CoreError> {
            unreachable!("not part of this action")
        }
        async fn projects(
            &self,
            _query: &crate::client::query::ListQuery,
        ) -> Result<
            crate::client::query::ListEnvelope<crate::client::projects::ProjectRecord>,
            CoreError,
        > {
            unreachable!("not part of this action")
        }
        async fn project_find(
            &self,
            _name: &str,
        ) -> Result<crate::client::projects::ProjectRecord, CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_create(
            &self,
            _body: &crate::client::projects::ProjectCreate,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_copy(&self, _from: &str, _to: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_rename(&self, _name: &str, _new_name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_modify(
            &self,
            _name: &str,
            _body: &crate::client::projects::ProjectModify,
        ) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_delete(&self, _name: &str) -> Result<(), CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_export_to_file(
            &self,
            _name: &str,
            _out: &std::path::Path,
        ) -> Result<crate::client::projects::ExportMeta, CoreError> {
            unreachable!("not part of this action")
        }
        async fn project_import(
            &self,
            _name: &str,
            _zip: Vec<u8>,
            _overwrite: bool,
        ) -> Result<crate::client::projects::ImportOutcome, CoreError> {
            unreachable!("not part of this action")
        }
    }

    /// Two pages then silence under a short deadline: entries arrive in
    /// TIMESTAMP order through the sink, the cursor advances past each
    /// page's max (next query's startTime = max + 1), and the deadline
    /// expiry ends the tail CLEANLY (Ok, exit 0 semantics).
    #[tokio::test]
    async fn tail_streams_pages_in_order_and_ends_cleanly_on_deadline() {
        let rig = TailRig {
            pages: Mutex::new(
                vec![
                    // Deliberately out of order WITHIN the page: client-side
                    // sort must fix the stream order.
                    vec![entry(1010, "second"), entry(1005, "first")],
                    vec![entry(1022, "third"), entry(1018, "wait, also")],
                ]
                .into(),
            ),
            queries: Mutex::new(Vec::new()),
        };

        let mut received: Vec<(i64, String)> = Vec::new();
        let sink: &mut (dyn FnMut(&LogEntry) + Send) = &mut |entry: &LogEntry| {
            received.push((entry.timestamp, entry.message.clone()));
        };

        let result = tail(
            &rig,
            None,
            None,
            Some(1000), // since → first query startTime = 1000
            Duration::from_millis(5),
            // Deadline budget generous on purpose: 40ms starved the
            // second page under a full parallel workspace run (the
            // rig serves pages from memory — only scheduler latency
            // competes). 400ms gives ~10x headroom while keeping the
            // isolated test under half a second.
            Some(Duration::from_millis(400)),
            sink,
        )
        .await
        .expect("deadline expiry ends the tail cleanly");

        // Entries delivered in timestamp order across BOTH pages.
        assert_eq!(
            received,
            vec![
                (1005, "first".into()),
                (1010, "second".into()),
                (1018, "wait, also".into()),
                (1022, "third".into()),
            ],
            "stream order is timestamp order (client-side sort)"
        );
        assert_eq!(result.streamed, 4);

        // Cursor discipline: first query starts at `since` exactly;
        // after page 1 (max 1010) the next startTime = 1011; after
        // page 2 (max 1022) the next startTime = 1023 (then silence).
        let queries = rig.queries.lock().unwrap();
        assert_eq!(queries[0].start_time, Some(1000), "first = since");
        assert!(
            queries.len() >= 3,
            "polled again after each page: {}",
            queries.len()
        );
        assert_eq!(queries[1].start_time, Some(1011), "cursor = max + 1");
        assert!(
            queries[2].start_time == Some(1023),
            "cursor advanced past page 2: {:?}",
            queries[2].start_time
        );
        // Every query carries the explicit limit (Pitfall 9).
        assert!(queries.iter().all(|query| query.limit == 200));
    }

    /// Auth failures surface immediately — the tail never retries a
    /// rejected token (the poll engine's never-retry rule, proven at
    /// the action seam).
    #[tokio::test]
    async fn tail_fails_fast_on_auth() {
        struct AuthRig;
        #[async_trait::async_trait]
        impl GatewayApi for AuthRig {
            async fn bundle_generate(
                &self,
            ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn bundle_status(
                &self,
            ) -> Result<crate::client::diagnostics::BundleStatusWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn bundle_download(
                &self,
                _out: &std::path::Path,
            ) -> Result<crate::client::projects::ExportMeta, CoreError> {
                unreachable!("not part of this action")
            }
            async fn tag_provider_list(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<
                crate::client::query::ListEnvelope<crate::client::tags::TagProviderRecord>,
                CoreError,
            > {
                unreachable!("not part of this action")
            }
            async fn tag_provider_find(
                &self,
                _name: &str,
            ) -> Result<crate::client::tags::TagProviderRecord, CoreError> {
                unreachable!("not part of this action")
            }
            async fn tag_provider_create(
                &self,
                _body: &[crate::client::tags::TagProviderCreate],
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn tag_provider_delete(
                &self,
                _name: &str,
                _signature: &str,
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn trial_status_wire(
                &self,
            ) -> Result<crate::client::trial::TrialWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn banners(&self) -> Result<crate::client::trial::BannerSet, CoreError> {
                unreachable!("not part of this action")
            }
            async fn trial_reset_wire(&self) -> Result<crate::client::trial::TrialWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn backup_download(
                &self,
                _out: &std::path::Path,
                _backup_type: crate::client::backup::BackupType,
            ) -> Result<crate::client::projects::ExportMeta, CoreError> {
                unreachable!("not part of this action")
            }
            async fn backup_restore(&self, _gwbk: &std::path::Path) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_history(
                &self,
                _limit: Option<u32>,
                _search: Option<&str>,
            ) -> Result<
                crate::client::query::ListEnvelope<crate::client::eam::EamHistoryItem>,
                CoreError,
            > {
                unreachable!("not part of this action")
            }
            async fn eam_task_definitions(
                &self,
            ) -> Result<
                crate::client::query::ListEnvelope<crate::client::eam::EamTaskRecord>,
                CoreError,
            > {
                unreachable!("not part of this action")
            }
            async fn eam_task_find(
                &self,
                _name: &str,
            ) -> Result<crate::client::eam::EamTaskRecord, CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_create(
                &self,
                _definition: &serde_json::Value,
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_force(&self, _owner: &str, _name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_suspend(&self, _name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_resume(&self, _name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_cancel(&self, _name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_tasks_scheduled(
                &self,
                _running: bool,
            ) -> Result<Vec<crate::client::eam::EamScheduledTask>, CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_modify(
                &self,
                _definition: &serde_json::Value,
            ) -> Result<Option<crate::client::eam::ModifyOutcome>, CoreError> {
                unreachable!("not part of this action")
            }
            async fn eam_task_delete(
                &self,
                _name: &str,
                _signature: &str,
                _confirm: bool,
            ) -> Result<crate::client::eam::DeleteOutcome, CoreError> {
                unreachable!("not part of this action")
            }
            async fn api_call(
                &self,
                _call: &crate::client::apicall::ApiCallRequest,
            ) -> Result<crate::client::apicall::ApiCallData, CoreError> {
                unreachable!("not part of this action")
            }
            async fn license_status(
                &self,
            ) -> Result<crate::client::license::LicenseStatusWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn redundancy_status(
                &self,
            ) -> Result<crate::client::redundancy::RedundancyStatusWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn gan_status(&self) -> Result<crate::client::gan::GanStatusWire, CoreError> {
                unreachable!("not part of this action")
            }
            async fn logs(&self, _filter: &LogQuery) -> Result<ListEnvelope<LogEntry>, CoreError> {
                Err(CoreError::Auth {
                    status: 401,
                    endpoint: Some("http://gw/data/api/v1/logs".into()),
                })
            }
            async fn gateway_info(&self) -> Result<crate::client::version::GatewayInfo, CoreError> {
                unreachable!("not part of this action")
            }
            async fn overview(&self) -> Result<crate::client::status::Overview, CoreError> {
                unreachable!("not part of this action")
            }
            async fn status_ping(&self) -> Result<crate::client::status::StatusPing, CoreError> {
                unreachable!("not part of this action")
            }
            async fn modules(
                &self,
                _quarantined: bool,
                _query: &crate::client::query::ListQuery,
            ) -> Result<ListEnvelope<crate::client::status::ModuleInfo>, CoreError> {
                unreachable!("not part of this action")
            }
            async fn metrics_current(
                &self,
            ) -> Result<crate::client::metrics::CurrentGauges, CoreError> {
                unreachable!("not part of this action")
            }
            async fn metrics_historic(
                &self,
            ) -> Result<crate::client::metrics::PerformanceCharts, CoreError> {
                unreachable!("not part of this action")
            }
            async fn metrics_threads(
                &self,
            ) -> Result<crate::client::metrics::ThreadCounts, CoreError> {
                unreachable!("not part of this action")
            }
            async fn designers(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<ListEnvelope<crate::client::sessions::DesignerInfo>, CoreError>
            {
                unreachable!("not part of this action")
            }
            async fn perspective_sessions(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<ListEnvelope<crate::client::sessions::PerspectiveSession>, CoreError>
            {
                unreachable!("not part of this action")
            }
            async fn vision_clients(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<ListEnvelope<crate::client::sessions::VisionClient>, CoreError>
            {
                unreachable!("not part of this action")
            }
            async fn terminate_perspective_session(
                &self,
                _id: &str,
                _message: Option<&str>,
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn terminate_vision_client(&self, _id: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn prune_designer(&self, _id: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn database_connections(
                &self,
            ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
            {
                unreachable!("not part of this action")
            }
            async fn opc_connections(
                &self,
            ) -> Result<ListEnvelope<crate::client::connections::GatewayConnection>, CoreError>
            {
                unreachable!("not part of this action")
            }
            async fn logs_download(&self) -> Result<crate::client::logs::LogDownload, CoreError> {
                unreachable!("not part of this action")
            }
            async fn loggers(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<ListEnvelope<crate::client::logs::LoggerInfo>, CoreError> {
                unreachable!("not part of this action")
            }
            async fn set_logger_level(&self, _logger: &str, _level: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn reset_logger_levels(&self) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn restart(&self) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn scan_projects(&self) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn security_properties(
                &self,
            ) -> Result<crate::client::restart::SecurityProperties, CoreError> {
                unreachable!("not part of this action")
            }
            async fn webdev_route_status(&self, _route: &str) -> Result<u16, CoreError> {
                unreachable!("not part of this action")
            }
            async fn webdev_route_call(
                &self,
                _project: &str,
                _route: &str,
                _body: &serde_json::Value,
                _extra_headers: &[(&str, &str)],
            ) -> Result<serde_json::Value, CoreError> {
                unreachable!("not part of this action")
            }
            async fn webdev_route_probe(
                &self,
                _project: &str,
                _route: &str,
                _extra_headers: &[(&str, &str)],
            ) -> Result<crate::client::webdev::RouteProbe, CoreError> {
                unreachable!("not part of this action")
            }
            async fn projects(
                &self,
                _query: &crate::client::query::ListQuery,
            ) -> Result<
                crate::client::query::ListEnvelope<crate::client::projects::ProjectRecord>,
                CoreError,
            > {
                unreachable!("not part of this action")
            }
            async fn project_find(
                &self,
                _name: &str,
            ) -> Result<crate::client::projects::ProjectRecord, CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_create(
                &self,
                _body: &crate::client::projects::ProjectCreate,
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_copy(&self, _from: &str, _to: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_rename(&self, _name: &str, _new_name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_modify(
                &self,
                _name: &str,
                _body: &crate::client::projects::ProjectModify,
            ) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_delete(&self, _name: &str) -> Result<(), CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_export_to_file(
                &self,
                _name: &str,
                _out: &std::path::Path,
            ) -> Result<crate::client::projects::ExportMeta, CoreError> {
                unreachable!("not part of this action")
            }
            async fn project_import(
                &self,
                _name: &str,
                _zip: Vec<u8>,
                _overwrite: bool,
            ) -> Result<crate::client::projects::ImportOutcome, CoreError> {
                unreachable!("not part of this action")
            }
        }

        let sink: &mut (dyn FnMut(&LogEntry) + Send) = &mut |_| {};
        let err = tail(
            &AuthRig,
            None,
            None,
            None,
            Duration::from_millis(5),
            Some(Duration::from_secs(5)),
            sink,
        )
        .await
        .expect_err("auth must fail fast");
        assert!(matches!(err, CoreError::Auth { status: 401, .. }));
        assert_eq!(err.exit_code(), 5);
    }
}