hyperinfer-core 0.1.1

Core types and traits for HyperInfer LLM Gateway
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
use hyperinfer_core::{TelemetryConsumer, UsageRecord};
use std::sync::Once;
use testcontainers::{core::IntoContainerPort, runners::AsyncRunner, GenericImage};
use testcontainers_modules::redis::REDIS_PORT;

/// Helper for enabling tracing in tests when debugging.
/// Usage: call `init_tracing()` at the start of a test, then run with
/// `RUST_LOG=debug cargo test ...` to see trace output.
#[allow(dead_code)]
static TRACING_INIT: Once = Once::new();

#[allow(dead_code)]
fn init_tracing() {
    TRACING_INIT.call_once(|| {
        let _ = tracing_subscriber::fmt()
            .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
            .try_init();
    });
}

async fn setup_redis() -> (String, testcontainers::ContainerAsync<GenericImage>) {
    let redis = GenericImage::new("redis", "7.2")
        .with_exposed_port(REDIS_PORT.tcp())
        .with_wait_for(testcontainers::core::WaitFor::message_on_stdout(
            "Ready to accept connections",
        ))
        .start()
        .await
        .expect("Failed to start Redis container");
    let port = redis.get_host_port_ipv4(REDIS_PORT).await.unwrap();
    let redis_url = format!("redis://127.0.0.1:{}", port);
    (redis_url, redis)
}

#[tokio::test]
async fn test_telemetry_consumer_new() {
    let (redis_url, _container) = setup_redis().await;

    let result = TelemetryConsumer::new(&redis_url).await;
    assert!(result.is_ok(), "Should create consumer successfully");
}

#[tokio::test]
async fn test_telemetry_consumer_with_custom_settings() {
    let (redis_url, _container) = setup_redis().await;

    let result = TelemetryConsumer::new(&redis_url).await;
    assert!(result.is_ok(), "Should create consumer");

    let consumer = result
        .unwrap()
        .with_stream_key("custom:stream")
        .with_consumer_group("custom-group");

    // Can't directly verify fields, but verify it doesn't panic
    let _ = consumer;
}

#[tokio::test]
async fn test_telemetry_consumer_read_empty_stream() {
    let (redis_url, _container) = setup_redis().await;

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    assert_eq!(records.len(), 0, "Should have no records in empty stream");
}

#[tokio::test]
async fn test_telemetry_consumer_read_records() {
    let (redis_url, _container) = setup_redis().await;

    // Push some test data to the stream
    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    // Add test records to stream
    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("test-key-1")
        .arg("model")
        .arg("gpt-4")
        .arg("input_tokens")
        .arg("100")
        .arg("output_tokens")
        .arg("50")
        .arg("response_time_ms")
        .arg("250")
        .arg("timestamp")
        .arg("1700000000000")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("test-key-2")
        .arg("model")
        .arg("claude-3")
        .arg("input_tokens")
        .arg("200")
        .arg("output_tokens")
        .arg("100")
        .arg("response_time_ms")
        .arg("300")
        .arg("timestamp")
        .arg("1700000001000")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    // Read records
    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    assert_eq!(records.len(), 2, "Should have 2 records");
    assert_eq!(records[0].key, "test-key-1");
    assert_eq!(records[0].model, "gpt-4");
    assert_eq!(records[0].input_tokens, 100);
    assert_eq!(records[0].output_tokens, 50);
    assert_eq!(records[0].response_time_ms, 250);
    assert_eq!(records[0].timestamp, 1700000000000);

    assert_eq!(records[1].key, "test-key-2");
    assert_eq!(records[1].model, "claude-3");
    assert_eq!(records[1].input_tokens, 200);
    assert_eq!(records[1].output_tokens, 100);
    assert_eq!(records[1].response_time_ms, 300);
    assert_eq!(records[1].timestamp, 1700000001000);
}

#[tokio::test]
async fn test_telemetry_consumer_with_custom_stream() {
    let (redis_url, _container) = setup_redis().await;

    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    // Add test record to custom stream
    let _: String = redis::cmd("XADD")
        .arg("custom:telemetry")
        .arg("*")
        .arg("key")
        .arg("test-key")
        .arg("model")
        .arg("gpt-4")
        .arg("input_tokens")
        .arg("150")
        .arg("output_tokens")
        .arg("75")
        .arg("response_time_ms")
        .arg("200")
        .arg("timestamp")
        .arg("1700000000000")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer")
        .with_stream_key("custom:telemetry");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    assert_eq!(records.len(), 1);
    assert_eq!(records[0].key, "test-key");
    assert_eq!(records[0].model, "gpt-4");
}

