api_huggingface 0.6.1

HuggingFace's API for accessing large language models (LLMs) and embeddings.
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
//! Integration tests for Circuit Breaker
//!
//! These tests use REAL `HuggingFace` API calls to verify circuit breaker behavior.
//! NO MOCKING is used - all tests interact with actual endpoints.
//!
//! ## Test Strategy
//!
//! - Use real `HuggingFace` API endpoints
//! - Test actual failure scenarios ( invalid models, network errors )
//! - Test recovery scenarios with real successful calls

#![ allow( clippy::doc_markdown ) ]
//! - Test all state transitions with real operations
//!
//! ## Running Tests
//!
//! These tests require:
//! - HuggingFace API key ( `HUGGINGFACE_API_KEY` or `INFERENCE_API_KEY` env var )
//! - Network connectivity
//! - Real API quota/limits
//!
//! Run with:
//! ```bash
//! cargo test --test circuit_breaker_tests --all-features -- --ignored
//! ```

use api_huggingface::reliability::{ CircuitBreaker, CircuitBreakerConfig, CircuitBreakerError, CircuitState };
use core::time::Duration;

#[ cfg( feature = "integration" ) ]
use api_huggingface::{
  Client,
  environment::HuggingFaceEnvironmentImpl,
  providers::ChatMessage,
  Secret,
};

/// Helper to create a test client
#[ cfg( feature = "integration" ) ]
fn create_test_client() -> Client< HuggingFaceEnvironmentImpl >
{
  use workspace_tools as workspace;

  let workspace = workspace::workspace()
    .expect( "[create_test_client] Failed to access workspace - required for integration tests" );
  let secrets = workspace.load_secrets_from_file( "-secrets.sh" )
    .expect( "[create_test_client] Failed to load secret/-secrets.sh - required for integration tests" );
  let api_key = secrets.get( "HUGGINGFACE_API_KEY" )
    .expect( "[create_test_client] HUGGINGFACE_API_KEY not found in secret/-secrets.sh - required for integration tests. Get your token from https://huggingface.co/settings/tokens" )
    .clone();

  let secret = Secret::new( api_key );
  let env = HuggingFaceEnvironmentImpl::build( secret, None )
    .expect( "Failed to build environment" );
  Client::build( env ).expect( "Failed to create client" )
}

// ============================================================================
// Basic Circuit Breaker Tests
// ============================================================================

