cross-stream 0.14.1

An event stream store for personal, local-first use, specializing in event sourcing.
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
#[cfg(test)]
mod tests {
    use nu_protocol::{PipelineData, Span, Value};
    use serde_json::json;
    use std::str::FromStr;
    use tempfile::TempDir;

    use crate::error::Error;
    use crate::nu::{commands, util, Engine};
    use crate::store::{Frame, Store};

    fn setup_test_env() -> (Store, Engine) {
        // Store::new captures the ambient tokio runtime handle so the now-sync
        // read() can spawn its follow/heartbeat tasks. These tests are plain
        // `#[test]`s with no ambient runtime, so enter a shared long-lived one
        // (leaked; lives for the whole test binary) before creating the store.
        use std::sync::OnceLock;
        static RT: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
        let rt = RT.get_or_init(|| tokio::runtime::Runtime::new().unwrap());
        let _guard = rt.enter();

        let temp_dir = TempDir::new().unwrap();
        let store = Store::new(temp_dir.keep()).unwrap();
        let engine = Engine::new().unwrap();
        (store, engine)
    }

    // Helper to run Nu eval in its own thread
    fn nu_eval(engine: &Engine, input: PipelineData, command: impl Into<String>) -> Value {
        let engine = engine.clone();
        let command = command.into();
        std::thread::spawn(move || {
            engine
                .eval(input, command)
                .unwrap()
                .into_value(Span::test_data())
                .unwrap()
        })
        .join()
        .unwrap()
    }

    fn value_to_frame(value: Value) -> Frame {
        let value = util::value_to_json(&value);
        serde_json::from_value(value).expect("Failed to deserialize JSON into Frame")
    }

    fn setup_scru128_test_env() -> Engine {
        let (_store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![
                Box::new(commands::scru128_command::Scru128Command::new()),
                Box::new(commands::scru128_command::Scru128UnpackCommand::new()),
                Box::new(commands::scru128_command::Scru128PackCommand::new()),
            ])
            .unwrap();
        engine
    }

    #[test]
    fn test_append_command() {
        let (store, mut engine) = setup_test_env();
        engine.set_append_meta(&json!({"base": "meta"}));
        engine
            .add_commands(vec![Box::new(
                commands::append_command::AppendCommand::new(store.clone()),
            )])
            .unwrap();

        // Test piping a basic string to .append
        let frame = nu_eval(
            &engine,
            PipelineData::empty(),
            r#""test content" | .append topic"#,
        );
        let frame = value_to_frame(frame);
        assert_eq!(frame.topic, "topic");
        assert_eq!(frame.meta.unwrap(), json!({"base": "meta"}));
        let content = store.cas_read_sync(&frame.hash.unwrap()).unwrap();
        assert_eq!(String::from_utf8(content).unwrap(), "test content");

        // Test piping a record to .append
        let frame = nu_eval(
            &engine,
            PipelineData::empty(),
            r#"{data: 123} | .append arecord"#,
        );
        let frame = value_to_frame(frame);
        assert_eq!(frame.topic, "arecord");
        assert_eq!(frame.meta.unwrap(), json!({"base": "meta"}));
        let content = store.cas_read_sync(&frame.hash.unwrap()).unwrap();
        // The content should be the JSON representation of our record
        let expected_json = serde_json::json!({"data": 123});
        assert_eq!(
            serde_json::from_slice::<serde_json::Value>(&content).unwrap(),
            expected_json
        );

        // Test custom meta is merged correctly
        let frame = nu_eval(
            &engine,
            PipelineData::empty(),
            r#".append custom-meta --meta {foo: "bar"}"#,
        );
        let frame = value_to_frame(frame);
        assert_eq!(frame.topic, "custom-meta");
        assert_eq!(frame.meta.unwrap(), json!({"base": "meta", "foo": "bar"}));
        assert!(frame.hash.is_none());
    }

