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
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Test server management and robustness infrastructure for `api_ollama` integration tests.
//!
//! # Overview
//!
//! This module provides three critical robustness systems:
//!
//! 1. **Isolated Test Servers** - Eliminate environmental dependencies via hash-based port allocation
//! 2. **Timing Safety Framework** - Handle system load variance with 2x safety buffers
//! 3. **Loud Failure Enforcement** - Prevent silent test skips that hide infrastructure problems
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use crate::server_helpers::{get_isolated_endpoint, wait_for_checks};
//!
//! #[tokio::test]
//! async fn test_api_feature() {
//! // Use isolated server instead of hardcoded localhost:11434
//! let endpoint = get_isolated_endpoint().await
//! .expect("Failed to get test endpoint");
//!
//! let client = OllamaClient::new(endpoint, Duration::from_secs(30))?;
//!
//! // Your test logic with real API calls
//! let response = client.chat(request).await?;
//! assert!(response.message.content.len() > 0);
//! }
//! ```
//!
//! # Test Isolation Architecture (issue-server-exhaustion-001)
//!
//! Each test binary gets its own dedicated Ollama server instance on a unique port calculated
//! from the binary name hash. This prevents server resource exhaustion that occurred when all
//! tests shared port 11435, causing intermittent timeout failures after ~67 tests.
//!
//! **Port allocation**:
//! - Range: 11435-11534 (100 ports for test binaries)
//! - Formula: `BASE_PORT` + (`hash(binary_name)` % `PORT_RANGE`)
//! - Model: smollm2:360m (23% faster than tinyllama)
//! - Cleanup: Automatic on test completion
//!
//! # Robustness Patterns
//!
//! ## Pattern 1: Endpoint Isolation
//!
//! **Problem**: Tests depending on system Ollama (localhost:11434) are flaky because they race
//! with system state. Test passes when system Ollama stopped, fails when running.
//!
//! **Solution**: Use `get_isolated_endpoint()` for all tests making real API calls.
//!
//! **Example**: See `health_checks_tests.rs:test_intermittent_failure_handling` (issue-flaky-test-002)
//! - Before: 80% fail rate due to hardcoded localhost:11434
//! - After: 10/10 marathon passes with isolated endpoint
//!
//! ## Pattern 2: Timing Safety
//!
//! **Problem**: Brittle sleep-based synchronization fails under system load. Exact timing
//! assertions break when GC pauses or thread scheduling delays occur.
//!
//! **Solution**: Use `wait_for_checks()` with built-in 2x safety buffers instead of raw sleep.
//!
//! **Formula**: `wait_time = check_interval × min_checks × safety_factor(2.0)`
//!
//! **Example**:
//! ```rust,ignore
//! // BAD - Brittle exact timing
//! tokio::time::sleep(Duration::from_millis(300)).await;
//! assert_eq!(status.total_checks(), 3); // Fails if 4 checks happen
//!
//! // GOOD - Safety buffer + range assertion
//! wait_for_checks(interval, 3).await; // 600ms for nominal 300ms
//! assert!(status.total_checks() >= 3); // Tolerates variance
//! ```
//!
//! ## Pattern 3: Loud Failures
//!
//! **Problem**: Silent test skips (println + return) hide infrastructure problems and reduce
//! test coverage visibility. Tests appear to pass but actually skipped execution.
//!
//! **Solution**: Use `with_test_server!` macro or `.expect()` - never silent skip.
//!
//! **Example**:
//! ```rust,ignore
//! // BAD - Silent skip
//! match client.embeddings(req).await {
//! Ok(emb) => emb,
//! Err(e) => {
//! println!("⏭️ Skipping test - {e}");
//! return; // Test appears to pass but didn't run!
//! }
//! }
//!
//! // GOOD - Loud failure
//! client.embeddings(req).await
//! .expect("Embeddings should succeed - test server is running")
//! ```
//!
//! # Common Pitfalls
//!
//! ## Pitfall 1: Hardcoded localhost:11434 in API-Calling Tests
//!
//! **Symptom**: Test passes when system Ollama stopped, fails when running
//! **Root Cause**: Race condition with system Ollama state
//! **Fix**: Use `get_isolated_endpoint().await?` instead of hardcoded URL
//! **Example**: `health_checks_tests.rs:test_intermittent_failure_handling`
//!
//! ## Pitfall 2: Exact Timing Assertions
//!
//! **Symptom**: Test fails intermittently under system load
//! **Root Cause**: No safety margin for scheduler variance, GC pauses
//! **Fix**: Use `>=` assertions with 2x safety buffers via `wait_for_checks()`
//! **Example**: Wait 600ms for nominal 300ms (3 × 100ms × 2.0)
//!
//! ## Pitfall 3: Silent Test Skips
//!
//! **Symptom**: Test suite shows 100% pass but coverage is low
//! **Root Cause**: Tests silently return on errors instead of failing
//! **Fix**: Replace `println!() + return` with `.expect()` or panic
//! **Example**: 7 instances fixed in `embeddings_tests.rs` (issue-silent-skip-002 through -005)
//!
//! ## Pitfall 4: Shared Mutable State Across Tests
//!
//! **Symptom**: Tests fail based on execution order, not code correctness
//! **Root Cause**: Multiple tests modifying same resource (port, file, etc)
//! **Fix**: Each test binary automatically gets isolated server (hash-based port)
//! **Architecture**: Port allocation prevents conflicts - no manual coordination needed
//!
//! # Migration Guide
//!
//! When adding new integration tests that make API calls:
//!
//! ```rust,ignore
//! // BEFORE (hardcoded, flaky):
//! let client = OllamaClient::new(
//! "http://localhost:11434".to_string(),
//! Duration::from_secs(30)
//! )?;
//!
//! // AFTER (isolated, robust):
//! let endpoint = get_isolated_endpoint().await?;
//! let client = OllamaClient::new(endpoint, Duration::from_secs(30))?;
//! ```
//!
//! When adding timing-dependent tests:
//!
//! ```rust,ignore
//! // BEFORE (brittle):
//! tokio::time::sleep(Duration::from_millis(500)).await;
//! assert_eq!(checks, 5);
//!
//! // AFTER (robust):
//! wait_for_checks(interval, 5).await;
//! assert!(checks >= 5);
//! ```
//!
//! # Marathon Validation
//!
//! For tests prone to flakiness (timing-dependent, API-calling):
//!
//! ```bash
//! # Run 20 iterations to detect <5% flake rate
//! bash tests/-marathon_test.sh test_name 20
//!
//! # Run 100 iterations to detect <1% flake rate
//! bash tests/-marathon_test.sh test_name 100
//! ```
//!
//! **When to use**: After fixing flaky tests or adding timing-dependent logic.
use ;
use ;
use Duration;
use Instant;
use OllamaClient;
use DefaultHasher;
use ;
/// Global server instance shared across all tests in a single binary
static TEST_SERVER: = new;
/// Test server configuration
const BASE_PORT: u16 = 11435; // Base port for test servers
const PORT_RANGE: u16 = 100; // Allow 100 different test binaries (11435-11534)
// Optimization(phase3-model-switch): Changed from tinyllama to smollm2:360m for 23% speed improvement
// Root cause: Tinyllama (1.1B params) had extreme variability (350s-780s) and slow chat responses (avg 2220ms)
// Solution: Benchmark tested 4 models - smollm2:360m fastest (2024ms overall, 1730ms chat avg = 1.23x speedup)
// Benchmark results: smollm2:360m (2024ms), qwen2.5:0.5b (2267ms), tinyllama (2485ms), gemma3:1b (2672ms)
// Pitfall: Smaller model (360M vs 1.1B) may have different behavior - verify all tests still pass
const TEST_MODEL: &str = "smollm2:360m"; // Fastest model from benchmark (23% faster than tinyllama)
const SERVER_STARTUP_TIMEOUT: Duration = from_secs;
const MODEL_PULL_TIMEOUT: Duration = from_secs; // 5 minutes for model download
// Fix(issue-model-loading-timeout-001): Increased from 60s -> 180s to handle slow model loading
// Root cause: First inference request after server start takes 60+ seconds for model loading (smollm2:360m)
// Ollama loads models into RAM on first request, not during server startup - this is unavoidable overhead
// Pitfall: Timeout must exceed worst-case model load time (60-120s observed) plus inference time (10-30s)
const QUICK_RESPONSE_TIMEOUT: Duration = from_secs; // 3 minutes for model loading + inference
// Fix(issue-server-exhaustion-001): Unique port per test binary prevents server resource exhaustion
// Root cause: All tests shared port 11435, causing server exhaustion after ~67 tests with intermittent timeout failures
// Pitfall: Shared test infrastructure without isolation creates flaky tests that fail based on execution order, not code bugs
/// Calculate unique test port for this test binary based on binary name hash
///
/// This ensures each test binary gets its own isolated Ollama server instance,
/// preventing resource exhaustion and enabling parallel test execution.
///
/// # Returns
/// Port number in range [`BASE_PORT`, `BASE_PORT` + `PORT_RANGE`)
/// Managed test server instance
/// Clean up any orphaned Ollama test servers from previous runs
///
/// When test processes are killed forcefully (e.g., nextest timeout with SIGKILL),
/// the Drop implementation doesn't run, leaving orphaned Ollama servers running.
/// This function kills any user-owned Ollama servers AND runner processes before starting new tests.
///
/// Fix(issue-runner-cleanup-001): Added cleanup for ollama runner processes
/// Root cause: Only killed 'ollama serve' but left 'ollama runner' processes (each consuming 920MB RAM + 5-10 CPU cores)
/// Runner processes accumulate during parallel test execution, causing resource exhaustion and network timeouts
/// Pitfall: Always kill BOTH serve and runner processes - runners are the actual resource hogs
/// Get or create the global test server instance
///
/// # Errors
/// Returns an error if the test server fails to start or initialize
pub async
/// Test helper function to get a client for the managed test server
///
/// # Errors
/// Returns an error if the test server fails to start or initialize, or if mutex lock fails
pub async
/// Macro to ensure test server is available before running test
///
/// **Fix(issue-silent-skip-001)**: Changed from silent skip to loud failure.
/// **Root cause**: Silent skips (println + return) hide infrastructure problems and reduce test coverage visibility.
/// **Pitfall**: Tests must fail loudly when prerequisites are missing - use `#[ignore]` attribute for optional tests.
///
/// # When to Use
///
/// **Use this macro** for tests that need isolated Ollama client with test model:
/// - Quick tests that just need client + model (no manual endpoint setup)
/// - Tests that should fail loudly if infrastructure unavailable
/// - Migration from legacy silent skip pattern
///
/// **Don't use** when:
/// - Test needs custom endpoint URL (use `get_isolated_endpoint()` directly)
/// - Test needs custom client configuration (timeout, retries, etc.)
/// - Test is truly optional/experimental (use `#[ignore]` attribute instead)
///
/// # Loud Failure Rationale
///
/// Tests should never silently skip because:
/// - Hides broken test infrastructure (Ollama not installed, port conflicts)
/// - Reduces effective test coverage without visibility
/// - Violates "fail loudly" robustness principle
/// - Makes debugging harder (no clear signal of what's wrong)
///
/// # Migration Guide
///
/// ```rust,ignore
/// // ❌ BEFORE - Silent skip pattern (issue-silent-skip-001 through -005)
/// #[tokio::test]
/// async fn test_embeddings_feature() {
/// let client = match get_test_client().await {
/// Ok((c, _)) => c,
/// Err(e) => {
/// println!("⏭️ Skipping test - {e}");
/// return;
/// }
/// };
/// // Test logic...
/// }
///
/// // ✅ AFTER - Loud failure with macro
/// #[tokio::test]
/// async fn test_embeddings_feature() {
/// with_test_server!(|client, model| async move {
/// // Test logic...
/// Ok(())
/// });
/// }
/// ```
///
/// # Known Pitfalls
///
/// **Pitfall**: Catching macro panic to implement silent skip
/// **Symptom**: Code like `if let Err(_) = std::panic::catch_unwind(...)`
/// **Root Cause**: Attempting to bypass loud failure enforcement
/// **Fix**: If test is optional, use `#[ignore]` attribute, don't catch panic
/// **Pattern**: Mark test with `#[ignore = "reason"]` not `catch_unwind`
///
/// **Pitfall**: Using macro for configuration-only tests
/// **Symptom**: Test fails with "server unavailable" but only validates client creation
/// **Root Cause**: Macro requires full test server for simple config validation
/// **Fix**: Tests that don't make API calls shouldn't use this macro
/// **Example**: Tests for URL parsing, builder patterns, config validation
///
/// **Pitfall**: Returning wrong type from closure
/// **Symptom**: Compiler error "expected `()`, found `Result<...>`"
/// **Root Cause**: Macro expects async block returning `Result<(), Error>`
/// **Fix**: Ensure closure returns `Result<(), E>` where E implements Display
/// **Pattern**: `async move { /* test */ Ok(()) }`
///
/// # Resolution Steps
///
/// If test fails with "Test server unavailable":
/// 1. Install Ollama: `curl -fsSL https://ollama.com/install.sh | sh`
/// 2. Verify Ollama runs: `ollama --version`
/// 3. Check port availability: `lsof -i :11435-11534`
/// 4. Review `server_helpers.rs` startup logs for diagnostics
///
/// # Optional Tests
///
/// If a test is truly optional (e.g., requires external service), use `#[ignore]` attribute:
/// ```rust,ignore
/// #[tokio::test]
/// #[ignore = "requires external Ollama service"]
/// async fn test_optional_feature() { ... }
/// ```
///
/// # Examples
///
/// ```rust,ignore
/// // Example 1: Basic usage
/// #[tokio::test]
/// async fn test_chat_basic() {
/// with_test_server!(|client, model| async move {
/// let response = client.chat(ChatRequest::new(model)).await?;
/// assert!(!response.message.content.is_empty());
/// Ok(())
/// });
/// }
///
/// // Example 2: Multiple assertions
/// #[tokio::test]
/// async fn test_embeddings_dimensions() {
/// with_test_server!(|client, model| async move {
/// let request = EmbeddingsRequest::new(model, vec!["test".to_string()]);
/// let response = client.embeddings(request).await?;
///
/// assert_eq!(response.embeddings.len(), 1);
/// assert!(response.embeddings[0].len() > 0);
/// Ok(())
/// });
/// }
/// ```
//
// Endpoint Isolation Helpers
//
/// Get isolated test endpoint URL for robust testing
///
/// Returns URL for isolated test server running on hash-based unique port.
/// Eliminates race conditions with system Ollama on port 11434.
///
/// # When to Use
///
/// **Use this** whenever your test makes REAL API calls (`.chat()`, `.embeddings()`, `.generate()`).
///
/// **Don't use** for configuration-only tests that just validate client creation without API calls.
///
/// **Decision criteria**:
/// - If test calls `.await` on API method → Use `get_isolated_endpoint()`
/// - If test only checks client construction → Hardcoded endpoint acceptable
///
/// # Robustness Properties
///
/// - **Environmental Independence**: No dependency on system Ollama state
/// - **Parallel Safety**: Hash-based port allocation prevents conflicts
/// - **Deterministic**: Same binary always gets same port
///
/// # Errors
///
/// Returns error if test server initialization fails or server is not available.
///
/// # Example
///
/// ```rust,ignore
/// #[tokio::test]
/// async fn test_api_call() {
/// let endpoint = get_isolated_endpoint().await
/// .expect("Failed to get test endpoint");
///
/// let client = OllamaClient::new(endpoint, Duration::from_secs(30))?;
/// // Test uses isolated server, not system Ollama
/// }
/// ```
///
/// # Migration Pattern
///
/// **Before** (hardcoded, flaky):
/// ```rust,ignore
/// let client = OllamaClient::new(
/// "http://localhost:11434".to_string(), // ← Race with system Ollama
/// Duration::from_secs(30)
/// )?;
/// ```
///
/// **After** (isolated, robust):
/// ```rust,ignore
/// let endpoint = get_isolated_endpoint().await?;
/// let client = OllamaClient::new(
/// endpoint, // ← Uses unique test server port
/// Duration::from_secs(30)
/// )?;
/// ```
///
/// # Known Pitfalls
///
/// **Pitfall**: Using hardcoded `localhost:11434` in test making real API calls
///
/// **Symptom**: Test passes when system Ollama is stopped, fails when system Ollama is running.
/// Test failure is intermittent and environment-dependent.
///
/// **Root Cause**: Test connects to system Ollama instead of isolated test server, creating race
/// condition with system state. Health checks, model state, or port availability differ.
///
/// **Fix**: Replace hardcoded URL with `get_isolated_endpoint().await?`
///
/// **Real Example**: `health_checks_tests.rs:test_intermittent_failure_handling` (issue-flaky-test-002)
/// - Before: 80% fail rate due to hardcoded endpoint
/// - After: 10/10 marathon passes with isolated endpoint
/// - See lines 251-432 for complete implementation
// Used across multiple test files
pub async
/// Get invalid endpoint URL for failure testing
///
/// Returns endpoint URL guaranteed to fail (RFC 5737 non-routable address),
/// for testing error handling, circuit breakers, retry logic, and health check failure scenarios.
///
/// # When to Use
///
/// **Use this** when testing failure scenarios:
/// - Circuit breaker opening behavior (needs guaranteed failures)
/// - Health check failure detection and recovery
/// - Retry exhaustion scenarios (must fail every time)
/// - Timeout behavior validation (connection attempts guaranteed to timeout)
///
/// **Don't use** for:
/// - Tests requiring real API responses (use `get_isolated_endpoint()` instead)
/// - Tests simulating intermittent failures (use `client.simulate_endpoint_failure()`)
/// - Tests requiring specific error types (connection errors are generic)
///
/// # Known Pitfalls
///
/// **Pitfall**: Using `get_invalid_endpoint()` for positive test cases
/// **Symptom**: Test always fails with connection errors, never validates actual functionality
/// **Root Cause**: Invalid endpoint cannot serve real API responses
/// **Fix**: Use `get_isolated_endpoint()` for tests requiring real responses
/// **Example**: Health check recovery tests need real endpoint to validate recovery
///
/// **Pitfall**: Expecting specific error messages from invalid endpoint
/// **Symptom**: Tests break when underlying HTTP library changes error messages
/// **Root Cause**: Connection errors are implementation-dependent (OS, HTTP client)
/// **Fix**: Test for error presence, not specific error text
/// **Pattern**: `assert!(result.is_err())` not `assert_eq!(err.to_string(), "...")`
///
/// # Examples
///
/// ```rust,ignore
/// // Example 1: Circuit breaker opening
/// #[tokio::test]
/// async fn test_circuit_breaker_opens_on_failures() {
/// let endpoint = get_invalid_endpoint();
/// let client = OllamaClient::new(endpoint, Duration::from_secs(1))?;
///
/// // All requests will fail, triggering circuit breaker
/// for _ in 0..5 {
/// assert!(client.chat(...).await.is_err());
/// }
/// assert_eq!(client.circuit_breaker_state(), CircuitState::Open);
/// }
///
/// // Example 2: Retry exhaustion
/// #[tokio::test]
/// async fn test_retry_exhaustion() {
/// let endpoint = get_invalid_endpoint();
/// let client = OllamaClient::new(endpoint, Duration::from_secs(1))?
/// .with_retries(3);
///
/// let start = Instant::now();
/// let result = client.chat(...).await;
///
/// assert!(result.is_err()); // Failed after all retries
/// assert!(start.elapsed() >= Duration::from_secs(3)); // 3 retry attempts
/// }
/// ```
// Used across multiple test files
//
// Timing Robustness Helpers
//
/// Calculate safe wait time with 2x safety buffer for timing-dependent tests
///
/// Formula: `wait_time = check_interval × min_checks × safety_factor`
///
/// # When to Use
///
/// **Use this** for timing-dependent tests that need to wait for:
/// - Health check iterations (wait for N checks to complete)
/// - Periodic background tasks (wait for N task executions)
/// - Retry attempts (wait for N retry cycles)
/// - Rate limiting windows (wait for rate limit to reset)
///
/// **Don't use** for:
/// - Exact timing measurements (defeats purpose of safety buffer)
/// - Production code timeouts (tests only - production needs tighter bounds)
/// - Tests with external time constraints (API rate limits, session expirations)
///
/// # Robustness Rationale
///
/// Timing-dependent tests fail intermittently when:
/// - System is under load (GC pauses, thread scheduling delays)
/// - CI environment has variable performance
/// - Background tasks interfere with timing
///
/// Safety buffer (2.0x) accounts for:
/// - Scheduler variance (OS thread context switches)
/// - GC pauses in async runtime
/// - Network stack delays
/// - Measurement granularity
///
/// # Known Pitfalls
///
/// **Pitfall**: Using exact timing assertions after safe wait
/// **Symptom**: Test expects exactly N checks but gets N+1 or N+2
/// **Root Cause**: Safety buffer allows extra iterations beyond minimum
/// **Fix**: Use `>=` assertions, not `==` assertions
/// **Example**: `assert!(checks >= 3)` not `assert_eq!(checks, 3)`
///
/// **Pitfall**: Using `safety_factor` < 2.0 to "speed up tests"
/// **Symptom**: Tests pass locally but fail intermittently in CI
/// **Root Cause**: CI environments have higher scheduler variance
/// **Fix**: Always use 2.0x minimum, increase for CI flakiness
/// **Real Example**: `test_intermittent_failure_handling` (issue-flaky-test-002)
/// - Before: No safety buffer → 80% fail rate
/// - After: 2.0x buffer → 0% fail rate (10/10 marathon passes)
///
/// **Pitfall**: Calculating wait time manually instead of using helper
/// **Symptom**: Inconsistent safety factors across test suite
/// **Root Cause**: Copy-paste errors, forgotten multiplication
/// **Fix**: Use `wait_for_checks()` helper (wraps this function with 2.0x)
/// **Pattern**: `wait_for_checks(interval, 5).await` not manual calculation
///
/// # Examples
///
/// ```rust,ignore
/// // Example 1: Basic usage with range assertion
/// let interval = Duration::from_millis(100);
/// let min_checks = 3;
/// let wait_time = calculate_safe_wait_time(interval, min_checks, 2.0);
/// // Returns 600ms (3 × 100ms × 2.0)
///
/// tokio::time::sleep(wait_time).await;
/// let status = client.get_health_status();
/// assert!(status.total_checks() >= min_checks); // ✅ Range assertion
///
/// // Example 2: Higher safety factor for flaky CI
/// let wait_time = calculate_safe_wait_time(
/// Duration::from_millis(100),
/// 5,
/// 3.0 // Higher buffer for CI environment
/// );
/// // Returns 1500ms (5 × 100ms × 3.0)
/// ```
// Used across multiple test files
// Intentional - safety_factor is always positive
/// Wait for minimum number of checks to complete with safety buffer
///
/// Convenience wrapper for `calculate_safe_wait_time()` with hardcoded 2.0x safety factor.
/// Preferred over manual sleep calculations for test robustness.
///
/// # When to Use
///
/// **Use this** as default for timing-dependent waits:
/// - Health check test assertions (wait for N checks)
/// - Background task validation (wait for N executions)
/// - Periodic monitoring tests (wait for N iterations)
/// - Any test waiting for repeated operations
///
/// **Don't use** when:
/// - Custom safety factor needed (use `calculate_safe_wait_time()` directly)
/// - No timing dependency (don't add unnecessary waits)
/// - Waiting for single event (use event notification instead)
///
/// # Comparison with Naive Sleep
///
/// ```rust,ignore
/// // ❌ BAD - Brittle exact timing (fails under load)
/// tokio::time::sleep(Duration::from_millis(300)).await;
/// assert_eq!(status.total_checks(), 3); // Exact assertion
///
/// // ✅ GOOD - Robust timing with safety buffer
/// wait_for_checks(Duration::from_millis(100), 3).await; // 600ms (2x buffer)
/// assert!(status.total_checks() >= 3); // Range assertion
/// ```
///
/// # Known Pitfalls
///
/// **Pitfall**: Using exact sleep durations instead of `wait_for_checks()`
/// **Symptom**: Tests pass locally but fail intermittently in CI
/// **Root Cause**: Manual calculations miss safety buffer, don't account for variance
/// **Fix**: Replace `tokio::time::sleep()` with `wait_for_checks()`
/// **Migration**: `sleep(300ms)` → `wait_for_checks(100ms, 3)` (adds 2x buffer)
///
/// **Pitfall**: Pairing `wait_for_checks()` with exact assertions
/// **Symptom**: Test expects 3 checks but gets 4 due to timing variance
/// **Root Cause**: Safety buffer allows extra iterations beyond minimum
/// **Fix**: Always use `>=` assertions after `wait_for_checks()`
/// **Pattern**: `assert!(checks >= N)` never `assert_eq!(checks, N)`
///
/// **Pitfall**: Using `wait_for_checks()` for single-event synchronization
/// **Symptom**: Unnecessary delays in tests, slower test suite
/// **Root Cause**: Waiting for time instead of event notification
/// **Fix**: Use channels, condition variables, or polling for single events
/// **Example**: `rx.recv().await` instead of `wait_for_checks(...)`
///
/// # Examples
///
/// ```rust,ignore
/// // Example 1: Health check validation
/// let interval = Duration::from_millis(100);
/// client.start_health_monitoring().await;
///
/// wait_for_checks(interval, 5).await; // Waits 1000ms (5 × 100ms × 2.0)
///
/// let status = client.get_health_status();
/// assert!(status.total_checks() >= 5); // ✅ Range assertion
///
/// // Example 2: Failure detection
/// client.simulate_endpoint_failure();
///
/// wait_for_checks(interval, 3).await; // Waits 600ms (3 × 100ms × 2.0)
///
/// assert!(status.failed_checks() >= 3);
/// assert_eq!(status.overall_health(), EndpointHealth::Unhealthy);
/// ```
// Used across multiple test files
pub async
/// Timing assertion macro for range-based check counts
///
/// Use `>=` assertions instead of exact counts to tolerate timing variance.
///
/// # Example
///
/// ```rust,ignore
/// // BAD (brittle - fails if 6 checks happen):
/// assert_eq!(status.total_checks(), 5);
///
/// // GOOD (robust - tolerates 5, 6, 7, ... checks):
/// assert_timing_range!(status.total_checks() >= 5,
/// "Expected ≥5 checks after 750ms wait, got {}", status.total_checks());
/// ```
// Macro placement is intentional for visibility