rustsim-crowd 0.0.1

Microscopic crowd and pedestrian locomotion for rustsim: 2-D and layered 3-D, with Social Force, Collision-Free Speed, Generalized Centrifugal Force, Optimal Steps, and Anticipation Velocity models
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
//! Long-run stability tests for the crowd hot path.
//!
//! Closes the P0 "soak / long-run stability" item from
//! `docs/rustsim-crowd.md`. Exercises every prior blocker fix in
//! concert (broadphase, zero-alloc `Scratch`, `arrival_radius` taper,
//! `max_accel` cap + CFL validation, SoA-ready `CrowdAgent` layout)
//! under sustained load and asserts the invariants that matter for a
//! production deployment:
//!
//! - population is conserved across every tick;
//! - no pedestrian's position or velocity ever becomes NaN or Inf;
//! - per-agent speed stays bounded by `max_speed * 1.5` (the 1.5×
//!   margin catches a single-tick clamp-slip without masking a real
//!   runaway).
//!
//! The `Scratch` zero-growth property is already pinned by the
//! internal `broadphase::tests::scratch_reuses_capacity_across_ticks`
//! unit test against `pub(crate)` fields and is not re-asserted here.
//!
//! Two tests share one seeding helper:
//!
//! - `social_force_soak_mid_scale` (**unconditional**, ~seconds) —
//!   2 000 agents × 600 ticks = 30 s simulated at dt = 0.05 s. Sized to
//!   fit the workspace's default CI lane so every PR picks up stability
//!   regressions. Mirrors the mid-scale soak budgets in
//!   `rustsim-core/tests/soak_scale_tests.rs`.
//! - `social_force_soak_10k_one_hour` (**`#[ignore]`**, ~minutes) — the
//!   full 10 000 agents × 72 000 ticks = 1 h simulated. Runs opt-in in
//!   the workspace soak lane per `docs/soak-scale-testing.md`:
//!   `cargo test -p rustsim-crowd --test soak_scale --release -- --ignored --nocapture`.

use rand::rngs::StdRng;
use rand::{Rng, SeedableRng};
use rustsim_crowd::{
    anticipation_velocity,
    broadphase::{recommended_cell_size, Scratch},
    collision_free_speed,
    common::{Pedestrian, WallSegment},
    generalized_centrifugal_force, optimal_steps, social_force,
};
use std::time::Instant;

/// Seed `n` pedestrians in a periodic rectangular corridor at uniform
/// random positions with deterministic counter-flow intent (half +x,
/// half -x). Returns the pedestrian vector.
fn seed_counterflow(n: usize, length: f64, width: f64, seed: u64) -> Vec<Pedestrian> {
    let mut rng = StdRng::seed_from_u64(seed);
    (0..n)
        .map(|i| {
            let x: f64 = rng.gen_range(0.0..length);
            let y: f64 = rng.gen_range(0.0..width);
            let dir = if i % 2 == 0 { 1.0 } else { -1.0 };
            // Destination is well outside the domain on the intended
            // side so the driving force stays pointed along ±x even
            // though the corridor is periodic.
            let dest_x = x + dir * 10.0 * length;
            Pedestrian::new([x, y], [0.0, 0.0], 0.25, 1.34, [dest_x, y])
        })
        .collect()
}

/// Wrap each pedestrian back into `[0, length) × [0, width)` without
/// disturbing velocity; re-anchor the destination so the driving-force
/// direction survives the periodic seam.
fn wrap_and_retarget(peds: &mut [Pedestrian], length: f64, width: f64) {
    for p in peds.iter_mut() {
        if p.pos[0] < 0.0 {
            p.pos[0] += length;
            p.destination[0] += length;
        } else if p.pos[0] >= length {
            p.pos[0] -= length;
            p.destination[0] -= length;
        }
        if p.pos[1] < 0.0 {
            p.pos[1] = 0.0;
            p.vel[1] = 0.0;
        } else if p.pos[1] >= width {
            p.pos[1] = width;
            p.vel[1] = 0.0;
        }
    }
}

