common.py 55.6 KB
Newer Older
Ryan Olson's avatar
Ryan Olson committed
1
#!/usr/bin/env python3
2
# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Ryan Olson's avatar
Ryan Olson committed
3
4
5
# SPDX-License-Identifier: Apache-2.0

"""
6
Common functionality for KVBM determinism tests.
Ryan Olson's avatar
Ryan Olson committed
7

8
9
This module contains shared classes and functions used by both
aggregated and disaggregated determinism tests.
Ryan Olson's avatar
Ryan Olson committed
10
11
"""

12
import importlib.util
Ryan Olson's avatar
Ryan Olson committed
13
import os
14
import re
Ryan Olson's avatar
Ryan Olson committed
15
16
import time
from collections import defaultdict
17
from difflib import SequenceMatcher
18
from enum import Enum
Ryan Olson's avatar
Ryan Olson committed
19
from pathlib import Path
20
from typing import Dict, List, Optional, Tuple
Ryan Olson's avatar
Ryan Olson committed
21
22
23
24

import pytest
import requests

25
26
from tests.utils.port_utils import allocate_port, deallocate_port

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
# ============================================================================
# Module Availability Checks
# ============================================================================


def check_module_available(module_name: str) -> bool:
    """Check if a Python module is available and importable.

    This function first checks if the module spec can be found, then attempts
    to actually import it to ensure it's functional.

    Args:
        module_name: Name of the module to check (e.g., "vllm", "tensorrt_llm")

    Returns:
        True if the module is available and importable, False otherwise

    Example:
        >>> has_vllm = check_module_available("vllm")
        >>> has_trtllm = check_module_available("tensorrt_llm")
    """
    if importlib.util.find_spec(module_name) is None:
        return False
    try:
        importlib.import_module(module_name)
        return True
    except ImportError:
        return False


def calculate_semantic_similarity(text1: str, text2: str) -> float:
    """
    Calculate semantic similarity between two texts using character-level matching.

    Returns a similarity ratio between 0 and 1:
    - 1.0 = exact match
    - 0.8+ = semantically equivalent (minor word changes)
    - <0.7 = significantly different
    """
    matcher = SequenceMatcher(None, text1, text2)
    return matcher.ratio()


def are_semantically_equivalent(
    text1: str,
    text2: str,
    min_similarity: float = 0.75,
    prefix_exact_match_ratio: float = 0.5,
) -> tuple:
    """
    Check if two texts are semantically equivalent.

    Checks both overall similarity and prefix matching to ensure early tokens
    are deterministic (where FP errors haven't accumulated).

    Args:
        text1: First text (baseline)
        text2: Second text (response to compare)
        min_similarity: Minimum similarity ratio (0-1) to consider equivalent
        prefix_exact_match_ratio: Ratio of text that must exactly match from start

    Returns:
        (is_equivalent, similarity_score, reason)
    """
    # Calculate overall similarity
    similarity = calculate_semantic_similarity(text1, text2)

    # Check prefix match (first X% must be exact to avoid early divergence)
    prefix_len = int(min(len(text1), len(text2)) * prefix_exact_match_ratio)
    prefix_match = text1[:prefix_len] == text2[:prefix_len]

    if similarity >= min_similarity:
        if prefix_match:
            return (
                True,
                similarity,
                f"Semantically equivalent ({similarity:.1%} similar, prefix matches)",
            )
        else:
            return (
                False,
                similarity,
                f"High similarity but early divergence (prefix mismatch at {prefix_len} chars)",
            )
    else:
        return (False, similarity, f"Low similarity ({similarity:.1%})")


def load_prompt_from_file(prompt_path: Path) -> Optional[str]:
    """Load and preprocess prompt from file.

    Args:
        prompt_path: Path to the prompt file

    Returns:
        Cleaned prompt content, or None if file doesn't exist
    """
    if not prompt_path.exists():
        return None

    with open(prompt_path, "r", encoding="utf-8") as f:
        # Strip SPDX license header lines (start with #)
        lines = f.readlines()
        content_lines = [line for line in lines if not line.startswith("#")]
        return "".join(content_lines).strip()

Ryan Olson's avatar
Ryan Olson committed
133

134
135
136
137
138
def check_logs_for_patterns(
    log_path: Path, patterns: List[str], process_name: str
) -> List[str]:
    """Check log file for specific patterns (errors, warnings, etc.)."""
    findings = []
139

140
141
    if not log_path.exists():
        return [f"{process_name} log file not found at {log_path}"]
142

143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
    try:
        with open(log_path, "r") as f:
            content = f.read()

            for pattern in patterns:
                matches = re.findall(pattern, content, re.IGNORECASE | re.MULTILINE)
                if matches:
                    # Limit to first 3 matches and truncate each to 200 chars
                    for match in matches[:3]:
                        match_str = match if isinstance(match, str) else str(match)
                        findings.append(f"{process_name}: {match_str[:200]}")
    except Exception as e:
        findings.append(f"Error reading {process_name} log: {e}")

    return findings


class ApiTester:
161
162
163
164
165
    """Base class for making API requests to LLM endpoints.

    Note: base_url should be provided explicitly. The default fallback to localhost:8000
    is deprecated and should not be relied upon for new tests.
    """
Ryan Olson's avatar
Ryan Olson committed
166

167
168
169
170
171
    def __init__(
        self,
        base_url: Optional[str] = None,
        model_id: Optional[str] = None,
    ):
172
173
174
175
176
177
178
179
180
        if base_url is None:
            # Fallback chain: env var or error (no hardcoded default)
            base_url = os.environ.get("DYNAMO_API_BASE_URL")
            if base_url is None:
                raise ValueError(
                    "base_url must be provided explicitly or set DYNAMO_API_BASE_URL environment variable. "
                    "Hardcoded default ports are not supported for pytest-xdist compatibility."
                )
        self.base_url = base_url