#[ tokio::test ]
async fn test_circuit_breaker_initial_state_is_closed() 
{
  let circuit_breaker = CircuitBreaker::new( CircuitBreakerConfig::default( ));

  assert!( circuit_breaker.is_closed( ).await );
  assert_eq!( circuit_breaker.state( ).await, CircuitState::Closed );
  assert_eq!( circuit_breaker.failure_count( ).await, 0 );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_successful_request_keeps_closed() 
{
  let client = create_test_client( );
  let circuit_breaker = CircuitBreaker::new( CircuitBreakerConfig::default( ));

  let result = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  assert!( result.is_ok( ), "Request should succeed" );
  assert!( circuit_breaker.is_closed( ).await, "Circuit should remain closed" );
  assert_eq!( circuit_breaker.failure_count( ).await, 0, "Failure count should be 0" );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_resets_failure_count_on_success() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 5,
  success_threshold : 2,
  timeout : Duration::from_secs( 60 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // First, cause some failures ( but not enough to open circuit )
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert_eq!( circuit_breaker.failure_count( ).await, 2 );
  assert!( circuit_breaker.is_closed( ).await );

  // Now succeed
  let result = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  assert!( result.is_ok( ));
  assert_eq!( circuit_breaker.failure_count( ).await, 0, "Success should reset failure count" );
}

// ============================================================================
// Circuit Opening Tests
// ============================================================================

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_opens_after_threshold_failures() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 3,
  success_threshold : 2,
  timeout : Duration::from_secs( 60 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Execute 3 failing requests
  for i in 0..3
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;

  if i < 2
  {
      assert!( circuit_breaker.is_closed( ).await, "Circuit should stay closed before threshold" );
  }
  }

  assert!( circuit_breaker.is_open( ).await, "Circuit should be open after threshold failures" );
  assert_eq!( circuit_breaker.failure_count( ).await, 3 );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_rejects_requests_when_open() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 2,
  success_threshold : 2,
  timeout : Duration::from_secs( 60 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Open the circuit with failures
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert!( circuit_breaker.is_open( ).await );

  // Try a request that would normally succeed - should be rejected
  let result = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  assert!( result.is_err( ), "Request should be rejected" );
  match result
  {
  Err( api_huggingface::reliability::CircuitBreakerError::CircuitOpen ) => {
      // Expected
  }
  _ => panic!( "Expected CircuitOpen error" ),
  }
}

// ============================================================================
// Half-Open State and Recovery Tests
// ============================================================================

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_transitions_to_half_open_after_timeout() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 2,
  success_threshold : 2,
  timeout : Duration::from_millis( 500 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Open the circuit
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert!( circuit_breaker.is_open( ).await );

  // Wait for timeout
  tokio::time::sleep( Duration::from_millis( 600 )).await;

  // Execute a request - should transition to half-open
  let result = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  assert!( result.is_ok( ), "Request should succeed in half-open state" );
  assert!( !circuit_breaker.is_open( ).await, "Circuit should not be open" );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_closes_after_success_threshold_in_half_open() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 2,
  success_threshold : 2,
  timeout : Duration::from_millis( 500 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Open the circuit
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert!( circuit_breaker.is_open( ).await );

  // Wait for timeout
  tokio::time::sleep( Duration::from_millis( 600 )).await;

  // Execute success_threshold successful requests
  for _ in 0..2
  {
  let result = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "meta-llama/Llama-3.3-70B-Instruct",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  assert!( result.is_ok( ));
  }

  // Circuit should be closed
  assert!( circuit_breaker.is_closed( ).await, "Circuit should be closed after success threshold" );
}

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_reopens_on_failure_in_half_open() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 2,
  success_threshold : 2,
  timeout : Duration::from_millis( 500 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Open the circuit
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert!( circuit_breaker.is_open( ).await );

  // Wait for timeout
  tokio::time::sleep( Duration::from_millis( 600 )).await;

  // One success ( transitions to half-open )
  let _ = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  // One failure ( should reopen )
  let _ = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "invalid-model-xyz",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  // Circuit should be open again
  assert!( circuit_breaker.is_open( ).await, "Circuit should reopen after failure in half-open" );
}

// ============================================================================
// Reset Tests
// ============================================================================

#[ cfg( feature = "integration" ) ]
#[ tokio::test ]
async fn test_circuit_breaker_reset_clears_all_state() 
{
  let client = create_test_client( );
  let config = CircuitBreakerConfig {
  failure_threshold : 2,
  success_threshold : 2,
  timeout : Duration::from_secs( 60 ),
  };
  let circuit_breaker = CircuitBreaker::new( config );

  // Open the circuit
  for _ in 0..2
  {
  let _ = circuit_breaker.execute( async {
      client.providers( ).chat_completion(
  "invalid-model-xyz",
  vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
  Some( 10 ),
  None,
  None,
      ).await
  } ).await;
  }

  assert!( circuit_breaker.is_open( ).await );
  assert_eq!( circuit_breaker.failure_count( ).await, 2 );

  // Reset
  circuit_breaker.reset( ).await;

  // All state should be cleared
  assert!( circuit_breaker.is_closed( ).await );
  assert_eq!( circuit_breaker.failure_count( ).await, 0 );
  assert_eq!( circuit_breaker.success_count( ).await, 0 );

  // Should be able to execute requests normally
  let result = circuit_breaker.execute( async {
  client.providers( ).chat_completion(
      "meta-llama/Llama-3.3-70B-Instruct",
      vec![ChatMessage { role : "user".to_string( ), content : "test".to_string( ), tool_calls : None, tool_call_id : None } ],
      Some( 10 ),
      None,
      None,
  ).await
  } ).await;

  assert!( result.is_ok( ));
}

// ============================================================================
// Configuration Tests
// ============================================================================

#[ tokio::test ]
async fn test_circuit_breaker_default_config() 
{
  let config = CircuitBreakerConfig::default( );

  assert_eq!( config.failure_threshold, 5 );
  assert_eq!( config.success_threshold, 2 );
  assert_eq!( config.timeout, Duration::from_secs( 60 ));

  let circuit_breaker = CircuitBreaker::new( config );
  assert!( circuit_breaker.is_closed( ).await );
}

#[ tokio::test ]
async fn test_circuit_breaker_custom_config() 
{
  let config = CircuitBreakerConfig {
  failure_threshold : 10,
  success_threshold : 3,
  timeout : Duration::from_secs( 120 ),
  };

  let circuit_breaker = CircuitBreaker::new( config );
  assert!( circuit_breaker.is_closed( ).await );
}

// ============================================================================
// Pure-logic tests (migrated from src/reliability/circuit_breaker.rs)
// ============================================================================

#[ tokio::test ]
async fn test_initial_state_is_closed()
{
  let cb = CircuitBreaker::new( CircuitBreakerConfig::default() );
  assert!( cb.is_closed().await );
  assert_eq!( cb.state().await, CircuitState::Closed );
}

#[ tokio::test ]
async fn test_successful_operation_keeps_circuit_closed()
{
  let cb = CircuitBreaker::new( CircuitBreakerConfig::default() );

  let result = cb.execute( async { Ok::< _, String >( "success" ) } ).await;

  assert!( result.is_ok() );
  assert!( cb.is_closed().await );
}

#[ tokio::test ]
async fn test_failures_open_circuit()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 3,
    success_threshold : 2,
    timeout : Duration::from_secs( 60 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..3
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }

  assert!( cb.is_open().await );
}

#[ tokio::test ]
async fn test_open_circuit_rejects_requests()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 2,
    success_threshold : 2,
    timeout : Duration::from_secs( 60 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..2
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }

  assert!( cb.is_open().await );

  let result = cb.execute( async { Ok::< _, String >( "success" ) } ).await;
  assert!( matches!( result, Err( CircuitBreakerError::CircuitOpen ) ) );
}

#[ tokio::test ]
async fn test_timeout_transitions_to_half_open()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 2,
    success_threshold : 2,
    timeout : Duration::from_millis( 100 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..2
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }
  assert!( cb.is_open().await );

  tokio::time::sleep( Duration::from_millis( 150 ) ).await;

  let _ = cb.execute( async { Ok::< _, String >( "success" ) } ).await;

  assert!( !cb.is_open().await );
}