/// Run the shared invariant assertions after every tick.
#[inline]
fn assert_invariants(peds: &[Pedestrian], n: usize, speed_cap: f64, tick: usize) {
    assert_eq!(peds.len(), n, "population not conserved at tick {tick}");
    for (i, p) in peds.iter().enumerate() {
        assert!(
            p.pos[0].is_finite() && p.pos[1].is_finite(),
            "non-finite position at tick {tick}, agent {i}: {:?}",
            p.pos
        );
        assert!(
            p.vel[0].is_finite() && p.vel[1].is_finite(),
            "non-finite velocity at tick {tick}, agent {i}: {:?}",
            p.vel
        );
        let speed = (p.vel[0] * p.vel[0] + p.vel[1] * p.vel[1]).sqrt();
        assert!(
            speed <= speed_cap,
            "speed {speed} exceeds cap {speed_cap} at tick {tick}, agent {i}"
        );
    }
}

#[test]
fn social_force_soak_mid_scale() {
    const N: usize = 2_000;
    const LENGTH: f64 = 80.0;
    const WIDTH: f64 = 20.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = social_force::Params::default();
    params
        .validate(DT)
        .expect("default SFM params must validate at dt = 0.05 s");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xC0FFEE);
    let cutoff = social_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        social_force::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        assert_invariants(&peds, N, speed_cap, tick);
    }
    let elapsed_ms = t0.elapsed().as_millis();

    eprintln!(
        "[crowd soak] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

#[test]
#[ignore = "long-running soak test; run with --ignored in the workspace soak lane"]
fn social_force_soak_10k_one_hour() {
    const N: usize = 10_000;
    const LENGTH: f64 = 200.0;
    const WIDTH: f64 = 50.0;
    const DT: f64 = 0.05;
    // 1 hour simulated at dt = 0.05 s = 72 000 ticks.
    const NUM_TICKS: usize = 72_000;

    let params = social_force::Params::default();
    params.validate(DT).expect("params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xDEADBEEF);
    let cutoff = social_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        social_force::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        // Invariants every tick would slow the soak by ~10%; check
        // every 200 ticks (10 s simulated) in the long run.
        if tick % 200 == 0 {
            assert_invariants(&peds, N, speed_cap, tick);
        }
    }
    assert_invariants(&peds, N, speed_cap, NUM_TICKS);
    let elapsed_ms = t0.elapsed().as_millis();

    eprintln!(
        "[crowd soak 10k/1h] {N} agents x {NUM_TICKS} ticks (3600 s simulated) completed in {elapsed_ms} ms"
    );
}

// ---------------------------------------------------------------------------
// Mid-scale soaks for the remaining four models.
//
// Each test mirrors the SFM mid-scale shape (2 000 agents × periodic
// counter-flow corridor × 600 ticks, default-`Params`, default seed)
// and asserts the same population / finiteness / speed-cap invariants.
// Together with `social_force_soak_mid_scale` they cover the full
// `rustsim-crowd` model surface on every PR.
//
// First-order kinematic models (CFS, AVM, OSM) have no `Params::max_speed`;
// the per-pedestrian `desired_speed` (1.34 m/s in `seed_counterflow`) is
// the bound. We use `1.34 * 1.5 = 2.01` m/s as the soak cap to leave
// the same 50 % margin SFM uses, catching a single-tick clamp-slip
// without masking a real runaway.
// ---------------------------------------------------------------------------

const KINEMATIC_SPEED_CAP: f64 = 1.34 * 1.5;

#[test]
fn collision_free_speed_soak_mid_scale() {
    const N: usize = 2_000;
    const LENGTH: f64 = 80.0;
    const WIDTH: f64 = 20.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = collision_free_speed::Params::default();
    params
        .validate(DT)
        .expect("default CFS params must validate at dt = 0.05 s");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xCF5_0001);
    let cutoff = collision_free_speed::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        collision_free_speed::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak CFS] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

#[test]
fn anticipation_velocity_soak_mid_scale() {
    const N: usize = 2_000;
    const LENGTH: f64 = 80.0;
    const WIDTH: f64 = 20.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = anticipation_velocity::Params::default();
    params
        .validate(DT)
        .expect("default AVM params must validate at dt = 0.05 s");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xA_0001);
    let cutoff = anticipation_velocity::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        anticipation_velocity::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak AVM] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