181
182
183
        self.model_id = model_id or os.environ.get(
            "KVBM_MODEL_ID", "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
        )
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

    def make_request(
        self,
        content: str,
        max_tokens: Optional[int] = None,
        temperature: float = 0.0,
        seed: int = 42,
        **kwargs,
    ) -> str:
        """Make API request and return completion text."""
        payload = {
            "model": self.model_id,
            "messages": [
                {"role": "user", "content": content},
            ],
            "stream": False,
            "temperature": temperature,
            "seed": seed,
        }

        # Add max_tokens with appropriate key based on kwargs or defaults
        if max_tokens is not None:
            payload["max_tokens"] = max_tokens
        elif "max_completion_tokens" in kwargs:
            payload["max_completion_tokens"] = kwargs.pop("max_completion_tokens")
        else:
            payload["max_completion_tokens"] = int(
                os.environ.get("KVBM_MAX_TOKENS", "48")
            )

        # Add any additional kwargs
        payload.update(kwargs)

        response = requests.post(
            f"{self.base_url}/v1/chat/completions",
            headers={"Content-Type": "application/json"},
            json=payload,
            timeout=int(os.environ.get("KVBM_HTTP_TIMEOUT", "30")),
        )
        response.raise_for_status()

        data = response.json()
        return data["choices"][0]["message"]["content"]

    def send_chat_request(
        self,
        messages: List[dict],
        max_tokens: int = 50,
        temperature: float = 0.0,
        seed: int = 42,
    ) -> dict:
        """Send a chat request and return full response JSON."""
        url = f"{self.base_url}/v1/chat/completions"
        payload = {
            "model": self.model_id,
            "messages": messages,
            "max_tokens": max_tokens,
            "temperature": temperature,
            "seed": seed,
        }

        response = requests.post(url, json=payload, timeout=30)
        response.raise_for_status()
        return response.json()


class ServerType(str, Enum):
    vllm = "vllm"
    trtllm = "trtllm"


class DeterminismTester(ApiTester):
    """Test class for model determinism validation."""

    def __init__(
        self,
        base_url: Optional[str] = None,
        model_id: Optional[str] = None,
        server_type: Optional[str] = ServerType.vllm,
    ):
        super().__init__(base_url, model_id)
265
        self.server_type = server_type
Ryan Olson's avatar
Ryan Olson committed
266
267

        self.shakespeare_file = Path("t8.shakespeare.txt")
268
        self.max_iterations = int(os.environ.get("KVBM_MAX_ITERATIONS", "100"))
Ryan Olson's avatar
Ryan Olson committed
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
        self.word_count = int(os.environ.get("KVBM_WORD_COUNT", "200"))

        # Test intervals
        self.control_interval = int(os.environ.get("KVBM_CONTROL_INTERVAL", "10"))
        self.shakespeare_interval = int(
            os.environ.get("KVBM_SHAKESPEARE_INTERVAL", "1")
        )
        self.random_interval = int(os.environ.get("KVBM_RANDOM_INTERVAL", "7"))

        # Response storage
        self.control_responses: Dict[int, List[str]] = defaultdict(list)
        self.shakespeare_responses: Dict[int, List[str]] = defaultdict(list)
        self.random_responses: Dict[int, List[str]] = defaultdict(list)

        # Control sequences
        self.control_sequences = [
            "Hello world",
            "The quick brown fox jumps over the lazy dog. This is a standard pangram that contains all letters of the alphabet.",
            "Find light in the beautiful sea, I choose to be happy, You and I, you and I, we are like a beautiful melody that never ends, dancing through the night with stars as our companions, whispering secrets to the wind as we journey through life together, hand in hand, heart to heart, forever and always.",
            "The advancement of technology has fundamentally transformed the way we live, work, and communicate in the modern world. From the invention of the printing press to the development of the internet, each technological breakthrough has opened new possibilities and created unprecedented opportunities for human progress. Today, artificial intelligence and machine learning are reshaping industries, healthcare, education, and countless other fields, promising to solve complex problems and improve the quality of life for people around the globe.",
            "In the heart of Eldoria, an ancient land of boundless magic and mysterious creatures, lies the long-forgotten city of Aeloria. Once a beacon of knowledge and power, Aeloria was buried beneath the shifting sands of time, lost to the world for centuries. You are an intrepid explorer, known for your unparalleled curiosity and courage, who has stumbled upon an ancient map hinting at ests that Aeloria holds a secret so profound that it has the potential to reshape the very fabric of reality. Your journey will take you through treacherous deserts, enchanted forests, and across perilous mountain ranges. Your Task: Character Background: Develop a detailed background for your character. Describe their motivations for seeking out Aeloria, their skills and weaknesses, and any personal connections to the ancient city or its legends. Are they driven by a quest for knowledge, a search for lost familt clue is hidden.",
            "The human brain is the most complex organ in the known universe, containing approximately 86 billion neurons, each connected to thousands of others through intricate networks of synapses. This biological supercomputer processes information at speeds that would make even the most advanced artificial intelligence systems seem primitive by comparison. Every thought, memory, emotion, and decision we make is the result of electrical and chemical signals traveling through this vast neural network. The brain's ability to learn, adapt, and create is unmatched by any machine we have ever built. It can recognize patterns in milliseconds, solve complex problems through intuition, and generate creative ideas that have never existed before. Yet despite our incredible advances in neuroscience, we still understand only a fraction of how this remarkable organ truly works. The mysteries of consciousness, memory formation, and the nature of human intelligence continue to challenge the brightest minds in science and philosophy.",
        ]

        # Random sequences
        self.random_sequences = [
            "Coffee is ready",
            "The cat sat on the mat while the dog slept peacefully in the corner, creating a perfect picture of domestic tranquility that warmed the heart of anyone who witnessed this simple moment of harmony between two natural enemies turned friends.",
            "Mathematics is the language of the universe, and numbers are its alphabet. Through the elegant dance of equations and the symphony of algorithms, we unlock the secrets of nature's most profound mysteries. From the simple beauty of prime numbers to the complex elegance of calculus, mathematics provides us with the tools to understand everything from the smallest subatomic particles to the vast expanse of galaxies stretching across the cosmic void.",
            "A journey of a thousand miles begins with a single step, as the ancient Chinese proverb wisely reminds us. This timeless wisdom speaks to the fundamental truth that every great achievement, every monumental discovery, and every life-changing transformation starts with that crucial moment of decision - the moment when we choose to take action instead of remaining in the comfort of inaction. Whether it's learning a new skill, starting a business, writing a novel, or embarking on a spiritual quest, the path to success is paved with countless small steps, each one building upon the last, until we find ourselves transformed by the journey itself.",
            "Technology evolves rapidly, but human nature remains constant through the ages. Despite the incredible advances in artificial intelligence, virtual reality, and biotechnology, the fundamental desires, fears, and aspirations that drive human behavior have remained remarkably consistent throughout history. We still seek connection, meaning, and purpose in our lives. We still fear the unknown and crave security. We still dream of a better future and work to create it for ourselves and our loved ones. This paradox - the ever-changing nature of our tools and the unchanging nature of our hearts - is perhaps the most fascinating aspect of the human condition, reminding us that while we may build increasingly sophisticated machines, we remain fundamentally human in our core essence.",
        ]

    def download_shakespeare_text(self):
        """Download Shakespeare text if not present."""
        if not self.shakespeare_file.exists():
            print("Downloading Shakespeare text...")
            import urllib.request

            url = os.environ.get(
                "KVBM_SHAKESPEARE_URL",
                "https://ocw.mit.edu/ans7870/6/6.006/s08/lecturenotes/files/t8.shakespeare.txt",
            )
            urllib.request.urlretrieve(url, self.shakespeare_file)

            # Remove double newlines
            with open(self.shakespeare_file, "r", encoding="utf-8") as f:
                content = f.read()
            content = content.replace("\n\n", "")
            with open(self.shakespeare_file, "w", encoding="utf-8") as f:
                f.write(content)