    // `.append` takes its base metadata from the `XS_APPEND_META` env var at run
    // time, so the decl is instance-independent and a prepared engine can be
    // cloned per runner.
    #[test]
    fn test_append_meta_from_env() {
        // A value inherited from the process must not reach the engine: only
        // set_append_meta sets it. Any other engine built while this is set
        // strips it too, so no test observes it.
        std::env::set_var(
            commands::append_command::APPEND_META_ENV,
            r#"{"service_id":"leaked"}"#,
        );
        let (store, mut engine) = setup_test_env();
        std::env::remove_var(commands::append_command::APPEND_META_ENV);
        engine
            .add_commands(vec![Box::new(
                commands::append_command::AppendCommand::new(store.clone()),
            )])
            .unwrap();

        // No env, no --meta: base is an empty object.
        let frame = value_to_frame(nu_eval(&engine, PipelineData::empty(), r#".append a"#));
        assert_eq!(frame.meta.unwrap(), json!({}));

        // Base comes from $env.XS_APPEND_META, read at run time.
        let frame = value_to_frame(nu_eval(
            &engine,
            PipelineData::empty(),
            r#"$env.XS_APPEND_META = '{"service_id": "svc"}'; .append b"#,
        ));
        assert_eq!(frame.meta.unwrap(), json!({"service_id": "svc"}));

        // User --meta merges over the env base.
        let frame = value_to_frame(nu_eval(
            &engine,
            PipelineData::empty(),
            r#"$env.XS_APPEND_META = '{"service_id": "svc"}'; .append c --meta {k: 1}"#,
        ));
        assert_eq!(frame.meta.unwrap(), json!({"service_id": "svc", "k": 1}));
    }

    #[test]
    fn test_cas_command_string() {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::cas_command::CasCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let hash = store.cas_insert_sync("test content").unwrap();

        let value = nu_eval(&engine, PipelineData::empty(), format!(".cas {hash}"));

        let content = value.as_str().unwrap();
        assert_eq!(content, "test content");
    }

    #[test]
    fn test_cas_command_binary() {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::cas_command::CasCommand::new(
                store.clone(),
            ))])
            .unwrap();

        // Test binary data retrieval
        let binary_data = vec![0, 159, 146, 150]; // Non-UTF8 bytes
        let hash = store.cas_insert_sync(&binary_data).unwrap();

        let value = nu_eval(&engine, PipelineData::empty(), format!(".cas {hash}"));