#[test]
fn generalized_centrifugal_force_soak_mid_scale() {
    const N: usize = 2_000;
    const LENGTH: f64 = 80.0;
    const WIDTH: f64 = 20.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = generalized_centrifugal_force::Params::default();
    params
        .validate(DT)
        .expect("default GCF params must validate at dt = 0.05 s");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0x6CF_0001);
    let cutoff = generalized_centrifugal_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    // GCF is force-based and respects its own `Params::max_speed`.
    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        generalized_centrifugal_force::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        assert_invariants(&peds, N, speed_cap, tick);
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak GCF] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

#[test]
fn optimal_steps_soak_mid_scale() {
    // OSM is a discrete-step model: `dt` is the duration of one step,
    // not a sub-second integrator slice. The model's existing tests
    // use 0.4 s steps; we match that here so the soak exercises the
    // model at its intended cadence. 600 steps × 0.4 s = 240 s
    // simulated, comparable to the other mid-scale soaks.
    const N: usize = 2_000;
    const LENGTH: f64 = 80.0;
    const WIDTH: f64 = 20.0;
    const DT: f64 = 0.4;
    const NUM_STEPS: usize = 600;

    let params = optimal_steps::Params::default();
    params
        .validate(DT)
        .expect("default OSM params must validate at dt = 0.4 s");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0x05_0001);
    let cutoff = optimal_steps::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    // OSM derives velocity from the chosen step (`(new_pos - old_pos) / dt`)
    // and never clamps; bound stays at the seeded `desired_speed * 1.5`.
    let t0 = Instant::now();
    for tick in 0..NUM_STEPS {
        optimal_steps::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak OSM] {N} agents x {NUM_STEPS} steps ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_STEPS as f64 * DT
    );
}

// ---------------------------------------------------------------------------
// Long-run (1-hour simulated) soaks for the remaining four 2-D models.
//
// Mirror the SFM `social_force_soak_10k_one_hour` discipline so every
// 2-D model surfaces sustained-load instabilities (NaN propagation,
// runaway clamp-slip, capacity drift) under the workspace soak lane.
// All `#[ignore]`-gated; opt in with
//   cargo test -p rustsim-crowd --test soak_scale --release -- --ignored --nocapture
// Invariants are checked every 200 ticks (every 80 s for OSM at 0.4 s
// step duration) instead of every tick to keep the long-run wall-clock
// proportional to the work, not to the assertion overhead.
// ---------------------------------------------------------------------------

#[test]
#[ignore = "long-running soak test; run with --ignored in the workspace soak lane"]
fn collision_free_speed_soak_10k_one_hour() {
    const N: usize = 10_000;
    const LENGTH: f64 = 200.0;
    const WIDTH: f64 = 50.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 72_000;

    let params = collision_free_speed::Params::default();
    params.validate(DT).expect("CFS params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xCF5_BEEF);
    let cutoff = collision_free_speed::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        collision_free_speed::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        if tick % 200 == 0 {
            assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
        }
    }
    assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, NUM_TICKS);
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak CFS 10k/1h] {N} agents x {NUM_TICKS} ticks (3600 s simulated) completed in {elapsed_ms} ms"
    );
}

#[test]
#[ignore = "long-running soak test; run with --ignored in the workspace soak lane"]
fn anticipation_velocity_soak_10k_one_hour() {
    const N: usize = 10_000;
    const LENGTH: f64 = 200.0;
    const WIDTH: f64 = 50.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 72_000;

    let params = anticipation_velocity::Params::default();
    params.validate(DT).expect("AVM params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0xA_BEEF);
    let cutoff = anticipation_velocity::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        anticipation_velocity::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        if tick % 200 == 0 {
            assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
        }
    }
    assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, NUM_TICKS);
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak AVM 10k/1h] {N} agents x {NUM_TICKS} ticks (3600 s simulated) completed in {elapsed_ms} ms"
    );
}