321
    # Inherited from ApiTester, but override to add determinism-specific parameters
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
    def make_request(
        self,
        content: str,
        max_tokens: Optional[int] = None,
        temperature: float = 0.0,
        seed: int = 42,
        **kwargs,
    ) -> str:
        """Make API request and return completion text with determinism settings."""
        # Use determinism-specific defaults
        if max_tokens is None:
            max_tokens = int(os.environ.get("KVBM_MAX_TOKENS", "48"))
        if seed == 42:  # Default seed, use env override
            seed = int(os.environ.get("KVBM_SEED", "42"))

337
338
        top_k = -1
        if check_module_available("tensorrt_llm"):
339
            top_k = 1  # TensorRT-LLM requires top_k>=0 and dynamo frontend does not support top_k=0
340
341
        # For determinism: use temperature=0 which should trigger greedy decoding in vLLM
        # Setting top_p=1.0 and top_k=-1 to avoid any sampling/filtering
342
343
344
345
346
        return super().make_request(
            content,
            max_tokens=max_tokens,
            temperature=temperature,
            seed=seed,
347
348
            top_p=1.0,  # No nucleus sampling filtering
            top_k=top_k,  # No top-k filtering
349
            **kwargs,
Ryan Olson's avatar
Ryan Olson committed
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
        )

    def warmup_server(self):
        """Perform comprehensive server warmup with all test prompts."""
        print("=" * 70)
        print("PERFORMING COMPREHENSIVE SERVER WARMUP")
        print("=" * 70)
        print(
            "Sending all control, Shakespeare, and random prompts to warm up the server..."
        )

        # Warmup with all control sequences
        print("Warming up with control sequences...")
        for i, control_seq in enumerate(self.control_sequences):
            print(f"  Warmup control sequence {i + 1}: {control_seq[:50]}...")
            try:
                self.make_request(control_seq)
            except Exception as e:
                print(f"  Warning: Warmup request failed: {e}")

        # Warmup with Shakespeare sequences that will be used in testing
        print("Warming up with Shakespeare sequences...")
        shakespeare_count = self.max_iterations // self.shakespeare_interval
        for seq_idx in range(1, shakespeare_count + 1):
            start_word = (seq_idx - 1) * self.word_count
            content = self.get_shakespeare_content(start_word)

            if content:
                print(
                    f"  Warmup Shakespeare sequence {seq_idx} (words {start_word}-{start_word + self.word_count - 1})..."
                )
                try:
                    self.make_request(content)
                except Exception as e:
                    print(f"  Warning: Warmup request failed: {e}")

        # Warmup with all random sequences
        print("Warming up with random sequences...")
        for i, random_seq in enumerate(self.random_sequences):
            print(f"  Warmup random sequence {i + 1}: {random_seq[:50]}...")
            try:
                self.make_request(random_seq)
            except Exception as e:
                print(f"  Warning: Warmup request failed: {e}")

        print("Server warmup completed!")
        print("=" * 70)

    def get_shakespeare_content(self, start_word: int) -> str:
        """Get Shakespeare content starting from a specific word."""
        with open(self.shakespeare_file, "r", encoding="utf-8") as f:
            words = f.read().split()

        end_word = min(start_word + self.word_count, len(words))
        return " ".join(words[start_word:end_word])

    def run_test_iterations(self):
        """Run the test iterations with comprehensive warmup."""
        # Perform initial warmup before testing
        self.warmup_server()

        for iteration in range(1, self.max_iterations + 1):
            print(f"Iteration {iteration}/{self.max_iterations}")

            # Control sequence test
            if iteration % self.control_interval == 0:
                control_idx = (iteration // self.control_interval - 1) % len(
                    self.control_sequences
                )
                control_content = self.control_sequences[control_idx]

                print(
                    f"  Running control sequence {control_idx + 1}: {control_content[:50]}..."
                )
                completion = self.make_request(control_content)
                self.control_responses[control_idx].append(completion)
                print(f"  Response: {completion}")

            # Shakespeare sequence test
            if iteration % self.shakespeare_interval == 0:
                start_word = (
                    iteration // self.shakespeare_interval - 1
                ) * self.word_count
                content = self.get_shakespeare_content(start_word)

                if content:
                    shakespeare_idx = iteration // self.shakespeare_interval - 1
                    print(
                        f"  Running Shakespeare sequence {shakespeare_idx + 1} (words {start_word}-{start_word + self.word_count - 1})..."
                    )
                    completion = self.make_request(content)
                    self.shakespeare_responses[shakespeare_idx].append(completion)
                    print(f"  Response: {completion}")

            # Random sequence test
            if iteration % self.random_interval == 0:
                random_idx = (iteration // self.random_interval - 1) % len(
                    self.random_sequences
                )
                random_content = self.random_sequences[random_idx]

                print(
                    f"  Running random sequence {random_idx + 1}: {random_content[:50]}..."
                )
                completion = self.make_request(random_content)
                self.random_responses[random_idx].append(completion)
                print(f"  Response: {completion}")

    def analyze_responses(
        self, responses: Dict[int, List[str]], sequence_type: str
    ) -> Tuple[int, int]:
        """Analyze responses for determinism."""
        passed = 0
        failed = 0

        print(f"\n=== {sequence_type.upper()} SEQUENCES ===")

        for idx, response_list in responses.items():
            if not response_list:
                continue

            print(f"\n{sequence_type} sequence {idx + 1}:")
            print(f"Total responses: {len(response_list)}")

            if len(response_list) == 1:
                print("Single response - cannot check determinism")
                continue

            reference = response_list[0]
            differences = 0

            print(f"Reference response: {reference}")

            for i, response in enumerate(response_list[1:], 2):
                if response == reference:
                    print(f"Response {i}: MATCHES reference")
                else:
                    print(f"Response {i}: DIFFERS from reference")
                    print(f"  Expected: {reference}")
                    print(f"  Got:      {response}")
                    differences += 1

            if differences == 0:
                print(" ALL RESPONSES IDENTICAL - DETERMINISTIC")
                passed += 1
            else:
                print(f" {differences} DIFFERENCES DETECTED - NON-DETERMINISTIC")
                failed += 1

        return passed, failed


