terraphim_middleware 1.16.34

Terraphim middleware for searching haystacks
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
use serde_json::json;
use std::process::{Child, Command};
use std::time::Duration;

/// End-to-End Integration Test for QueryRs Document Persistence Fix
/// This test validates the complete flow:
/// 1. Start the server with the fixed configuration
/// 2. Perform a search that triggers QueryRs document processing
/// 3. Verify documents are saved to persistence
/// 4. Check that summarization tasks can be created
/// 5. Validate the complete search response
#[tokio::test]
async fn test_query_rs_e2e_integration() {
    println!("๐Ÿงช QueryRs End-to-End Integration Test");
    println!("=====================================");

    // Start the server in the background
    let server_process = start_test_server().await;

    // Wait for server to start
    tokio::time::sleep(Duration::from_secs(5)).await;

    // Test the search endpoint
    match test_search_endpoint().await {
        Ok(response) => {
            println!("โœ… Search endpoint test successful");

            // Validate the response structure
            validate_search_response(&response).await;

            // Test document persistence
            test_document_persistence().await;

            // Test summarization readiness
            test_summarization_readiness().await;

            println!("\n๐ŸŽ‰ END-TO-END INTEGRATION TEST PASSED!");
            println!(
                "๐Ÿš€ Complete flow working: Server -> Search -> Persistence -> Summarization Ready"
            );
        }
        Err(e) => {
            println!("โš ๏ธ  Search endpoint test failed: {}", e);
            println!("๐Ÿ”„ This may be due to network issues or server startup time");
        }
    }

    // Clean up - stop the server
    if let Some(mut process) = server_process {
        let _ = process.kill();
        let _ = process.wait();
        println!("๐Ÿงน Test server stopped");
    }
}

async fn start_test_server() -> Option<Child> {
    println!("๐Ÿš€ Starting test server...");

    // Build the server first
    let build_result = Command::new("cargo")
        .args(["build", "--release", "--bin", "terraphim_server"])
        .current_dir(".")
        .output();

    match build_result {
        Ok(output) => {
            if !output.status.success() {
                println!(
                    "โŒ Failed to build server: {}",
                    String::from_utf8_lossy(&output.stderr)
                );
                return None;
            }
            println!("โœ… Server built successfully");
        }
        Err(e) => {
            println!("โŒ Failed to build server: {}", e);
            return None;
        }
    }

    // Start the server
    let server_result = Command::new("./target/release/terraphim_server")
        .args([
            "--config",
            "terraphim_server/default/combined_roles_config.json",
        ])
        .current_dir(".")
        .spawn();

    match server_result {
        Ok(process) => {
            println!("โœ… Test server started (PID: {})", process.id());
            Some(process)
        }
        Err(e) => {
            println!("โŒ Failed to start server: {}", e);
            None
        }
    }
}

async fn test_search_endpoint() -> Result<serde_json::Value, Box<dyn std::error::Error>> {
    println!("๐Ÿ” Testing search endpoint...");

    let client = reqwest::Client::new();
    let search_payload = json!({
        "search_term": "tokio",
        "role": "Rust Engineer"
    });

    let response = client
        .post("http://localhost:8000/documents/search")
        .header("Content-Type", "application/json")
        .json(&search_payload)
        .send()
        .await?;

    if !response.status().is_success() {
        return Err(format!("Search request failed with status: {}", response.status()).into());
    }

    let response_json: serde_json::Value = response.json().await?;
    println!("โœ… Search request successful");

    Ok(response_json)
}