#[test]
#[ignore = "long-running soak test; run with --ignored in the workspace soak lane"]
fn generalized_centrifugal_force_soak_10k_one_hour() {
    const N: usize = 10_000;
    const LENGTH: f64 = 200.0;
    const WIDTH: f64 = 50.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 72_000;

    let params = generalized_centrifugal_force::Params::default();
    params.validate(DT).expect("GCF params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0x6CF_BEEF);
    let cutoff = generalized_centrifugal_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        generalized_centrifugal_force::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        if tick % 200 == 0 {
            assert_invariants(&peds, N, speed_cap, tick);
        }
    }
    assert_invariants(&peds, N, speed_cap, NUM_TICKS);
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak GCF 10k/1h] {N} agents x {NUM_TICKS} ticks (3600 s simulated) completed in {elapsed_ms} ms"
    );
}

#[test]
#[ignore = "long-running soak test; run with --ignored in the workspace soak lane"]
fn optimal_steps_soak_one_hour() {
    // OSM is a discrete-step model at 0.4 s/step. 1 h simulated =
    // 9 000 steps (vs 72 000 for the 0.05 s integrator-based models).
    // Smaller agent count keeps the inner step-utility search bounded.
    const N: usize = 5_000;
    const LENGTH: f64 = 200.0;
    const WIDTH: f64 = 50.0;
    const DT: f64 = 0.4;
    const NUM_STEPS: usize = 9_000;

    let params = optimal_steps::Params::default();
    params.validate(DT).expect("OSM params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds = seed_counterflow(N, LENGTH, WIDTH, 0x05_BEEF);
    let cutoff = optimal_steps::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);

    let t0 = Instant::now();
    for tick in 0..NUM_STEPS {
        optimal_steps::step_scratch(&mut peds, &walls, &params, DT, &mut scratch);
        wrap_and_retarget(&mut peds, LENGTH, WIDTH);
        if tick % 100 == 0 {
            assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, tick);
        }
    }
    assert_invariants(&peds, N, KINEMATIC_SPEED_CAP, NUM_STEPS);
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak OSM 5k/1h] {N} agents x {NUM_STEPS} steps (3600 s simulated) completed in {elapsed_ms} ms"
    );
}

// ---------------------------------------------------------------------------
// Layered 2.5-D soak.
//
// Pins the layered drive (`step_layered_scratch` + `LayeredScratch` +
// boarding/transition state) under sustained load with a non-trivial
// inter-floor traffic pattern. Two floors, one stair connector, half
// the agents bound for the upper floor (`heading_to_floor`) and half
// loitering on the ground floor — exactly the mix that previously
// surfaced the boarding-re-entrance bug pinned by the `target_floor`
// gate. Asserts on every sample tick: population conservation, finite
// (planar) pos/vel, finite z, floor membership ∈ {0, 1}, and that
// every active transition's `remaining` is finite and ≥ 0.
// ---------------------------------------------------------------------------