@pytest.fixture(scope="function")
503
def tester(llm_server):
Ryan Olson's avatar
Ryan Olson committed
504
    """Create determinism tester bound to the running server's base URL."""
505
506
507
    t = DeterminismTester(
        base_url=llm_server.base_url, server_type=llm_server.server_type
    )
Ryan Olson's avatar
Ryan Olson committed
508
509
510
511
    t.download_shakespeare_text()
    return t


512
@pytest.fixture(scope="function")
513
def llm_server_kvbm(request, runtime_services_dynamic_ports):
514
515
516
517
    """Start LLM server with configurable cache sizes for KVBM testing.

    Usage in test files:
        @pytest.mark.parametrize("llm_server_kvbm",
518
            [{"cpu_blocks": 100, "gpu_blocks": 10, "model": "Qwen/Qwen3-0.6B"}], indirect=True)
519
520
521
522
523
524
525
526
        def test_example(llm_server_kvbm):
            ...
    """
    import os
    import time

    from tests.utils.managed_process import ManagedProcess

527
    # Get configuration from request.param
528
529
530
    params = getattr(request, "param", {})
    cpu_blocks = params.get("cpu_blocks", 100)
    gpu_blocks = params.get("gpu_blocks", 10)
531
532
533
534
    model = params.get(
        "model",
        os.environ.get("KVBM_MODEL_ID", "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"),
    )
535

536
537
538
    # Unpack NATS and etcd processes from runtime_services_dynamic_ports
    nats_process, etcd_process = runtime_services_dynamic_ports

539
    # Detect available server type
540
    if check_module_available("vllm"):
541
        server_type = ServerType.vllm
542
    elif check_module_available("tensorrt_llm"):
543
544
545
546
547
548
549
        server_type = ServerType.trtllm
        pytest.skip("TensorRT-LLM tests are disabled for this test")
    else:
        pytest.skip(
            "Neither vllm nor tensorrt_llm module is available in the current environment."
        )

550
551
552
553
554
555
556
557
558
559
560
561
    # Use dynamic port allocation to avoid conflicts (pytest-xdist safe)
    # Note: ZMQ ports are allocated in lower range due to i16 limit (max 32767) in port_utils
    port = allocate_port(start_port=8000)
    metrics_port = allocate_port(start_port=6880)
    zmq_pub_port = allocate_port(start_port=20001)  # Lower range instead of 56001
    zmq_ack_port = allocate_port(start_port=20002)  # Lower range instead of 56002
    print(
        f"Allocated dynamic ports - vLLM: {port}, Metrics: {metrics_port}, "
        f"ZMQ Pub: {zmq_pub_port}, ZMQ Ack: {zmq_ack_port}, "
        f"NATS: {nats_process.port}, etcd: {etcd_process.port}"
    )

562
    # Build vLLM command
563
564
565
566
567
568
    # TODO: For parallel execution on single GPU with pytest-xdist, add dynamic GPU memory allocation:
    #   1. Detect parallel execution: worker_count = os.environ.get("PYTEST_XDIST_WORKER_COUNT")
    #   2. Calculate fraction: gpu_memory_fraction = 0.85 / int(worker_count) if worker_count else 0.9
    #   3. Add to command: "--gpu-memory-utilization", str(gpu_memory_fraction)
    #   Example: 2 workers → 42.5% each, 3 workers → 28.3% each
    #   Trade-off: Smaller GPU memory per worker = smaller KV cache = more CPU offloads
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
    command = [
        "vllm",
        "serve",
        "--block-size",
        "16",
        "--port",
        str(port),
        "--kv-transfer-config",
        '{"kv_connector":"DynamoConnector","kv_role":"kv_both", "kv_connector_module_path": "kvbm.vllm_integration.connector"}',
        model,
        "--max-model-len",
        "8000",  # Required to fit on L4 GPU with smaller models
    ]

    # GPU blocks override
    if gpu_blocks is not None:
        command.extend(["--num-gpu-blocks-override", str(gpu_blocks)])

587
588
589
590
591
592
    # Chunked prefill configuration
    if "max_num_batched_tokens" in params:
        command.extend(
            ["--max-num-batched-tokens", str(params["max_num_batched_tokens"])]
        )

593
    # Set up environment
594
    # Note: NATS_SERVER and ETCD_ENDPOINTS are already set by runtime_services_dynamic_ports fixture
595
596
597
598
599
600
601
    env = os.environ.copy()
    env.update(
        {
            "RUST_BACKTRACE": "1",
            "VLLM_SERVER_DEV_MODE": "1",
            "DYN_LOG": "debug",
            "DYN_KVBM_METRICS": "true",
602
603
604
605
606
            "DYN_KVBM_METRICS_PORT": str(metrics_port),
            "DYN_KVBM_LEADER_ZMQ_PUB_PORT": str(zmq_pub_port),
            "DYN_KVBM_LEADER_ZMQ_ACK_PORT": str(zmq_ack_port),
            # DynamoConnector will use NATS_SERVER and ETCD_ENDPOINTS from environment
            # (already set by runtime_services_dynamic_ports fixture)
607
608
609
610
611
612
613
614
615
616
617
        }
    )

    # CPU cache blocks override via env
    if cpu_blocks is not None:
        env["DYN_KVBM_CPU_CACHE_OVERRIDE_NUM_BLOCKS"] = str(cpu_blocks)

    # Start server with ManagedProcess
    timeout = int(os.environ.get("KVBM_SERVER_START_TIMEOUT", "600"))
    log_dir = f"{request.node.name}_vllm"

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
    # Port-specific cleanup: Only kill vLLM processes using OUR allocated ports.
    # This makes the fixture safe for pytest-xdist parallel execution.
    # Check for processes listening on our specific ports before starting.
    import psutil

    from tests.utils.managed_process import terminate_process_tree

    _logger = __import__("logging").getLogger(__name__)
    for check_port in [port, metrics_port]:
        for proc in psutil.process_iter(["pid", "name", "cmdline"]):
            try:
                # Check if process is listening on our port
                connections = proc.connections(kind="inet")
                for conn in connections:
                    if conn.laddr.port == check_port and conn.status == "LISTEN":
                        _logger.info(
                            f"Terminating existing process {proc.name()} (PID {proc.pid}) "
                            f"listening on port {check_port}"
                        )
                        terminate_process_tree(proc.pid, _logger)
                        break
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
            except Exception:
                pass  # Continue cleanup even if one process fails