#[ tokio::test ]
async fn test_half_open_success_closes_circuit()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 2,
    success_threshold : 2,
    timeout : Duration::from_millis( 100 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..2
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }

  tokio::time::sleep( Duration::from_millis( 150 ) ).await;

  for _ in 0..2
  {
    let _ = cb.execute( async { Ok::< _, String >( "success" ) } ).await;
  }

  assert!( cb.is_closed().await );
}

#[ tokio::test ]
async fn test_half_open_failure_reopens_circuit()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 2,
    success_threshold : 2,
    timeout : Duration::from_millis( 100 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..2
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }

  tokio::time::sleep( Duration::from_millis( 150 ) ).await;

  let _ = cb.execute( async { Ok::< _, String >( "success" ) } ).await;

  let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;

  assert!( cb.is_open().await );
}

#[ tokio::test ]
async fn test_reset_clears_state()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 2,
    success_threshold : 2,
    timeout : Duration::from_secs( 60 ),
  };
  let cb = CircuitBreaker::new( config );

  for _ in 0..2
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }
  assert!( cb.is_open().await );

  cb.reset().await;

  assert!( cb.is_closed().await );
  assert_eq!( cb.failure_count().await, 0 );
  assert_eq!( cb.success_count().await, 0 );
}

/// Circuit stays closed until the failure count reaches exactly `failure_threshold`.
///
/// Root Cause: N/A — coverage gap.  The condition is `failure_count >= failure_threshold`.
///   Existing tests only verify that `threshold` failures open the circuit.  The other
///   half — that `threshold - 1` failures keep it closed — was never asserted in unit tests.
/// Why Not Caught: All pure-logic unit tests inject exactly `threshold` failures and then
///   check the open state; the "stays closed at threshold - 1" invariant was not tested.
/// Fix Applied: N/A — test added to lock both halves of the boundary invariant.
/// Prevention: For every `>=` threshold guard, test both `N - 1` (stays closed) and `N`
///   (opens) to catch off-by-one changes in a single refactor.
/// Pitfall: Changing `>=` to `>` would shift opening by one failure.  `test_failures_open_circuit`
///   catches that, but this test makes the closed-below-threshold contract explicit.
#[ tokio::test ]
async fn test_circuit_stays_closed_below_threshold()
{
  let config = CircuitBreakerConfig
  {
    failure_threshold : 5,
    success_threshold : 2,
    timeout : Duration::from_secs( 60 ),
  };
  let cb = CircuitBreaker::new( config );

  // threshold - 1 = 4 failures must NOT open the circuit
  for _ in 0..4
  {
    let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  }

  assert!( cb.is_closed().await, "Circuit must stay closed with threshold - 1 failures" );
  assert_eq!( cb.failure_count().await, 4, "Must track all 4 failures" );

  // The 5th failure (exactly at threshold) must open it
  let _ = cb.execute( async { Err::< String, _ >( "error" ) } ).await;
  assert!( cb.is_open().await, "Circuit must open at exactly the threshold" );
  assert_eq!( cb.failure_count().await, 5 );
}