#[test]
fn layered_soak_mid_scale() {
    use rustsim_crowd::threed::{
        step_layered_scratch, ConnectorKind, FloorTransition, LayeredScratch, LayeredSpace,
        Pedestrian3D,
    };

    const N: usize = 200;
    const HALF_TARGETING_F1: usize = 100;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    // Two floors, one stair.
    let mut space = LayeredSpace::new();
    space.set_floor(0, 0.0);
    space.set_floor(1, 4.0);
    space.connectors.push(FloorTransition {
        id: 1,
        kind: ConnectorKind::Stair,
        from_floor: 0,
        from_pos: [10.0, 0.0],
        to_floor: 1,
        to_pos: [10.0, 0.0],
        boarding_radius: 1.0,
        travel_time: 10.0,
    });

    // Seed: half walk toward the stair with `target_floor = Some(1)`,
    // half loiter on the ground floor (no transition intent).
    let mut peds: Vec<Pedestrian3D> = (0..N)
        .map(|i| {
            let y = (i as f64 - N as f64 / 2.0) * 0.4;
            let base = Pedestrian::new([0.0, y], [0.0, 0.0], 0.25, 1.34, [10.0, y]);
            if i < HALF_TARGETING_F1 {
                Pedestrian3D::heading_to_floor(base, 0, 1)
            } else {
                Pedestrian3D::grounded(base, 0)
            }
        })
        .collect();

    let params = social_force::Params::default();
    params.validate(DT).expect("SFM params must validate");
    let mut scratch = LayeredScratch::with_capacity(N);

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        // The layered drive's `PlanarStepFn` signature is the O(n²)
        // `step` shape; this soak drives it intentionally to exercise
        // the layered + boarding state machine, not raw planar
        // throughput.
        #[allow(deprecated)]
        step_layered_scratch(
            &mut peds,
            &space,
            social_force::step,
            &params,
            DT,
            &mut scratch,
        );
        // Population conservation + floor / pos / vel finiteness.
        assert_eq!(peds.len(), N, "layered population drift at tick {tick}");
        for (i, p) in peds.iter().enumerate() {
            assert!(
                p.base.pos[0].is_finite() && p.base.pos[1].is_finite(),
                "non-finite planar pos at tick {tick}, agent {i}: {:?}",
                p.base.pos
            );
            assert!(
                p.base.vel[0].is_finite() && p.base.vel[1].is_finite(),
                "non-finite planar vel at tick {tick}, agent {i}: {:?}",
                p.base.vel
            );
            assert!(
                p.floor == 0 || p.floor == 1,
                "agent {i} drifted off the layered space (floor = {}) at tick {tick}",
                p.floor
            );
            if let Some(active) = &p.transition {
                assert!(
                    active.remaining.is_finite() && active.remaining >= 0.0,
                    "agent {i} transition remaining={} at tick {tick}",
                    active.remaining
                );
            }
        }
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak layered] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

// ---------------------------------------------------------------------------
// Rayon-parallel multi-core soak.
//
// Pins long-run multi-core stability for the rayon-parallel hot path:
// confirms `step_scratch_par` stays bit-exactly equivalent to the
// serial `step_scratch` over an extended run (drift accumulates), and
// asserts the same population / finiteness / speed-cap invariants. A
// single-tick `rayon_bit_exact` test catches spec drift; this one
// catches a subtle ordering bug that only surfaces after thousands of
// ticks of accumulated divergence.
// ---------------------------------------------------------------------------

#[cfg(feature = "rayon")]
#[test]
fn social_force_rayon_bit_exact_soak() {
    const N: usize = 256;
    const LENGTH: f64 = 40.0;
    const WIDTH: f64 = 10.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 3_000; // 150 s simulated, comfortably above any ordering-divergence threshold.

    let params = social_force::Params::default();
    params.validate(DT).expect("SFM params must validate");

    let walls: Vec<WallSegment> = Vec::new();
    let mut peds_serial = seed_counterflow(N, LENGTH, WIDTH, 0x5AFE);
    let mut peds_par = peds_serial.clone();
    let cutoff = social_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch_serial = Scratch::with_capacity(N, cell);
    let mut scratch_par = Scratch::with_capacity(N, cell);

    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        social_force::step_scratch(&mut peds_serial, &walls, &params, DT, &mut scratch_serial);
        social_force::step_scratch_par(&mut peds_par, &walls, &params, DT, &mut scratch_par);
        wrap_and_retarget(&mut peds_serial, LENGTH, WIDTH);
        wrap_and_retarget(&mut peds_par, LENGTH, WIDTH);
        // Bit-exact equivalence is the long-run gate.
        for (i, (a, b)) in peds_serial.iter().zip(peds_par.iter()).enumerate() {
            assert_eq!(
                a.pos, b.pos,
                "rayon vs serial pos drift at tick {tick}, agent {i}: serial={:?} par={:?}",
                a.pos, b.pos
            );
            assert_eq!(
                a.vel, b.vel,
                "rayon vs serial vel drift at tick {tick}, agent {i}: serial={:?} par={:?}",
                a.vel, b.vel
            );
        }
        // Standard soak invariants on the parallel stream.
        if tick % 100 == 0 {
            assert_invariants(&peds_par, N, speed_cap, tick);
        }
    }
    assert_invariants(&peds_par, N, speed_cap, NUM_TICKS);
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak SFM rayon] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated, bit-exact vs serial) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