#[tokio::test]
async fn test_telemetry_consumer_start_consuming() {
    use std::sync::Arc;
    use tokio::sync::Mutex;
    use tokio_util::sync::CancellationToken;

    let (redis_url, _container) = setup_redis().await;

    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    let received = Arc::new(Mutex::new(Vec::new()));
    let received_clone = Arc::clone(&received);

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let cancellation_token = CancellationToken::new();
    let handle = consumer
        .start_consuming(
            move |record: UsageRecord| {
                let received = Arc::clone(&received_clone);
                async move {
                    received.lock().await.push(record);
                    Ok(())
                }
            },
            cancellation_token.clone(),
        )
        .await
        .expect("Failed to start consuming");

    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("consume-test-key")
        .arg("model")
        .arg("gpt-4")
        .arg("input_tokens")
        .arg("100")
        .arg("output_tokens")
        .arg("50")
        .arg("response_time_ms")
        .arg("250")
        .arg("timestamp")
        .arg("1700000000000")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    let timeout = tokio::time::timeout(tokio::time::Duration::from_secs(10), async {
        loop {
            let len = received.lock().await.len();
            if len >= 1 {
                return;
            }
            tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;
        }
    })
    .await;

    assert!(timeout.is_ok(), "Timeout waiting for consumer to process");

    let records = received.lock().await;
    assert_eq!(records.len(), 1, "Should have consumed 1 record");
    assert_eq!(records[0].key, "consume-test-key");
    assert_eq!(records[0].model, "gpt-4");

    cancellation_token.cancel();
    handle.await.expect("Consumer task panicked");
}

#[tokio::test]
async fn test_telemetry_consumer_handles_malformed_data() {
    let (redis_url, _container) = setup_redis().await;

    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    // Add malformed record (missing fields)
    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("test-key")
        .arg("model")
        .arg("gpt-4")
        // Missing tokens and other fields
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    // Add valid record
    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("valid-key")
        .arg("model")
        .arg("gpt-4")
        .arg("input_tokens")
        .arg("100")
        .arg("output_tokens")
        .arg("50")
        .arg("response_time_ms")
        .arg("250")
        .arg("timestamp")
        .arg("1700000000000")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    // Should only get the valid record
    assert_eq!(records.len(), 1);
    assert_eq!(records[0].key, "valid-key");
}

#[tokio::test]
async fn test_telemetry_consumer_large_batch() {
    let (redis_url, _container) = setup_redis().await;

    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    // Add 50 records
    for i in 0..50 {
        let _: String = redis::cmd("XADD")
            .arg("hyperinfer:telemetry")
            .arg("*")
            .arg("key")
            .arg(format!("test-key-{}", i))
            .arg("model")
            .arg("gpt-4")
            .arg("input_tokens")
            .arg("100")
            .arg("output_tokens")
            .arg("50")
            .arg("response_time_ms")
            .arg("250")
            .arg("timestamp")
            .arg("1700000000000")
            .query_async(&mut conn)
            .await
            .expect("Failed to add to stream");
    }

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    assert_eq!(records.len(), 50, "Should read all 50 records");
}

#[tokio::test]
async fn test_telemetry_consumer_zero_tokens() {
    let (redis_url, _container) = setup_redis().await;

    let client = redis::Client::open(redis_url.as_str()).expect("Failed to create client");
    let config = redis::AsyncConnectionConfig::new()
        .set_response_timeout(Some(std::time::Duration::from_millis(10000)));
    let mut conn = client
        .get_multiplexed_async_connection_with_config(&config)
        .await
        .expect("Failed to connect");

    let _: String = redis::cmd("XADD")
        .arg("hyperinfer:telemetry")
        .arg("*")
        .arg("key")
        .arg("test-key")
        .arg("model")
        .arg("gpt-4")
        .arg("input_tokens")
        .arg("0")
        .arg("output_tokens")
        .arg("0")
        .arg("response_time_ms")
        .arg("0")
        .arg("timestamp")
        .arg("0")
        .query_async(&mut conn)
        .await
        .expect("Failed to add to stream");

    let consumer = TelemetryConsumer::new(&redis_url)
        .await
        .expect("Failed to create consumer");

    let records = consumer
        .read_single_batch()
        .await
        .expect("Failed to read batch");

    assert_eq!(records.len(), 1);
    assert_eq!(records[0].input_tokens, 0);
    assert_eq!(records[0].output_tokens, 0);
    assert_eq!(records[0].response_time_ms, 0);
}