o
    پi                     @   sR   d Z ddlZddlmZmZ ddlmZ ddlmZm	Z	m
Z
mZ G dd dZdS )z6Utilities for running stress tests with bench_serving.    N)ListOptional)kill_process_tree)!DEFAULT_TIMEOUT_FOR_SERVER_LAUNCHis_in_cipopen_launch_serverwrite_github_step_summaryc                   @   s  e Zd ZdZ		d(dedededefdd	Z	
	d)dedededededee	e  de	e fddZ
	d*de	e dee dejfddZ			d+dededededee	e  dee	e  dee defddZdedededdfdd Zded!eddfd"d#Zd,d$d%Zdefd&d'ZdS )-StressTestRunnera  Helper class for running stress tests with bench_serving.

    This class encapsulates common patterns for stress testing, including:
    - Server launch and cleanup
    - Stress test command construction and execution
    - Result collection and reporting
    P  -   	test_namebase_urlnum_promptsduration_minutesc                 C   s*   || _ || _|| _|| _d| d| _dS )a(  Initialize the stress test runner.

        Args:
            test_name: Name of the test (used for reporting)
            base_url: Base URL for the server
            num_prompts: Number of prompts to send (default: 50000)
            duration_minutes: Timeout in minutes (default: 45)
        z## 
N)r   r   r   r   full_report)selfr   r   r   r    r   R/home/ubuntu/.local/lib/python3.10/site-packages/sglang/test/ci/ci_stress_utils.py__init__   s
   zStressTestRunner.__init__皙?N
model_pathrandom_input_lenrandom_output_lenoutput_filerandom_range_ratio
extra_argsreturnc                 C   sP   dddddd| j ddd	t|d
t|dt|dt| jd|g}|r&|| |S )a  Build the bench_serving stress test command.

        Args:
            model_path: Path to the model
            random_input_len: Random input length
            random_output_len: Random output length
            output_file: Output JSONL file path
            random_range_ratio: Random range ratio (default: 0.2)
            extra_args: Optional extra arguments

        Returns:
            List of command arguments ready for subprocess.run()
        python3z-mzsglang.bench_servingz	--backendz
sglang-oaiz
--base-urlz--dataset-namerandomz--random-input-lenz--random-output-lenz--random-range-ratioz--num-promptsz--output-file)r   strr   extend)r   r   r   r   r   r   r   commandr   r   r   build_stress_test_command-   s.   
z*StressTestRunner.build_stress_test_commandr"   timeout_minutesc                 C   st   |p| j d }td| d tdd|  tj|dd|d}|jdkr8td	 t|j td
|j |S )zExecute the stress test command with timeout.

        Args:
            command: Command to execute
            timeout_minutes: Timeout in minutes (uses class default if None)

        Returns:
            CompletedProcess result
        <   z&Running stress test command (timeout: zs):z   T)capture_outputtexttimeoutr   zError running stress test:z$Stress test failed with return code )r   printjoin
subprocessrun
returncodestderrRuntimeError)r   r"   r$   r)   resultr   r   r   run_stress_test_command^   s   


z(StressTestRunner.run_stress_test_commandserver_argsextra_bench_argsc              
   C   s8  t dd  t d|  t d|  t d|  t d| j  t d d t|| j|p2g td}z[z+| j|||||d}	| |	| t d	|  | ||| W W t d
 t|j	 dS  t
y }
 z#t d| d|
  | |t|
 W Y d}
~
W t d
 t|j	 dS d}
~
ww t d
 t|j	 w )a  Run a complete stress test for a single model with server management.

        This method handles:
        - Server launch and cleanup
        - Stress test command construction and execution
        - Error handling and reporting

        Args:
            model_path: Path to the model
            random_input_len: Random input length
            random_output_len: Random output length
            output_file: Output JSONL file path
            server_args: Arguments to pass to server launch
            extra_bench_args: Extra arguments for bench_serving
            timeout_minutes: Timeout in minutes (uses class default if None)

        Returns:
            True if successful, False otherwise
        r   z<============================================================zStarting stress test for: zInput length: zOutput length: zNum prompts: )modelr   
other_argsr)   )r   z(
Stress test completed successfully for zCleaning up server process...Tz
Stress test failed for z: NF)r*   r   r   r   r   r#   r2   _add_success_to_reportr   pid	Exception_add_failure_to_reportr    )r   r   r   r   r   r3   r4   r$   processr"   er   r   r   run_stress_test_for_model{   sH   	z*StressTestRunner.run_stress_test_for_model	input_len
output_lenc                 C   s   | dd }|  jd| d7  _|  jd| d7  _|  jd| d7  _|  jd	| d7  _|  jd
| j d7  _|  jd7  _dS )zAdd success entry to report./### z - Success

- Model: ``
z- Input Length: r   z- Output Length: z- Num Prompts: z- Status: **PASSED**

N)splitr   r   )r   r   r>   r?   
model_namer   r   r   r7      s   z'StressTestRunner._add_success_to_reporterrorc                 C   sb   | dd }|  jd| d7  _|  jd| d7  _|  jd7  _|  jd| d	7  _d
S )zAdd failure entry to report.r@   rA   rB   z - Failure
rC   rD   z- Status: **FAILED**
z	- Error: z

N)rE   r   )r   r   rG   rF   r   r   r   r:      s
   z'StressTestRunner._add_failure_to_reportc                 C   s   t  r
t| j dS dS )z2Write the final report to GitHub summary if in CI.N)r   r   r   r   r   r   r   write_final_report   s   z#StressTestRunner.write_final_reportc                 C   s   | j S )zlGet the accumulated full report.

        Returns:
            The full markdown report as a string
        )r   rH   r   r   r   get_full_report   s   z StressTestRunner.get_full_report)r
   r   )r   N)N)NNN)r   N)__name__
__module____qualname____doc__r    intr   floatr   r   r#   r,   CompletedProcessr2   boolr=   r7   r:   rI   rJ   r   r   r   r   r	      s    


2
#

	
F

r	   )rN   r,   typingr   r   sglang.srt.utilsr   sglang.test.test_utilsr   r   r   r   r	   r   r   r   r   <module>   s    