// ---------------------------------------------------------------------------
// Integrated-drive soaks.
//
// The five model-level mid-scale soaks above all drive the kernel
// directly against `&mut [Pedestrian]`. Production callers, however,
// route through the `rustsim-core`-integrated drive
// (`step_scratch_store` against `AgentStore<CrowdAgent>`), which adds
// an extract → step → write-back round-trip on every tick. That
// round-trip allocates a per-tick reusable buffer (`buf`) and walks
// `iter_ids()` twice per tick, both of which are exactly the kind of
// thing that can leak / grow / drift over thousands of ticks.
//
// `tests/rayon_bit_exact.rs` covers the 40-tick bit-exact contract;
// these soaks pin the long-run stability of the same path:
//
// - `step_scratch_store_soak_mid_scale` — sustained AgentStore round
//   trip, asserting population conservation across `iter_ids()`,
//   finite pos/vel after every write-back, and per-agent speed
//   bounded by the SFM cap.
// - `crowd_observer_soak_mid_scale` — drives `step_scratch_store_observed`
//   with a counting closure and asserts the observer is called
//   **exactly** `N × NUM_TICKS` times — i.e. once per (tick, agent)
//   with no leak, no double-call, no skipped row across thousands of
//   ticks.
// ---------------------------------------------------------------------------

#[test]
fn step_scratch_store_soak_mid_scale() {
    use rustsim_core::prelude::VecStore;
    use rustsim_core::store::AgentStore;
    use rustsim_crowd::prelude::{step_scratch_store, CrowdAgent, SocialForceModel};

    const N: usize = 1_000;
    const LENGTH: f64 = 60.0;
    const WIDTH: f64 = 15.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = social_force::Params::default();
    params.validate(DT).expect("SFM params must validate");

    let seed_peds = seed_counterflow(N, LENGTH, WIDTH, 0x0570_BEEF);
    let mut store: VecStore<CrowdAgent> = VecStore::new();
    for (i, p) in seed_peds.iter().enumerate() {
        store.insert(CrowdAgent {
            id: i as u64 + 1,
            ped: *p,
        });
    }

    let walls: Vec<WallSegment> = Vec::new();
    let cutoff = social_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);
    let mut buf: Vec<Pedestrian> = Vec::with_capacity(N);
    let model = SocialForceModel;

    let speed_cap = params.max_speed * 1.5;
    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        step_scratch_store(
            &model,
            &mut store,
            &walls,
            &params,
            DT,
            &mut scratch,
            &mut buf,
        );
        // Re-anchor: extract → wrap → write-back, so the long-run
        // soak exercises the same `iter_ids()`-driven round-trip
        // that production callers use to reseat agents after a
        // domain wrap.
        buf.clear();
        for &id in &store.iter_ids() {
            buf.push(store.get(id).expect("id present").ped);
        }
        wrap_and_retarget(&mut buf, LENGTH, WIDTH);
        for (i, &id) in store.iter_ids().iter().enumerate() {
            let mut entry = store.get_mut(id).expect("id present");
            entry.ped = buf[i];
        }

        if tick % 50 == 0 {
            // Population conservation through the store, plus the
            // standard finiteness + speed-cap invariants on the
            // post-tick rows.
            let ids = store.iter_ids();
            assert_eq!(
                ids.len(),
                N,
                "store population drift at tick {tick}: {} != {N}",
                ids.len()
            );
            for &id in &ids {
                let p = store.get(id).expect("id present").ped;
                assert!(
                    p.pos[0].is_finite() && p.pos[1].is_finite(),
                    "non-finite store pos at tick {tick}, id {id}: {:?}",
                    p.pos
                );
                assert!(
                    p.vel[0].is_finite() && p.vel[1].is_finite(),
                    "non-finite store vel at tick {tick}, id {id}: {:?}",
                    p.vel
                );
                let speed = (p.vel[0] * p.vel[0] + p.vel[1] * p.vel[1]).sqrt();
                assert!(
                    speed <= speed_cap,
                    "store speed {speed} exceeds cap {speed_cap} at tick {tick}, id {id}"
                );
            }
        }
    }
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak store] {N} agents x {NUM_TICKS} ticks ({:.1} s simulated, integrated drive) completed in {elapsed_ms} ms",
        NUM_TICKS as f64 * DT
    );
}