async fn validate_search_response(response: &serde_json::Value) {
    println!("๐Ÿ“‹ Validating search response structure...");

    // Check required fields
    assert!(
        response.get("total").is_some(),
        "Response should have 'total' field"
    );
    assert!(
        response.get("results").is_some(),
        "Response should have 'results' field"
    );

    let total = response.get("total").unwrap().as_u64().unwrap_or(0);
    let empty_vec = vec![];
    let results = response
        .get("results")
        .unwrap()
        .as_array()
        .unwrap_or(&empty_vec);

    println!("  ๐Ÿ“Š Total results: {}", total);
    println!("  ๐Ÿ“Š Results array length: {}", results.len());

    // Validate that we have results
    assert!(total > 0, "Should have some search results");
    assert!(!results.is_empty(), "Results array should not be empty");

    // Validate result structure
    if let Some(first_result) = results.first() {
        assert!(
            first_result.get("id").is_some(),
            "Result should have 'id' field"
        );
        assert!(
            first_result.get("title").is_some(),
            "Result should have 'title' field"
        );
        assert!(
            first_result.get("url").is_some(),
            "Result should have 'url' field"
        );

        let result_id = first_result.get("id").unwrap().as_str().unwrap();
        let result_title = first_result.get("title").unwrap().as_str().unwrap();

        println!("  ๐Ÿ“„ Sample result:");
        println!("    ID: {}", result_id);
        println!("    Title: {}", result_title);
    }

    println!("โœ… Search response structure validated");
}

async fn test_document_persistence() {
    println!("๐Ÿ’พ Testing document persistence...");

    // This test would ideally check the persistence layer directly
    // For now, we'll validate that the search results have the expected structure
    // that indicates they were processed and could be persisted

    let client = reqwest::Client::new();
    let search_payload = json!({
        "search_term": "async",
        "role": "Rust Engineer"
    });

    match client
        .post("http://localhost:8000/documents/search")
        .header("Content-Type", "application/json")
        .json(&search_payload)
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                let response_json: serde_json::Value = response.json().await.unwrap();
                let results = response_json.get("results").unwrap().as_array().unwrap();

                println!("  ๐Ÿ“Š Found {} results for persistence test", results.len());

                // Check that results have the structure expected after persistence fix
                let mut valid_results = 0;
                for result in results.iter().take(3) {
                    if result.get("id").is_some()
                        && result.get("title").is_some()
                        && result.get("body").is_some()
                    {
                        valid_results += 1;
                    }
                }

                assert!(
                    valid_results > 0,
                    "Should have valid results with proper structure"
                );
                println!(
                    "  โœ… {} results have valid structure for persistence",
                    valid_results
                );
            }
        }
        Err(e) => {
            println!("  โš ๏ธ  Persistence test failed: {}", e);
        }
    }

    println!("โœ… Document persistence test completed");
}

async fn test_summarization_readiness() {
    println!("๐Ÿค– Testing summarization readiness...");

    let client = reqwest::Client::new();
    let search_payload = json!({
        "search_term": "rust-performance",
        "role": "Rust Engineer"
    });

    match client
        .post("http://localhost:8000/documents/search")
        .header("Content-Type", "application/json")
        .json(&search_payload)
        .send()
        .await
    {
        Ok(response) => {
            if response.status().is_success() {
                let response_json: serde_json::Value = response.json().await.unwrap();

                // Check if summarization_tasks field exists
                let summarization_tasks = response_json.get("summarization_tasks");

                match summarization_tasks {
                    Some(tasks) => {
                        if tasks.is_array() {
                            let task_count = tasks.as_array().unwrap().len();
                            println!("  ๐Ÿ“Š Summarization tasks: {}", task_count);

                            if task_count > 0 {
                                println!("  โœ… Summarization tasks created successfully");
                            } else {
                                println!("  โš ๏ธ  No summarization tasks created (may be expected)");
                            }
                        } else if tasks.is_null() {
                            println!("  โš ๏ธ  Summarization tasks field is null");
                        } else {
                            println!("  โš ๏ธ  Unexpected summarization_tasks format");
                        }
                    }
                    None => {
                        println!("  โš ๏ธ  No summarization_tasks field in response");
                    }
                }

                // Check other relevant fields
                let total = response_json.get("total").unwrap().as_u64().unwrap_or(0);
                let results = response_json.get("results").unwrap().as_array().unwrap();

                println!("  ๐Ÿ“Š Total: {}, Results: {}", total, results.len());

                // Validate that we have results that could be summarized
                if !results.is_empty() {
                    println!("  โœ… Results available for summarization");
                }
            }
        }
        Err(e) => {
            println!("  โš ๏ธ  Summarization readiness test failed: {}", e);
        }
    }

    println!("โœ… Summarization readiness test completed");
}

