File size: 8,787 Bytes
ddcb55f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""

Deep Data & Edge-Case Benchmark Suite against Live Production API

Tests datasets:

- Graph & Tree algorithms

- Sorting algorithms

- Dynamic programming & Greedy

- Strings & Two-pointer

- Platform rules & FAQs

- Code & Syntax inputs

- Linguistic edge cases (case variance, typos, multi-line, unicode)

- Concurrency & Latency

"""

import time
import requests
import json
import concurrent.futures

BASE_URL = "https://chatbot.codorythm.com"

test_suite = [
    # Category 1: Real Training Data Sample Tests across DSA topics
    {"cat": "Dataset - Graph", "q": "How does Dijkstra's algorithm work?", "expected_intent_part": "dijkstra"},
    {"cat": "Dataset - Graph", "q": "Explain A* pathfinding algorithm", "expected_intent_part": "a_star"},
    {"cat": "Dataset - Graph", "q": "How does Floyd Warshall work?", "expected_intent_part": "floyd"},
    {"cat": "Dataset - Graph", "q": "Explain Kruskal's algorithm for minimum spanning tree", "expected_intent_part": "kruskal"},
    {"cat": "Dataset - Tree", "q": "How do you check if a binary tree is balanced?", "expected_intent_part": "balanced_tree"},
    {"cat": "Dataset - Tree", "q": "Explain AVL tree rotations", "expected_intent_part": "avl"},
    {"cat": "Dataset - Tree", "q": "What is the diameter of a binary tree?", "expected_intent_part": "diameter"},
    {"cat": "Dataset - Sorting", "q": "What is the time complexity of merge sort?", "expected_intent_part": "merge_sort"},
    {"cat": "Dataset - Sorting", "q": "Explain quick sort algorithm", "expected_intent_part": "quick_sort"},
    {"cat": "Dataset - Sorting", "q": "How does radix sort work?", "expected_intent_part": "radix"},
    {"cat": "Dataset - DP", "q": "Explain Coin Change problem using dynamic programming", "expected_intent_part": "coin_change"},
    {"cat": "Dataset - DP", "q": "How to solve edit distance between two strings?", "expected_intent_part": "editdistance"},
    {"cat": "Dataset - DP", "q": "What is longest common subsequence?", "expected_intent_part": "longestcommonsubsequence"},
    {"cat": "Dataset - Greedy", "q": "Explain Huffman coding algorithm", "expected_intent_part": "huffman"},
    {"cat": "Dataset - Greedy", "q": "What is fractional knapsack problem?", "expected_intent_part": "knapsack"},
    {"cat": "Dataset - Strings", "q": "Explain KMP pattern matching algorithm", "expected_intent_part": "kmp"},
    {"cat": "Dataset - Strings", "q": "Find longest substring without repeating characters", "expected_intent_part": "longest_substring"},
    {"cat": "Dataset - Strings", "q": "What is minimum window substring?", "expected_intent_part": "minimum_window"},
    {"cat": "Dataset - Backtracking", "q": "How to solve N Queens problem?", "expected_intent_part": "n_queens"},
    {"cat": "Dataset - Backtracking", "q": "Explain Sudoku solver using backtracking", "expected_intent_part": "sudoku"},
    {"cat": "Dataset - Backtracking", "q": "How does Rat in a Maze backtracking work?", "expected_intent_part": "rat_in_a_maze"},
    {"cat": "Dataset - Linked List", "q": "How do I reverse a linked list?", "expected_intent_part": "reverse_ll"},
    {"cat": "Dataset - Stacks", "q": "How to check valid parentheses using stack?", "expected_intent_part": "valid_parenthesis"},
    {"cat": "Dataset - Stacks", "q": "Convert infix expression to postfix", "expected_intent_part": "infix_to_postfix"},

    # Category 2: Platform Rules & FAQs
    {"cat": "Platform Rules", "q": "Can I use external libraries in codorythm?", "expected_intent_part": None},
    {"cat": "Platform Rules", "q": "What programming languages are supported?", "expected_intent_part": None},
    {"cat": "Platform Rules", "q": "How does code grading work?", "expected_intent_part": None},

    # Category 3: Linguistic Variations & Noise
    {"cat": "Linguistic Edge Case", "q": "WHAT IS BINARY SEARCH?", "expected_intent_part": "binary_search"},
    {"cat": "Linguistic Edge Case", "q": "what is binary search?", "expected_intent_part": "binary_search"},
    {"cat": "Linguistic Edge Case", "q": "What    is     binary     search?", "expected_intent_part": "binary_search"},
    {"cat": "Linguistic Edge Case", "q": "Can you please explain binary search to me?", "expected_intent_part": "binary_search"},
    {"cat": "Linguistic Edge Case", "q": "What is O(1) time complexity?", "expected_intent_part": None},
    {"cat": "Linguistic Edge Case", "q": "How do pointers work in C++?", "expected_intent_part": None},
    {"cat": "Linguistic Edge Case", "q": "Multi-line query:\nWhat is binary search?\nExplain its complexity", "expected_intent_part": "binary_search"},
    {"cat": "Linguistic Edge Case", "q": "Single char 'a'", "expected_intent_part": None},
    {"cat": "Linguistic Edge Case", "q": "naïve string matching with accents", "expected_intent_part": None},

    # Category 4: Disambiguation Trigger Check
    {"cat": "Disambiguation", "q": "linked list", "expected_intent_part": None},
    {"cat": "Disambiguation", "q": "binary tree", "expected_intent_part": None},
    {"cat": "Disambiguation", "q": "sorting algorithm", "expected_intent_part": None},
    {"cat": "Disambiguation", "q": "stack vs queue", "expected_intent_part": None},
]

def run_suite():
    results = []
    print(f"Executing {len(test_suite)} tests against {BASE_URL}...")
    
    for i, t in enumerate(test_suite):
        q = t["q"]
        cat = t["cat"]
        expected_part = t["expected_intent_part"]
        t0 = time.time()
        try:
            r = requests.post(f"{BASE_URL}/predict", json={"text": q, "use_history": False, "top_k": 3}, timeout=10)
            lat = (time.time() - t0) * 1000
            if r.status_code == 200:
                data = r.json()
                intent = data.get("intent", "")
                conf = data.get("confidence", 0)
                resp = data.get("response", "")
                fallback_opts = data.get("fallback_options")
                
                passed = True
                if expected_part:
                    passed = (expected_part.lower() in intent.lower()) and conf >= 0.50
                
                res_item = {
                    "index": i + 1,
                    "category": cat,
                    "query": q,
                    "status_code": 200,
                    "intent": intent,
                    "confidence": round(conf, 4),
                    "resolution_type": data.get("resolution_type"),
                    "latency_ms": round(lat, 2),
                    "has_fallback_options": bool(fallback_opts),
                    "fallback_options": fallback_opts,
                    "response_preview": resp[:80] + ("..." if len(resp) > 80 else ""),
                    "passed": passed
                }
                results.append(res_item)
                status_str = "PASS" if passed else "WARN/FAIL"
                print(f"[{status_str}] [{cat}] '{q}' -> Intent: {intent} (conf: {conf:.2f}, {lat:.1f}ms)")
            else:
                results.append({
                    "index": i + 1,
                    "category": cat,
                    "query": q,
                    "status_code": r.status_code,
                    "passed": False,
                    "error": r.text
                })
                print(f"[FAIL] [{cat}] '{q}' -> HTTP {r.status_code}: {r.text[:60]}")
        except Exception as e:
            results.append({
                "index": i + 1,
                "category": cat,
                "query": q,
                "passed": False,
                "error": str(e)
            })
            print(f"[ERROR] [{cat}] '{q}' -> {e}")

    # Concurrency Test (10 parallel requests)
    print("\n--- Concurrency Burst Test (10 parallel requests) ---")
    concurrent_queries = ["What is binary search?", "How to reverse linked list?", "Explain Dijkstra", "What is merge sort?"] * 3
    t_start = time.time()
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        futures = [executor.submit(requests.post, f"{BASE_URL}/predict", json={"text": q, "use_history": False}, timeout=10) for q in concurrent_queries]
        c_results = [f.result() for f in futures]
    t_total = (time.time() - t_start) * 1000
    avg_lat = t_total / len(concurrent_queries)
    all_200 = all(r.status_code == 200 for r in c_results)
    print(f"Concurrent burst: 12 requests in {t_total:.1f}ms (Avg {avg_lat:.1f}ms/req), All HTTP 200: {all_200}")

    with open("artifacts/dataset_benchmark_results.json", "w") as f:
        json.dump({"results": results, "concurrency": {"total_ms": t_total, "all_200": all_200}}, f, indent=2)

if __name__ == "__main__":
    run_suite()