#[test]
fn crowd_observer_soak_mid_scale() {
    use rustsim_core::prelude::VecStore;
    use rustsim_core::store::AgentStore;
    use rustsim_crowd::prelude::{step_scratch_store_observed, CrowdAgent, SocialForceModel};

    const N: usize = 500;
    const LENGTH: f64 = 40.0;
    const WIDTH: f64 = 10.0;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let params = social_force::Params::default();
    params.validate(DT).expect("SFM params must validate");

    let seed_peds = seed_counterflow(N, LENGTH, WIDTH, 0x0B55_0AC0);
    let mut store: VecStore<CrowdAgent> = VecStore::new();
    for (i, p) in seed_peds.iter().enumerate() {
        store.insert(CrowdAgent {
            id: i as u64 + 1,
            ped: *p,
        });
    }

    let walls: Vec<WallSegment> = Vec::new();
    let cutoff = social_force::neighbor_cutoff(&params);
    let cell = recommended_cell_size(cutoff);
    let mut scratch = Scratch::with_capacity(N, cell);
    let mut buf: Vec<Pedestrian> = Vec::with_capacity(N);
    let model = SocialForceModel;

    // Counter pinned to (id, tick) — verifies one observer invocation
    // per (tick, agent), no leak, no double-call, no skipped row.
    let mut observer_calls: u64 = 0;
    let mut last_id_seen: u64 = 0;
    let mut max_finite_pos: f64 = 0.0;

    let t0 = Instant::now();
    for _tick in 0..NUM_TICKS {
        step_scratch_store_observed(
            &model,
            &mut store,
            &walls,
            &params,
            DT,
            &mut scratch,
            &mut buf,
            &mut |id, ped: &Pedestrian| {
                observer_calls += 1;
                last_id_seen = id;
                // Cheap NaN guard inside the hot observer hook —
                // catches a kernel that hands the observer a bogus
                // row even if the post-tick state-write later
                // sanitises it.
                debug_assert!(
                    ped.pos[0].is_finite() && ped.pos[1].is_finite(),
                    "observer received non-finite pos for id {id}"
                );
                let mag = ped.pos[0].abs().max(ped.pos[1].abs());
                if mag.is_finite() && mag > max_finite_pos {
                    max_finite_pos = mag;
                }
            },
        );
    }

    let expected = (N as u64) * (NUM_TICKS as u64);
    assert_eq!(
        observer_calls, expected,
        "observer call count {observer_calls} != expected {expected} (N={N}, ticks={NUM_TICKS})"
    );
    assert!(
        last_id_seen >= 1 && last_id_seen <= N as u64,
        "observer last id {last_id_seen} out of range [1, {N}]"
    );
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak observer] {N} agents x {NUM_TICKS} ticks: {observer_calls} hook calls, max |pos|={max_finite_pos:.2}, completed in {elapsed_ms} ms"
    );
}

// ---------------------------------------------------------------------------
// Layered observer soak.
//
// `step_layered_scratch_observed` is the production telemetry entry
// point for the 2.5-D drive — closures forwarding into
// `TelemetryPipeline::push_row` (or any other sink) plug in here and
// must receive one call per (tick, agent) with stable
// `0..peds.len()` ordering across thousands of ticks. The unit
// tests in `src/threed.rs` cover the equivalence to the unobserved
// path on a single tick; this soak pins that the same contract
// holds across a sustained run with a non-trivial inter-floor
// traffic pattern (the same boarding mix as `layered_soak_mid_scale`).
// Asserts:
//   - exactly `N × NUM_TICKS` total observer calls (no leak, no
//     double-call, no skipped row);
//   - per-tick observation count == `N`;
//   - observation index sequence on every tick is `0..N` strictly
//     increasing (the layered drive never reorders the slice);
//   - every observed `Pedestrian3D` has finite planar pos/vel and a
//     valid floor membership.
// ---------------------------------------------------------------------------