        // The value should be returned as binary
        assert!(matches!(value, Value::Binary { .. }));
        let retrieved_data = value.as_binary().unwrap();
        assert_eq!(retrieved_data, &binary_data);
    }

    #[test]
    fn test_last_command() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let _frame1 = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content1")?)
                    .build(),
            )
            .unwrap();

        let frame2 = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content2")?)
                    .build(),
            )
            .unwrap();

        let last_frame = nu_eval(&engine, PipelineData::empty(), ".last topic");

        assert_eq!(
            last_frame.get_data_by_key("id").unwrap().as_str().unwrap(),
            frame2.id.to_string()
        );
        Ok(())
    }

    #[test]
    fn test_last_command_no_topic() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let _frame1 = store
            .append(
                Frame::builder("topic_a")
                    .hash(store.cas_insert_sync("content1")?)
                    .build(),
            )
            .unwrap();

        let frame2 = store
            .append(
                Frame::builder("topic_b")
                    .hash(store.cas_insert_sync("content2")?)
                    .build(),
            )
            .unwrap();

        // .last with no topic returns last frame across all topics
        let last_frame = nu_eval(&engine, PipelineData::empty(), ".last");

        assert_eq!(
            last_frame.get_data_by_key("id").unwrap().as_str().unwrap(),
            frame2.id.to_string()
        );
        Ok(())
    }

    #[test]
    fn test_last_command_count() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let frame1 = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content1")?)
                    .build(),
            )
            .unwrap();

        let frame2 = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content2")?)
                    .build(),
            )
            .unwrap();

        let frame3 = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content3")?)
                    .build(),
            )
            .unwrap();

        // .last 2 returns last 2 frames in chronological order
        let result = nu_eval(&engine, PipelineData::empty(), ".last 2");
        let frames = result.as_list().unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(
            frames[0].get_data_by_key("id").unwrap().as_str().unwrap(),
            frame2.id.to_string()
        );
        assert_eq!(
            frames[1].get_data_by_key("id").unwrap().as_str().unwrap(),
            frame3.id.to_string()
        );

        // .last 1 returns single value (not list)
        let result = nu_eval(&engine, PipelineData::empty(), ".last 1");
        assert_eq!(
            result.get_data_by_key("id").unwrap().as_str().unwrap(),
            frame3.id.to_string()
        );

        // .last 10 with only 3 frames returns all 3
        let result = nu_eval(&engine, PipelineData::empty(), ".last 10");
        let frames = result.as_list().unwrap();
        assert_eq!(frames.len(), 3);
        assert_eq!(
            frames[0].get_data_by_key("id").unwrap().as_str().unwrap(),
            frame1.id.to_string()
        );

        Ok(())
    }

    #[test]
    fn test_last_command_topic_with_count() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        // Add frames to different topics
        let _other = store
            .append(
                Frame::builder("other")
                    .hash(store.cas_insert_sync("other")?)
                    .build(),
            )
            .unwrap();

        let frame1 = store
            .append(
                Frame::builder("target")
                    .hash(store.cas_insert_sync("content1")?)
                    .build(),
            )
            .unwrap();

        let frame2 = store
            .append(
                Frame::builder("target")
                    .hash(store.cas_insert_sync("content2")?)
                    .build(),
            )
            .unwrap();

        // .last target 2 returns last 2 frames for "target" topic only
        let result = nu_eval(&engine, PipelineData::empty(), ".last target 2");
        let frames = result.as_list().unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(
            frames[0].get_data_by_key("id").unwrap().as_str().unwrap(),
            frame1.id.to_string()
        );
        assert_eq!(
            frames[1].get_data_by_key("id").unwrap().as_str().unwrap(),
            frame2.id.to_string()
        );

        Ok(())
    }

    #[test]
    fn test_cat_command() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::cat_command::CatCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let _frame1 = store
            .append(
                Frame::builder("topic1")
                    .hash(store.cas_insert_sync("content1")?)
                    .build(),
            )
            .unwrap();

        let _frame2 = store
            .append(
                Frame::builder("topic2")
                    .hash(store.cas_insert_sync("content2")?)
                    .build(),
            )
            .unwrap();

        // Test basic .cat
        let value = nu_eval(&engine, PipelineData::empty(), ".cat");
        let frames = value.as_list().unwrap();
        assert_eq!(frames.len(), 2);

        // Test .cat with limit - try with quotes
        let value = nu_eval(&engine, PipelineData::empty(), ".cat --limit 1");
        let frames = value.as_list().unwrap();
        assert_eq!(frames.len(), 1);

        // Test .cat with topic filter
        let value = nu_eval(&engine, PipelineData::empty(), ".cat --topic topic2");
        let frames = value.as_list().unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(
            frames[0]
                .get_data_by_key("topic")
                .unwrap()
                .as_str()
                .unwrap(),
            "topic2"
        );

        Ok(())
    }

    #[test]
    fn test_remove_command() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(
                commands::remove_command::RemoveCommand::new(store.clone()),
            )])
            .unwrap();

        let frame = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("test")?)
                    .build(),
            )
            .unwrap();

        nu_eval(
            &engine,
            PipelineData::empty(),
            format!(".remove {}", frame.id),
        );

        assert!(store.get(&frame.id).is_none());
        Ok(())
    }

    #[test]
    fn test_get_command() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::get_command::GetCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let frame = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("test")?)
                    .build(),
            )
            .unwrap();

        let retrieved_frame = nu_eval(&engine, PipelineData::empty(), format!(".get {}", frame.id));

        assert_eq!(
            retrieved_frame
                .get_data_by_key("id")
                .unwrap()
                .as_str()
                .unwrap(),
            frame.id.to_string()
        );

        Ok(())
    }

    #[test]
    fn test_scru128_generate() {
        let engine = setup_scru128_test_env();
        let id_value = nu_eval(&engine, PipelineData::empty(), ".id");

        let id_string = id_value.as_str().unwrap();
        assert!(id_string.len() > 20); // SCRU128 IDs are 25 characters
        assert!(scru128::Scru128Id::from_str(id_string).is_ok()); // Verify it's a valid SCRU128 ID
    }

    #[test]
    fn test_scru128_unpack() {
        let engine = setup_scru128_test_env();
        let test_id = "03d4q1qhbiv09ovtuhokw5yxv";
        let unpacked = nu_eval(
            &engine,
            PipelineData::empty(),
            format!(".id unpack {}", test_id),
        );

        assert!(unpacked.as_record().is_ok());
        let record = unpacked.as_record().unwrap();

        // Verify expected fields are present
        assert!(record.get("ts_ms").is_some());
        assert!(record.get("when").is_some());
        assert!(record.get("counter_hi").is_some());
        assert!(record.get("counter_lo").is_some());
        assert!(record.get("node").is_some());

        // ts_ms is the authoritative integer millisecond timestamp.
        assert!(record.get("ts_ms").unwrap().as_int().is_ok());
        // when is a display-only datetime derived from ts_ms.
        assert!(record.get("when").unwrap().as_date().is_ok());
    }

    #[test]
    fn test_scru128_unpack_when_matches_ts_ms() {
        let engine = setup_scru128_test_env();
        let test_id = "03d4q1qhbiv09ovtuhokw5yxv";
        let unpacked = nu_eval(
            &engine,
            PipelineData::empty(),
            format!(".id unpack {}", test_id),
        );
        let record = unpacked.as_record().unwrap();

        // The display-only when field must read back the same instant as the
        // authoritative ts_ms, so a future change cannot silently drop or skew
        // the human-readable view.
        let ts_ms = record.get("ts_ms").unwrap().as_int().unwrap();
        let when = record.get("when").unwrap().as_date().unwrap();
        assert_eq!(ts_ms, when.timestamp_millis());
    }

    #[test]
    fn test_scru128_unpack_pipeline() {
        let engine = setup_scru128_test_env();
        let test_id = "03d4q1qhbiv09ovtuhokw5yxv";
        let unpacked = nu_eval(
            &engine,
            PipelineData::empty(),
            format!("\"{}\" | .id unpack", test_id),
        );

        assert!(unpacked.as_record().is_ok());
        let record = unpacked.as_record().unwrap();

        // The pipeline form emits the same record as the row form: ts_ms is the
        // authoritative integer millisecond timestamp, when is the display-only
        // datetime derived from it.
        assert!(record.get("ts_ms").unwrap().as_int().is_ok());
        assert!(record.get("when").unwrap().as_date().is_ok());
        assert!(record.get("counter_hi").is_some());
        assert!(record.get("counter_lo").is_some());
        assert!(record.get("node").is_some());
    }

    #[test]
    fn test_scru128_pack() {
        let engine = setup_scru128_test_env();
        let components =
            r#"{ts_ms: 1700000000000, counter_hi: 1234, counter_lo: 5678, node: "abcd1234"}"#;
        let packed = nu_eval(
            &engine,
            PipelineData::empty(),
            format!(".id pack {}", components),
        );

        let id_string = packed.as_str().unwrap();
        assert!(id_string.len() > 20); // SCRU128 IDs are 25 characters
        assert!(scru128::Scru128Id::from_str(id_string).is_ok()); // Verify it's a valid SCRU128 ID
    }

    #[test]
    fn test_scru128_pack_pipeline() {
        let engine = setup_scru128_test_env();
        // when is display-only; pack must ignore it and use ts_ms.
        let components = r#"{ts_ms: 1700000000000, when: (date now), counter_hi: 1234, counter_lo: 5678, node: "abcd1234"}"#;
        let packed = nu_eval(
            &engine,
            PipelineData::empty(),
            format!("{} | .id pack", components),
        );

        let id_string = packed.as_str().unwrap();
        assert!(id_string.len() > 20); // SCRU128 IDs are 25 characters
        assert!(scru128::Scru128Id::from_str(id_string).is_ok()); // Verify it's a valid SCRU128 ID
    }

    fn assert_id_roundtrips(engine: &crate::nu::Engine, id: &str) {
        let unpacked = nu_eval(
            engine,
            PipelineData::empty(),
            format!("\"{}\" | .id unpack", id),
        );
        let repacked = nu_eval(engine, PipelineData::Value(unpacked, None), ".id pack");
        assert_eq!(
            id,
            repacked.as_str().unwrap(),
            "roundtrip mismatch for {id}"
        );
    }

    #[test]
    fn test_scru128_round_trip() {
        let engine = setup_scru128_test_env();

        // Pinned ids that lost 1ms of timestamp before the round fix. The
        // unpack seconds -> datetime -> pack path truncated milliseconds
        // instead of rounding, so ids whose f64 ms landed just below an
        // integer dropped a millisecond and repacked to a different id.
        for id in [
            "03gmmrhqljv8bnulus79wipck",
            "03gmmrhqzjzlbz75e1r8fyvmt",
            "03gmmrhsh0x17va0knqvbhly6",
        ] {
            assert_id_roundtrips(&engine, id);
        }

        // Deterministic sweep: every fresh id must roundtrip exactly. Before
        // the fix this failed on roughly 3% of ids, so 2000 makes a failure
        // essentially certain rather than a ~1-in-35 flake.
        for _ in 0..2000 {
            let id = nu_eval(&engine, PipelineData::empty(), ".id");
            assert_id_roundtrips(&engine, id.as_str().unwrap());
        }
    }

    /// `.id unpack $id` takes its id as an argument, so its pipeline input
    /// is nothing. Nu picks an output type at parse time from the input type
    /// alone, so the type declared for a nothing input decides what it allows
    /// downstream. A wrong one rejects field access before the command runs.
    #[test]
    fn test_scru128_unpack_argument_form_parses_as_a_record() {
        let engine = setup_scru128_test_env();
        let id = nu_eval(&engine, PipelineData::empty(), ".id");
        let id = id.as_str().unwrap();

        // Binding the id to a variable first is what exposes it: with a
        // literal, nu infers a type for the whole expression instead.
        let ts = nu_eval(
            &engine,
            PipelineData::empty(),
            format!("let id = \"{id}\"; .id unpack $id | get ts_ms"),
        );
        assert!(ts.as_int().is_ok(), "ts_ms was {ts:?}");

        // pack goes the other way, and has the same shape.
        let packed = nu_eval(
            &engine,
            PipelineData::empty(),
            format!("let r = (\"{id}\" | .id unpack); .id pack $r"),
        );
        assert_eq!(packed.as_str().unwrap(), id);
    }

    #[test]
    fn test_scru128_invalid_id() {
        let engine = setup_scru128_test_env();

        let engine_clone = engine.clone();
        let result = std::thread::spawn(move || {
            engine_clone.eval(PipelineData::empty(), ".id unpack invalid_id".to_string())
        })
        .join();

        assert!(result.is_ok());
        assert!(result.unwrap().is_err());
    }

    #[test]
    fn test_last_command_with_timestamp() -> Result<(), Error> {
        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let frame = store
            .append(
                Frame::builder("topic")
                    .hash(store.cas_insert_sync("content")?)
                    .build(),
            )
            .unwrap();

        // Without --with-timestamp, no timestamp field
        let result = nu_eval(&engine, PipelineData::empty(), ".last topic");
        assert!(result.get_data_by_key("timestamp").is_none());

        // With --with-timestamp, timestamp field is a datetime
        let result = nu_eval(
            &engine,
            PipelineData::empty(),
            ".last topic --with-timestamp",
        );
        let timestamp = result.get_data_by_key("timestamp");
        assert!(timestamp.is_some());
        assert!(timestamp.unwrap().as_date().is_ok());

        // Verify frame id still matches
        assert_eq!(
            result.get_data_by_key("id").unwrap().as_str().unwrap(),
            frame.id.to_string()
        );

        Ok(())
    }

    // Regression test for the per-frame ThreadJob leak: run_closure_in_job
    // registered a job in the engine's jobs table on every call and never
    // removed it. The actor hot loop now attaches one long-lived job and
    // evaluates frames with eval_closure_no_job; the table must not grow
    // with call count.
    #[test]
    fn test_eval_closure_no_job_does_not_grow_jobs_table() {
        let (_store, mut engine) = setup_test_env();
        let closure = engine.parse_closure("{|x, state| $x}").unwrap();
        engine.attach_background_job("test-actor");

        let baseline = engine.state.jobs.lock().unwrap().iter().count();
        assert_eq!(baseline, 1);

        for i in 0..100 {
            let result = engine
                .eval_closure_no_job(
                    &closure,
                    vec![
                        Value::int(i, Span::test_data()),
                        Value::nothing(Span::test_data()),
                    ],
                    None,
                )
                .unwrap()
                .into_value(Span::test_data())
                .unwrap();
            assert_eq!(result, Value::int(i, Span::test_data()));
        }

        let after = engine.state.jobs.lock().unwrap().iter().count();
        assert_eq!(after, baseline);
    }

    // Count this process's open file descriptors via /proc/self/fd.
    // Linux-only; the fd-leak repro below is gated on the same.
    #[cfg(target_os = "linux")]
    fn open_fd_count() -> usize {
        std::fs::read_dir("/proc/self/fd")
            .expect("read /proc/self/fd")
            .count()
    }

    // Reproduce the file-descriptor leak in `.cat` (CatCommand).
    //
    // (Pre-L1 mechanism, retained for context:) each `.cat` run spawned an OS
    // thread that built a fresh `tokio::runtime::Runtime` and called
    // `rt.block_on` on a loop that reads from the store and forwards frames to
    // the ListStream. A tokio runtime owns an eventfd (anon_inode) + a wakeup
    // socket. That runtime is only dropped when the block_on future returns,
    // which requires the forwarding loop to exit.
    //
    // A following read has to notice interruption. Its iterator parks
    // waiting for the next frame on the topic, and on an idle topic that wait
    // has no end. http-nu gives each request its own `Signals` and triggers
    // them when the client disconnects, so without this the thread and the
    // store's follow task stay parked until some unrelated append happens to
    // land on that topic.
    #[test]
    fn test_cat_follow_stops_when_interrupted() {
        use crate::nu::commands;
        use nu_protocol::Signals;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::Duration;

        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::cat_command::CatCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let flag = Arc::new(AtomicBool::new(false));
        engine.state.set_signals(Signals::new(flag.clone()));

        // Nothing is ever appended to this topic, so the only way out of the
        // follow is the signal.
        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let engine_clone = engine.clone();
        std::thread::spawn(move || {
            let out = engine_clone.eval(PipelineData::empty(), ".cat -f -T idle".to_string());
            let drained = out.map(|d| d.into_iter().count());
            let _ = done_tx.send(drained.is_ok());
        });

        // Let it reach the park before interrupting.
        std::thread::sleep(Duration::from_millis(200));
        flag.store(true, Ordering::SeqCst);

        let finished = done_rx.recv_timeout(Duration::from_secs(5));
        assert!(
            finished.is_ok(),
            "a following read ignored its interrupt and stayed parked",
        );
    }

    // `.last -f` has the same follow branch and the same wait.
    #[test]
    fn test_last_follow_stops_when_interrupted() {
        use crate::nu::commands;
        use nu_protocol::Signals;
        use std::sync::atomic::{AtomicBool, Ordering};
        use std::sync::Arc;
        use std::time::Duration;

        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![Box::new(commands::last_command::LastCommand::new(
                store.clone(),
            ))])
            .unwrap();

        let flag = Arc::new(AtomicBool::new(false));
        engine.state.set_signals(Signals::new(flag.clone()));

        let (done_tx, done_rx) = std::sync::mpsc::channel();
        let engine_clone = engine.clone();
        std::thread::spawn(move || {
            let out = engine_clone.eval(PipelineData::empty(), ".last idle -f".to_string());
            // Assert on the count, not just that the thread ended: a bad
            // invocation would error out at once and pass vacuously.
            let _ = done_tx.send(out.map(|d| d.into_iter().count()));
        });

        std::thread::sleep(Duration::from_millis(200));
        flag.store(true, Ordering::SeqCst);

        let finished = done_rx
            .recv_timeout(Duration::from_secs(5))
            .expect("a following read ignored its interrupt and stayed parked");
        assert!(finished.is_ok(), ".last -f failed to run: {finished:?}");
    }

    // In `--follow` mode the store's read() future parks on the broadcast
    // receiver waiting for the next append. When the ListStream consumer is
    // dropped (client disconnects, pipeline ends early), the spawned thread is
    // still blocked inside `receiver.recv().await` and never observes that the
    // std mpsc `tx` is now disconnected: std mpsc only reports Disconnected on
    // the *next* send attempt, and no send happens while parked. So the thread
    // -- and its runtime, eventfd, and socket -- leak for the life of the
    // process. One socket+eventfd pair per `.cat --follow` invocation, matching
    // the production evidence (EMFILE, growing socket/anon_inode pairs).
    //
    // This test drives `.cat --follow` through the real nushell engine, takes
    // the historical frame, then drops the stream -- exactly the "consumer went
    // away while the follower is parked" case -- and asserts the process fd
    // count stays bounded. Against current code it grows ~linearly with N.
    // Runs the real measurement in its OWN process (the `fd_leak_worker` below,
    // spawned here). `cargo test` runs tests concurrently and file descriptors
    // are a process-wide resource, so an in-suite measurement of /proc/self/fd
    // races unrelated tests opening their own fds. Isolating it in a fresh
    // process makes the count reflect only the `.cat` read path.
    #[cfg(target_os = "linux")]
    #[test]
    fn test_cat_stream_fd_leak() {
        let exe = std::env::current_exe().expect("current_exe");
        let output = std::process::Command::new(exe)
            .args([
                "--exact",
                "--ignored",
                "--nocapture",
                "--test-threads=1",
                "nu::test_commands::tests::fd_leak_worker",
            ])
            .output()
            .expect("spawn isolated fd-leak worker");
        assert!(
            output.status.success(),
            "isolated fd-leak worker failed:\n--- stdout ---\n{}\n--- stderr ---\n{}",
            String::from_utf8_lossy(&output.stdout),
            String::from_utf8_lossy(&output.stderr),
        );
    }

    // The isolated worker, spawned as its own process by `test_cat_stream_fd_leak`
    // (hence `#[ignore]` -- it must not run in the normal parallel pass). Alone in
    // the process, its /proc/self/fd count reflects only the read path.
    #[cfg(target_os = "linux")]
    #[test]
    #[ignore = "spawned in isolation by test_cat_stream_fd_leak"]
    fn fd_leak_worker() {
        use crate::nu::commands;
        use crate::store::TTL;

        let (store, mut engine) = setup_test_env();
        engine
            .add_commands(vec![
                Box::new(commands::cat_command::CatCommand::new(store.clone())),
                Box::new(commands::append_command::AppendCommand::new(store.clone())),
            ])
            .unwrap();

        // One historical frame so `.cat --follow` has something to emit before
        // it parks on the broadcast receiver.
        store
            .append(Frame::builder("seed").ttl(TTL::Forever).build())
            .unwrap();

        // Warm up: the first couple of runs allocate some steady-state fds
        // (thread-locals, lazy statics) that are not a leak. Measure after.
        let warmup = 3usize;
        let iterations = 50usize;

        let run_once = |engine: &Engine| {
            // `.cat --follow` yields the historical frame then parks. Take the
            // first value to prove the path ran, then drop the stream while the
            // follower thread is still parked on the broadcast receiver.
            let engine = engine.clone();
            std::thread::spawn(move || {
                let pipeline = engine
                    .eval(PipelineData::empty(), ".cat --follow".to_string())
                    .unwrap();
                let mut iter = pipeline.into_iter();
                let first = iter.next();
                assert!(first.is_some(), "expected the seeded historical frame");
                // Drop `iter` (and its ListStream) here: consumer goes away.
            })
            .join()
            .unwrap();
        };

        for _ in 0..warmup {
            run_once(&engine);
        }
        std::thread::sleep(std::time::Duration::from_millis(100));
        let before = open_fd_count();

        for _ in 0..iterations {
            run_once(&engine);
        }

        // Follow-task cleanup is asynchronous (cancelled via `tx.closed()` on the
        // shared runtime). In this isolated, otherwise-idle process there is no
        // concurrent fd churn, so a brief settle converges; a real leak does not.
        std::thread::sleep(std::time::Duration::from_millis(500));
        let after = open_fd_count();

        let growth = after.saturating_sub(before);
        eprintln!(
            "fd count before={before} after={after} growth={growth} over {iterations} iterations"
        );

        // A correct implementation reuses/drops the runtime, so fd count stays
        // flat. Small slack for allocator/thread-pool noise. The old leak added
        // ~2 fds (socket + eventfd) per iteration, far above the slack.
        let slack = 8;
        assert!(
            growth <= slack,
            "file descriptor leak: fd count grew by {growth} over {iterations} \
             `.cat --follow` runs (before={before}, after={after}); expected <= \
             {slack}. A leaked runtime holds a socket + eventfd pair (pre-L1 mechanism)."
        );
    }
}