644
    # SAFETY: Do NOT use terminate_all_matching_process_names=True or stragglers=["vllm"] here.
645
646
    # Those kill ALL vLLM processes system-wide, breaking parallel test execution.
    # Port-based cleanup above is targeted and xdist-safe.
647
648
649
    with ManagedProcess(
        command=command,
        env=env,
650
        health_check_ports=[port, metrics_port],  # vLLM server + KVBM metrics
651
652
        timeout=timeout,
        display_output=True,
653
        terminate_all_matching_process_names=False,  # Port-based cleanup done above instead
654
655
        stragglers=[],  # Empty - we handle cleanup manually per port
        straggler_commands=[],  # Empty - we handle cleanup manually per port
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
        log_dir=log_dir,
    ) as proc:
        # Give KVBM connector extra time to fully initialize
        print("Waiting 5 seconds for KVBM connector to fully initialize...")
        time.sleep(5)

        # Create wrapper object for compatibility with existing test code
        class ServerWrapper:
            """Wrapper to maintain compatibility with LLMServerManager interface."""

            def __init__(self):
                self.base_url = f"http://localhost:{port}"
                self.server_type = server_type
                self.cpu_cache_blocks = cpu_blocks
                self.gpu_cache_blocks = gpu_blocks
                self.port = port
672
                self.metrics_port = metrics_port
673
674
                self.proc = proc

675
676
677
678
679
680
681
682
683
684
685
686
        try:
            yield ServerWrapper()
        finally:
            # Clean up allocated ports
            deallocate_port(port)
            deallocate_port(metrics_port)
            deallocate_port(zmq_pub_port)
            deallocate_port(zmq_ack_port)
            print(
                f"Deallocated ports - vLLM: {port}, Metrics: {metrics_port}, "
                f"ZMQ Pub: {zmq_pub_port}, ZMQ Ack: {zmq_ack_port}"
            )
687
688


Ryan Olson's avatar
Ryan Olson committed
689
690
691
class TestDeterminism:
    """Test class for determinism validation."""

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
    def _establish_baseline(self, tester, prompt: str, max_tokens: int) -> str:
        """Establish baseline response: warmup -> clear cache -> baseline."""
        print("\n" + "=" * 70)
        print("ESTABLISHING BASELINE (warmup -> clear cache -> baseline)")
        print("=" * 70)

        # Step 1: Warmup
        print("\nStep 1: Warmup request...")
        try:
            warmup_response = tester.make_request(
                prompt, max_tokens=max_tokens, temperature=0, seed=42
            )
            print(f"Warmup response: {warmup_response}")
        except Exception as e:
            pytest.fail(f"Warmup request failed: {e}")

        # Step 2: Clear cache
        print("\nStep 2: Clearing cache...")
        try:
            tester.reset_prefix_cache()
            print("Cache cleared successfully")
        except Exception as e:
            print(f"Warning: Cache reset failed: {e}")

        # Step 3: Baseline request
        print("\nStep 3: Baseline request (after cache clear)...")
        try:
            baseline_response = tester.make_request(
                prompt, max_tokens=max_tokens, temperature=0, seed=42
            )
            print(f"Baseline response: {baseline_response}")
            print("\n✓ Baseline established")
            print("=" * 70)
            return baseline_response
        except Exception as e:
            pytest.fail(f"Baseline request failed: {e}")

    def _start_benchmark(self, llm_server) -> tuple:
        """Start vllm bench in background.

        Returns:
            tuple: (process, file_handle, log_path)
        """
        import subprocess

        model = os.environ.get(
            "KVBM_MODEL_ID", "deepseek-ai/DeepSeek-R1-Distill-Llama-8B"
        )
        bench_cmd = [
            "vllm",
            "bench",
            "serve",
            "--backend",
            "vllm",
            "--model",
            model,
            "--base-url",
            llm_server.base_url,
            "--dataset-name",
            "random",
            "--random-input-len",
            "4000",
            "--random-output-len",
            "180",
            "--max-concurrency",
            "7",
            "--num-prompts",
            "2000",
        ]

        print(f"\nStarting vllm bench: {' '.join(bench_cmd)}")
        bench_log = os.path.join(str(Path(".")), "vllm_bench_semantic.log")
        bench_file = open(bench_log, "w")
        bench_process = subprocess.Popen(
            bench_cmd,
            stdout=bench_file,
            stderr=subprocess.STDOUT,
            env=os.environ.copy(),
        )
        return bench_process, bench_file, bench_log

773
774
775
    def _wait_for_benchmark_activity(
        self, metrics_port: int, initial_offload: int
    ) -> bool:
776
777
778
        """Wait for benchmark to start creating offload activity.

        Args:
779
            metrics_port: Port number for the KVBM metrics endpoint
780
781
782
783
784
785
786
787
788
789
790
791
792
            initial_offload: Initial offload block count to compare against

        Returns:
            bool: True if benchmark activity detected, False otherwise
        """
        print("\nWaiting for benchmark to start and create memory pressure...")
        max_wait = int(os.environ.get("KVBM_BENCH_STARTUP_WAIT", "120"))

        for wait_iteration in range(max_wait // 5):
            time.sleep(5)
            elapsed = (wait_iteration + 1) * 5

            try:
793
                current_metrics = fetch_kvbm_metrics(port=metrics_port)
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
                current_offload = current_metrics.get("kvbm_offload_blocks_d2h", 0)

                if current_offload > initial_offload:
                    offload_delta = current_offload - initial_offload
                    print(
                        f" Benchmark activity detected after {elapsed}s ({offload_delta} blocks offloaded)"
                    )
                    print("Waiting additional 10s for benchmark to fully ramp up...")
                    time.sleep(10)
                    return True
                else:
                    print(f" Waiting... ({elapsed}s elapsed, no offload activity yet)")
            except Exception as e:
                print(f"  Waiting... ({elapsed}s elapsed, metrics check failed: {e})")

        print(f" Warning: No benchmark activity detected after {max_wait}s")
        return False

    def _compare_with_baseline(
        self, response: str, baseline: str, min_similarity: float, request_num: int
    ) -> dict:
        """Compare response with baseline. Returns comparison result dict.

        Returns a dict with keys:
        - exact_match: bool - True if response exactly matches baseline
        - semantic_match: bool - True if semantically equivalent (includes exact matches)
        - similarity: float - Similarity score 0.0-1.0
        - reason: str - Explanation of the result
        - diverge_pos: int - Character position where divergence starts (if not matching)
        - approx_token: int - Approximate token position of divergence
        - context_before: str - Text context before divergence point
        - baseline_continues: str - How baseline continues after divergence
        - response_continues: str - How response continues after divergence
        - request_num: int - Request number
        - response: str - Full response text
        - baseline: str - Full baseline text
        """
        result = {
            "request_num": request_num,
            "exact_match": False,
            "semantic_match": False,
            "similarity": 0.0,
            "reason": "",
            "response": response,
            "baseline": baseline,
        }

        # Check for exact match
        if response == baseline:
            result["exact_match"] = True
            result["semantic_match"] = True
            result["similarity"] = 1.0
            result["reason"] = "Exact match"
            return result

        # Check semantic equivalence
        is_equivalent, similarity, reason = are_semantically_equivalent(
            baseline, response, min_similarity=min_similarity
        )
        result["similarity"] = similarity
        result["reason"] = reason

        if is_equivalent:
            result["semantic_match"] = True
        else:
            # Find divergence point for reporting
            diverge_pos = 0
            for j, (c1, c2) in enumerate(zip(baseline, response)):
                if c1 != c2:
                    diverge_pos = j
                    break
            else:
                diverge_pos = min(len(baseline), len(response))

            approx_token = diverge_pos // 4

            result["diverge_pos"] = diverge_pos
            result["approx_token"] = approx_token
            result["context_before"] = baseline[max(0, diverge_pos - 30) : diverge_pos]
            result["baseline_continues"] = baseline[diverge_pos : diverge_pos + 50]
            result["response_continues"] = response[diverge_pos : diverge_pos + 50]

        return result

    def _report_results(
        self,
        num_requests: int,
        exact_matches: int,
        semantic_matches: int,
        mismatches: list,
    ):
        """Print final test results."""
        print("\n" + "=" * 70)
        print("SEMANTIC DETERMINISM RESULTS")
        print("=" * 70)
        print(f"Total requests: {num_requests}")
        print(
            f"Exact matches: {exact_matches}/{num_requests} ({exact_matches/num_requests:.1%})"
        )
        print(
            f"Semantic matches: {semantic_matches}/{num_requests} ({semantic_matches/num_requests:.1%})"
        )
        print(
            f"Semantic divergence: {len(mismatches)}/{num_requests} ({len(mismatches)/num_requests:.1%})"
        )

        if mismatches:
            print(f"\n{'='*70}")
            print(f"NON-DETERMINISTIC RESPONSES ({len(mismatches)} total):")
            print(f"{'='*70}")
            for mismatch in mismatches:
                req_num = mismatch["request_num"]
                if "error" in mismatch:
                    print(f"\nRequest {req_num}: FAILED - {mismatch['error']}")
                else:
                    print(
                        f"\nRequest {req_num}: MISMATCH (similarity: {mismatch.get('similarity', 0):.1%})"
                    )
                    print(f"  Baseline: {mismatch.get('baseline', '')[:150]}...")
                    print(f"  Got:      {mismatch.get('response', '')[:150]}...")

            semantic_success_rate = (semantic_matches / num_requests) * 100
            min_success_rate = 80.0

            print(f"\n{'='*70}")
            print(f"SEMANTIC SUCCESS RATE: {semantic_success_rate:.1f}%")
            print(f"{'='*70}")
            print(f"Failed requests: {[m['request_num'] for m in mismatches]}")

            if semantic_success_rate < min_success_rate:
                pytest.fail(
                    f"Semantic determinism test failed!\n"
                    f"Semantic match rate: {semantic_success_rate:.1f}% (< {min_success_rate:.0f}%)\n"
                    f"This indicates significant non-determinism beyond FP precision effects"
                )
            else:
                print(
                    f"TEST PASSED - SEMANTICALLY DETERMINISTIC (>= {min_success_rate:.0f}%)"
                )
        else:
            print(f"\n{'='*70}")
            print("TEST PASSED - ALL RESPONSES SEMANTICALLY EQUIVALENT")
            print(f"{'='*70}")
            print(
                f"Exact matches: {exact_matches}/{num_requests} ({exact_matches/num_requests:.1%})"
            )

941
    def _show_final_kvbm_stats(self, metrics_port: int, initial_offload: int):
942
943
944
        """Display final KVBM metrics and compare with initial state.

        Args:
945
            metrics_port: Port number for the KVBM metrics endpoint
946
947
948
949
950
951
952
953
954
            initial_offload: Initial offload block count to compare against

        Raises:
            pytest.fail: If no offload activity was detected during the test
        """
        print(f"\n{'='*70}")
        print("FINAL KVBM STATS")
        print(f"{'='*70}")
        try:
955
            final_metrics = fetch_kvbm_metrics(port=metrics_port)
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
            final_offload = final_metrics.get("kvbm_offload_blocks_d2h", 0)
            final_onboard = final_metrics.get("kvbm_onboard_blocks_h2d", 0)

            offload_delta = final_offload - initial_offload
            print(f"Initial offload: {initial_offload} blocks")
            print(f"Final offload:   {final_offload} blocks")
            print(f"Total offloaded: {offload_delta} blocks")
            print(f"Total onboarded: {final_onboard} blocks")

            if offload_delta > 0:
                print(
                    f"\n KVBM offload activity detected: {offload_delta} blocks offloaded"
                )
            else:
                pytest.fail(
                    f"No offload activity detected during test.\n"
                    f"Initial offload: {initial_offload} blocks, Final offload: {final_offload} blocks.\n"
                    f"Test requires memory pressure to properly validate determinism under load."
                )

            if final_onboard > 0:
                print(
                    f" KVBM onboard activity detected: {final_onboard} blocks onboarded"
                )
            else:
                pytest.fail(
                    f"No onboard activity detected during test.\n"
                    f"Final onboard: {final_onboard} blocks.\n"
                    f"Test requires KV cache onboarding to properly validate determinism under load."
                )

        except Exception as e:
            print(f"Could not fetch final metrics: {e}")

    def base_test_spanish_prompt_determinism_under_load(
        self, tester, llm_server, runtime_services, spanish_prompt_path: Path
    ):
        """Base implementation: send Spanish prompt repeatedly while vllm bench runs.

        Tests determinism under high concurrency load. Reproduces bugs where responses
        can become corrupted or non-deterministic under memory pressure.

        Args:
            tester: DeterminismTester instance
            llm_server: LLM server manager
            runtime_services: Runtime services fixture
            spanish_prompt_path: Path to the Spanish prompt file
        """
        import subprocess

        print("\n" + "=" * 70)
        print("DETERMINISM TEST UNDER HIGH CONCURRENCY LOAD")
        print("=" * 70)

        # Load prompt
        prompt = load_prompt_from_file(spanish_prompt_path)
        if prompt is None:
            pytest.fail(f"Prompt not found at {spanish_prompt_path}")

        # Test parameters
        num_requests = int(os.environ.get("KVBM_NUM_ITERATIONS", "15"))
        delay_seconds = int(os.environ.get("KVBM_REQUEST_DELAY", "30"))
        max_tokens = int(os.environ.get("KVBM_MAX_TOKENS", "80"))
        min_similarity = float(os.environ.get("KVBM_MIN_SIMILARITY", "0.75"))

        print("\nTest configuration:")
        print(f"  Requests: {num_requests}")
        print(f"  Delay: {delay_seconds}s")
        print(f"  Max tokens: {max_tokens}")
        print(f"  Min semantic similarity: {min_similarity:.0%}")

        # Establish baseline
        baseline_response = self._establish_baseline(tester, prompt, max_tokens)

        # Start benchmark
        bench_process, bench_file, bench_log = self._start_benchmark(llm_server)

        try:
            # Check initial metrics
            print("\nChecking initial KVBM metrics...")
            try:
1037
                initial_metrics = fetch_kvbm_metrics(port=llm_server.metrics_port)
1038
1039
1040
1041
1042
1043
1044
                initial_offload = initial_metrics.get("kvbm_offload_blocks_d2h", 0)
                print(f"Initial offload: {initial_offload} blocks")
            except Exception as e:
                print(f"Could not fetch initial metrics: {e}")
                initial_offload = 0

            # Wait for benchmark activity
1045
1046
1047
            benchmark_started = self._wait_for_benchmark_activity(
                llm_server.metrics_port, initial_offload
            )
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
            if not benchmark_started:
                pytest.fail(
                    "Benchmark failed to start or create offload activity. "
                    "Test cannot proceed without memory pressure to properly test determinism under load."
                )

            print("Waiting additional 10s for benchmark to fully ramp up...")
            time.sleep(10)

            # Send requests and track results
            print(f"\n{'='*70}")
            print(f"SENDING {num_requests} REQUESTS (comparing against baseline)")
            print(f"{'='*70}")

            responses = []
            mismatches = []
            exact_matches = 0
            semantic_matches = 0

            for i in range(num_requests):
                print(f"\n--- Request {i+1}/{num_requests} ---")

                try:
                    response = tester.make_request(
                        prompt, max_tokens=max_tokens, temperature=0, seed=42
                    )
                    responses.append(response)
                    print(f"Response: {response}")

                    # Compare with baseline
                    comparison = self._compare_with_baseline(
                        response, baseline_response, min_similarity, i + 1
                    )

                    if comparison["exact_match"]:
                        print("✓ EXACT MATCH (100% deterministic)")
                        exact_matches += 1
                        semantic_matches += 1
                    elif comparison["semantic_match"]:
                        print(
                            f"✓ SEMANTICALLY EQUIVALENT ({comparison['similarity']:.1%} similar)"
                        )
                        print(f"  {comparison['reason']}")
                        semantic_matches += 1
                    else:
                        print(
                            f"✗ SEMANTIC DIVERGENCE ({comparison['similarity']:.1%} similar)"
                        )
                        print(f"  {comparison['reason']}")
                        print(
                            f"  Divergence at char {comparison['diverge_pos']} (~token {comparison['approx_token']})"
                        )
                        print(f"  Context before: ...{comparison['context_before']}")
                        print(
                            f"  Baseline continues: {comparison['baseline_continues']}..."
                        )
                        print(
                            f"  Response continues: {comparison['response_continues']}..."
                        )
                        mismatches.append(comparison)

                except Exception as e:
                    print(f"Request failed: {e}")
                    responses.append(None)
                    mismatches.append({"request_num": i + 1, "error": str(e)})

                # Wait before next request
                if i < num_requests - 1:
                    print(f"Waiting {delay_seconds}s...")
                    time.sleep(delay_seconds)

            # Report results
            self._report_results(
                num_requests, exact_matches, semantic_matches, mismatches
            )

            # Show final KVBM stats
1125
            self._show_final_kvbm_stats(llm_server.metrics_port, initial_offload)
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137

        finally:
            print("\nStopping benchmark...")
            try:
                bench_process.terminate()
                bench_process.wait(timeout=10)
            except subprocess.TimeoutExpired:
                bench_process.kill()
                bench_process.wait()
            bench_file.close()
            print(f"Benchmark log: {bench_log}")

1138
1139
1140
    def base_test_determinism_with_cache_reset(
        self, tester, llm_server, runtime_services, success_rate_threshold=1.0
    ):
Ryan Olson's avatar
Ryan Olson committed
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
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
        """Test determinism across cache reset: run test with warmup, reset cache, run again without warmup."""
        print("\n" + "=" * 70)
        print("STARTING DETERMINISM TEST (WITH CACHE RESET)")
        print("=" * 70)

        # Phase 1: Run test with warmup
        print("\n=== PHASE 1: BEFORE CACHE RESET (WITH WARMUP) ===")
        tester.run_test_iterations()

        # Store Phase 1 results
        phase1_control = {k: v.copy() for k, v in tester.control_responses.items()}
        phase1_shakespeare = {
            k: v.copy() for k, v in tester.shakespeare_responses.items()
        }
        phase1_random = {k: v.copy() for k, v in tester.random_responses.items()}

        # Reset cache
        print("\n" + "=" * 50)
        print("RESETTING CACHE")
        print("=" * 50)
        tester.reset_prefix_cache()

        # Clear response storage for Phase 2 (they are defaultdict, so they'll auto-initialize)
        tester.control_responses.clear()
        tester.shakespeare_responses.clear()
        tester.random_responses.clear()

        # Phase 2: Run test without warmup
        print("\n=== PHASE 2: AFTER CACHE RESET (NO WARMUP) ===")
        # Temporarily disable warmup by modifying the method
        original_warmup = tester.warmup_server
        tester.warmup_server = lambda: print(
            "Skipping warmup (testing determinism across cache reset)"
        )

        try:
            tester.run_test_iterations()
        finally:
            # Restore original warmup method
            tester.warmup_server = original_warmup

        # Compare Phase 1 vs Phase 2 results
        print("\n" + "=" * 70)
        print("CROSS-CACHE-RESET DETERMINISM ANALYSIS")
        print("=" * 70)

        total_passed = 0
        total_failed = 0

        # Compare control sequences
        for seq_idx in phase1_control:
            if seq_idx in tester.control_responses:
                phase1_responses = phase1_control[seq_idx]
                phase2_responses = tester.control_responses[seq_idx]

                min_responses = min(len(phase1_responses), len(phase2_responses))
                for i in range(min_responses):
                    if phase1_responses[i] == phase2_responses[i]:
                        total_passed += 1
                        print(f"   Control {seq_idx}, response {i}: DETERMINISTIC")
                    else:
                        total_failed += 1
                        print(f"   Control {seq_idx}, response {i}: NON-DETERMINISTIC")
                        print(f"     Before: {phase1_responses[i]}")
                        print(f"     After:  {phase2_responses[i]}")

        # Compare Shakespeare sequences
        for seq_idx in phase1_shakespeare:
            if seq_idx in tester.shakespeare_responses:
                phase1_responses = phase1_shakespeare[seq_idx]
                phase2_responses = tester.shakespeare_responses[seq_idx]

                min_responses = min(len(phase1_responses), len(phase2_responses))
                for i in range(min_responses):
                    if phase1_responses[i] == phase2_responses[i]:
                        total_passed += 1
                        print(f"   Shakespeare {seq_idx}, response {i}: DETERMINISTIC")
                    else:
                        total_failed += 1
                        print(
                            f"   Shakespeare {seq_idx}, response {i}: NON-DETERMINISTIC"
                        )
                        print(f"     Before: {phase1_responses[i]}")
                        print(f"     After:  {phase2_responses[i]}")

        # Compare random sequences
        for seq_idx in phase1_random:
            if seq_idx in tester.random_responses:
                phase1_responses = phase1_random[seq_idx]
                phase2_responses = tester.random_responses[seq_idx]

                min_responses = min(len(phase1_responses), len(phase2_responses))
                for i in range(min_responses):
                    if phase1_responses[i] == phase2_responses[i]:
                        total_passed += 1
                        print(f"   Random {seq_idx}, response {i}: DETERMINISTIC")
                    else:
                        total_failed += 1
                        print(f"   Random {seq_idx}, response {i}: NON-DETERMINISTIC")
                        print(f"     Before: {phase1_responses[i]}")
                        print(f"     After:  {phase2_responses[i]}")

        # Final assessment
        print("\n" + "=" * 70)
        print("FINAL CROSS-CACHE-RESET DETERMINISM ASSESSMENT")
        print("=" * 70)
        print(f"Total comparisons: {total_passed + total_failed}")
        print(f"Passed (deterministic): {total_passed}")
        print(f"Failed (non-deterministic): {total_failed}")
1250
1251
1252
1253
1254
1255
        success_rate = (
            total_passed / (total_passed + total_failed)
            if total_passed + total_failed > 0
            else 0
        )
        print(f"Success rate: {success_rate:.1%}")
Ryan Olson's avatar
Ryan Olson committed
1256
1257
1258
1259
1260
1261
1262
1263
        print(
            "Test compared responses before cache reset (with warmup) vs after cache reset (no warmup)."
        )

        if total_passed + total_failed == 0:
            pytest.skip("No tests were completed - insufficient data")

        assert (
1264
1265
            success_rate >= success_rate_threshold
        ), f"Model is not deterministic across cache reset: {total_failed} comparisons failed, success rate {success_rate:.1%} lower than expected {success_rate_threshold*100}%"
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300


# ============================================================================
# KVBM Test Helper Functions
# ============================================================================
# Note: KVBM fixtures are in conftest.py for automatic pytest discovery


def parse_kvbm_metrics(metrics_text: str) -> dict:
    """Parse KVBM metrics from Prometheus format.

    Args:
        metrics_text: Raw Prometheus metrics text

    Returns:
        Dictionary mapping metric names to integer values
    """
    metrics = {}
    for line in metrics_text.split("\n"):
        if line.startswith("#") or not line.strip():
            continue
        for metric_name in [
            "kvbm_offload_blocks_d2h",
            "kvbm_onboard_blocks_h2d",
            "kvbm_offload_blocks_h2d",
            "kvbm_onboard_blocks_d2d",
            "kvbm_matched_tokens",
        ]:
            if line.startswith(metric_name + " "):
                parts = line.strip().split()
                if len(parts) >= 2:
                    metrics[metric_name] = int(parts[1])
    return metrics


1301
def fetch_kvbm_metrics(port: int, timeout: int = 10) -> dict:
1302
1303
1304
    """Fetch and parse KVBM metrics from the metrics endpoint.

    Args:
1305
        port: Metrics server port (required for dynamic port allocation)
1306
1307
1308
1309
1310
1311
1312
1313
        timeout: Request timeout in seconds

    Returns:
        Dictionary of parsed metrics

    Raises:
        RuntimeError: If metrics endpoint is unreachable or returns error
    """
1314
1315
1316
1317
1318
1319
1320
1321
    url = f"http://localhost:{port}/metrics"
    try:
        response = requests.get(url, timeout=timeout)
    except requests.exceptions.ConnectionError as err:
        raise RuntimeError(
            f"Metrics endpoint {url} refused connection. "
            f"Check that DYN_KVBM_METRICS_PORT={port} matches the running server."
        ) from err
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
    if response.status_code != 200:
        raise RuntimeError(
            f"Metrics endpoint returned status {response.status_code}. "
            "Metrics server may not have started."
        )
    return parse_kvbm_metrics(response.text)


def assert_deterministic(
    response1: str,
    response2: str,
    test_name: str = "",
    label1: str = "Response 1",
    label2: str = "Response 2",
) -> None:
    """Verify two responses are identical (deterministic).

    Args:
        response1: First response text
        response2: Second response text
        test_name: Name of test for error messages
        label1: Label for first response in output
        label2: Label for second response in output

    Raises:
        pytest.fail: If responses differ
    """
    if response1 == response2:
        print(f" ✓ PASS: {test_name} responses are deterministic")
        print(f"    {label1}: {response1}")
        print(f"    {label2}: {response2}")
    else:
        print(f" ✗ FAIL: {test_name} responses differ")
        print(f"    {label1}: {response1}")
        print(f"    {label2}: {response2}")
        pytest.fail(
            f"{test_name}: Responses not deterministic\n"
            f"{label1}: {response1}\n"
            f"{label2}: {response2}"
        )