/// Test that validates the server configuration is correct
#[tokio::test]
async fn test_server_configuration() {
    println!("๐Ÿงช Server Configuration Test");
    println!("============================");

    // Test that the configuration file exists and is valid
    let config_path = "terraphim_server/default/combined_roles_config.json";

    match std::fs::read_to_string(config_path) {
        Ok(config_content) => {
            println!("โœ… Configuration file found: {}", config_path);

            // Parse the configuration
            match serde_json::from_str::<serde_json::Value>(&config_content) {
                Ok(config) => {
                    println!("โœ… Configuration file is valid JSON");

                    // Check for Rust Engineer role
                    if let Some(roles) = config.get("roles") {
                        if let Some(rust_engineer) = roles.get("Rust Engineer") {
                            println!("โœ… Rust Engineer role found in configuration");

                            // Check for QueryRs haystack
                            if let Some(haystacks) = rust_engineer.get("haystacks") {
                                if let Some(haystack_array) = haystacks.as_array() {
                                    let mut found_queryrs = false;
                                    for haystack in haystack_array {
                                        if let Some(service) = haystack.get("service") {
                                            if service == "QueryRs" {
                                                found_queryrs = true;
                                                println!("โœ… QueryRs haystack found");

                                                // Check for disable_content_enhancement parameter
                                                if let Some(extra_params) =
                                                    haystack.get("extra_parameters")
                                                {
                                                    if let Some(disable_enhancement) = extra_params
                                                        .get("disable_content_enhancement")
                                                    {
                                                        if disable_enhancement == "true" {
                                                            println!(
                                                                "โœ… disable_content_enhancement is set to true"
                                                            );
                                                        } else {
                                                            println!(
                                                                "โš ๏ธ  disable_content_enhancement is not set to true"
                                                            );
                                                        }
                                                    } else {
                                                        println!(
                                                            "โš ๏ธ  disable_content_enhancement parameter not found"
                                                        );
                                                    }
                                                } else {
                                                    println!("โš ๏ธ  extra_parameters not found");
                                                }
                                                break;
                                            }
                                        }
                                    }

                                    if !found_queryrs {
                                        println!(
                                            "โŒ QueryRs haystack not found in Rust Engineer role"
                                        );
                                    }
                                } else {
                                    println!("โŒ haystacks is not an array");
                                }
                            } else {
                                println!("โŒ haystacks not found in Rust Engineer role");
                            }

                            // Check for LLM configuration
                            if let Some(llm_auto_summarize) =
                                rust_engineer.get("llm_auto_summarize")
                            {
                                if llm_auto_summarize == true {
                                    println!("โœ… llm_auto_summarize is enabled");
                                } else {
                                    println!("โš ๏ธ  llm_auto_summarize is disabled");
                                }
                            } else {
                                println!("โš ๏ธ  llm_auto_summarize not found in configuration");
                            }

                            if let Some(llm_provider) = rust_engineer.get("llm_provider") {
                                println!("โœ… llm_provider: {}", llm_provider);
                            } else {
                                println!("โš ๏ธ  llm_provider not found in configuration");
                            }
                        } else {
                            println!("โŒ Rust Engineer role not found in configuration");
                        }
                    } else {
                        println!("โŒ roles not found in configuration");
                    }
                }
                Err(e) => {
                    println!("โŒ Configuration file is not valid JSON: {}", e);
                }
            }
        }
        Err(e) => {
            println!("โŒ Configuration file not found: {}", e);
        }
    }

    println!("\nโœ… Server configuration test completed");
}