#[test]
fn layered_observer_soak_mid_scale() {
    use rustsim_crowd::threed::{
        step_layered_scratch_observed, ConnectorKind, FloorTransition, LayeredScratch,
        LayeredSpace, Pedestrian3D,
    };

    const N: usize = 200;
    const HALF_TARGETING_F1: usize = 100;
    const DT: f64 = 0.05;
    const NUM_TICKS: usize = 600;

    let mut space = LayeredSpace::new();
    space.set_floor(0, 0.0);
    space.set_floor(1, 4.0);
    space.connectors.push(FloorTransition {
        id: 1,
        kind: ConnectorKind::Stair,
        from_floor: 0,
        from_pos: [10.0, 0.0],
        to_floor: 1,
        to_pos: [10.0, 0.0],
        boarding_radius: 1.0,
        travel_time: 10.0,
    });

    let mut peds: Vec<Pedestrian3D> = (0..N)
        .map(|i| {
            let y = (i as f64 - N as f64 / 2.0) * 0.4;
            let base = Pedestrian::new([0.0, y], [0.0, 0.0], 0.25, 1.34, [10.0, y]);
            if i < HALF_TARGETING_F1 {
                Pedestrian3D::heading_to_floor(base, 0, 1)
            } else {
                Pedestrian3D::grounded(base, 0)
            }
        })
        .collect();

    let params = social_force::Params::default();
    params.validate(DT).expect("SFM params must validate");
    let mut scratch = LayeredScratch::with_capacity(N);

    let mut total_calls: u64 = 0;
    // Per-tick state: cleared at the start of each tick, then
    // checked against `0..N` after the tick completes.
    let mut tick_indices: Vec<usize> = Vec::with_capacity(N);
    let mut nonfinite_observed: u64 = 0;
    let mut bad_floor_observed: u64 = 0;

    let t0 = Instant::now();
    for tick in 0..NUM_TICKS {
        tick_indices.clear();
        #[allow(deprecated)]
        step_layered_scratch_observed(
            &mut peds,
            &space,
            social_force::step,
            &params,
            DT,
            &mut scratch,
            &mut |idx: usize, p: &Pedestrian3D| {
                total_calls += 1;
                tick_indices.push(idx);
                if !(p.base.pos[0].is_finite()
                    && p.base.pos[1].is_finite()
                    && p.base.vel[0].is_finite()
                    && p.base.vel[1].is_finite())
                {
                    nonfinite_observed += 1;
                }
                if p.floor != 0 && p.floor != 1 {
                    bad_floor_observed += 1;
                }
            },
        );
        // Per-tick contract: exactly `N` observations, in stable
        // `0..N` order. The layered drive guarantees this by never
        // reordering `peds`; this soak pins that the guarantee
        // holds across a long run.
        assert_eq!(
            tick_indices.len(),
            N,
            "tick {tick}: observed {} agents, expected {N}",
            tick_indices.len()
        );
        for (expected, &got) in tick_indices.iter().enumerate() {
            assert_eq!(
                got, expected,
                "tick {tick}: observation index {got} at slot {expected} broke 0..N stable order"
            );
        }
    }

    let expected = (N as u64) * (NUM_TICKS as u64);
    assert_eq!(
        total_calls, expected,
        "layered observer call count {total_calls} != expected {expected}"
    );
    assert_eq!(
        nonfinite_observed, 0,
        "layered observer received {nonfinite_observed} non-finite pos/vel rows"
    );
    assert_eq!(
        bad_floor_observed, 0,
        "layered observer received {bad_floor_observed} rows with floor ∉ {{0, 1}}"
    );
    let elapsed_ms = t0.elapsed().as_millis();
    eprintln!(
        "[crowd soak layered-observer] {N} agents x {NUM_TICKS} ticks: {total_calls} hook calls, completed in {elapsed_ms} ms"
    );
}