-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy patheval_server.py
More file actions
1545 lines (1299 loc) · 57.1 KB
/
eval_server.py
File metadata and controls
1545 lines (1299 loc) · 57.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
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
#!/usr/bin/env python3
"""
Toolathlon Remote Evaluation Server
This server allows remote clients to submit evaluation tasks.
Only one task can run at a time, with IP rate limiting (3 tasks per 24 hours).
"""
# Version control
SERVER_VERSION = "1.2"
SUPPORTED_CLIENT_VERSIONS = ["1.2"] # List of supported client versions
SUPPORTED_WS_CLIENT_VERSIONS = ["1.2"] # List of supported WS client versions
import asyncio
import os
import sys
import time
import uuid
import json
import tarfile
import io
import hashlib
import tempfile
import shutil
import yaml
import signal
from datetime import datetime, timedelta
from pathlib import Path
from typing import Optional, Dict, Any
from collections import defaultdict
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import Response
from pydantic import BaseModel
import uvicorn
def log(msg):
"""Log with timestamp (local time + UTC)"""
local_time = datetime.now().strftime('%H:%M:%S.%f')[:-3]
utc_time = datetime.utcnow().strftime('%H:%M:%S.%f')[:-3]
print(f"[{local_time}][UTC {utc_time}] {msg}", flush=True)
app = FastAPI(title="Toolathlon Eval Server")
# ===== Global State =====
current_job: Optional[Dict[str, Any]] = None
# New structure: ip -> list of job records
# Each record: {"job_id": str, "submitted_at": str, "completed_at": str or None, "duration_seconds": int or None}
ip_submission_history: Dict[str, list] = defaultdict(list)
ws_proxy_process = None # Global WebSocket proxy process
ws_proxy_log_file = None # Global log file handle
transferred_tasks: Dict[str, set] = defaultdict(set) # job_id -> set of transferred task names
# ===== Configuration =====
TIMEOUT_SECONDS = 240 * 60 # 240 minutes
MAX_SUBMISSIONS_PER_IP = 3 # Max number of requests per IP
RATE_LIMIT_HOURS = 24 # Time window for request count limit
MAX_DURATION_MINUTES = 180 # Max cumulative duration in minutes (-1 for unlimited)
MAX_WORKERS = 10 # Will be updated in main
DUMPS_DIR = "./dumps_public_service"
RATE_LIMIT_DATA_FILE = "./dumps_public_service/ip_rate_limit_data.json"
SERVER_PORT = 8080 # Will be updated in main
WS_PROXY_PORT = 8081 # Will be updated in main
# ===== Request/Response Models =====
class SubmitEvaluationRequest(BaseModel):
client_version: Optional[str] = None # Client version for compatibility check (None means old client without version)
mode: str # "public" or "private"
base_url: str
api_key: Optional[str] = None
model_name: str
workers: int = 10
custom_job_id: Optional[str] = None # Allow custom job_id
model_params: Optional[Dict[str, Any]] = None # User-specified model parameters
task_list_content: Optional[str] = None # Task list file content (each line is a task name)
skip_container_restart: bool = False # Skip container restart (for debugging/testing only)
provider: str = "unified" # Model provider (default: "unified" for backward compatibility with v1.0 clients)
ws_client_version: Optional[str] = None # WebSocket client version (required for private mode in v1.2+)
class SubmitEvaluationResponse(BaseModel):
status: str
job_id: str
client_id: Optional[str] = None
message: str
warning: Optional[str] = None # Warning if job_id already exists
# ===== Helper Functions =====
def load_rate_limit_data():
"""Load IP rate limit data from persistent file"""
global ip_submission_history
if not Path(RATE_LIMIT_DATA_FILE).exists():
log(f"No existing rate limit data file found, starting fresh")
return
try:
with open(RATE_LIMIT_DATA_FILE, 'r') as f:
data = json.load(f)
# Convert loaded data back to defaultdict
ip_submission_history = defaultdict(list, data)
# Count total records
total_records = sum(len(records) for records in ip_submission_history.values())
log(f"Loaded rate limit data: {len(ip_submission_history)} IPs, {total_records} total records")
except Exception as e:
log(f"Warning: Failed to load rate limit data: {e}")
ip_submission_history = defaultdict(list)
def save_rate_limit_data():
"""Save IP rate limit data to persistent file"""
try:
# Ensure directory exists
Path(RATE_LIMIT_DATA_FILE).parent.mkdir(parents=True, exist_ok=True)
# Convert defaultdict to regular dict for JSON serialization
data_to_save = dict(ip_submission_history)
with open(RATE_LIMIT_DATA_FILE, 'w') as f:
json.dump(data_to_save, f, indent=2)
log(f"Saved rate limit data: {len(data_to_save)} IPs")
except Exception as e:
log(f"Error: Failed to save rate limit data: {e}")
def load_sensitive_values() -> Dict[str, str]:
"""Load sensitive values from token_key_session.py"""
try:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'configs'))
from token_key_session import all_token_key_session
sensitive_keys = [
'serper_api_key',
'google_cloud_console_api_key',
'gcp_project_id',
'google_client_id',
'google_client_secret',
'google_refresh_token',
'github_token',
'huggingface_token',
'wandb_api_key',
'notion_integration_key',
'notion_integration_key_eval',
'source_notion_page_url',
'eval_notion_page_url',
'snowflake_account',
'snowflake_user',
'snowflake_password'
]
sensitive_values = {}
for key in sensitive_keys:
value = all_token_key_session.get(key)
if value and isinstance(value, str) and len(value) > 0:
sensitive_values[key] = value
return sensitive_values
except Exception as e:
log(f"Warning: Failed to load sensitive values: {e}")
return {}
def load_instance_config() -> Dict[str, str]:
"""Load instance prefix and container runtime from config files"""
config = {
'instance_prefix': '', # Default: no prefix
'container_runtime': 'docker' # Default: docker
}
# Read instance_prefix from ports_config.yaml
try:
ports_config_path = Path(__file__).parent / 'configs' / 'ports_config.yaml'
if ports_config_path.exists():
with open(ports_config_path, 'r') as f:
ports_config = yaml.safe_load(f)
instance_prefix = ports_config.get('instance_prefix', '')
if instance_prefix and isinstance(instance_prefix, str):
config['instance_prefix'] = instance_prefix
log(f"[Server] Loaded instance_prefix from ports_config.yaml: '{instance_prefix}'")
else:
log(f"[Server] Using default instance_prefix (empty)")
except Exception as e:
log(f"Warning: Failed to load instance_prefix from ports_config.yaml: {e}")
# Read container_runtime from global_configs.py
try:
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'configs'))
from global_configs import global_configs
runtime = global_configs.get('podman_or_docker', 'docker')
if runtime in ['docker', 'podman']:
config['container_runtime'] = runtime
log(f"[Server] Loaded container_runtime from global_configs.py: {runtime}")
else:
log(f"Warning: Invalid container_runtime '{runtime}', using default 'docker'")
except Exception as e:
log(f"Warning: Failed to load container_runtime from global_configs.py: {e}")
return config
def anonymize_content(content: str, sensitive_values: Dict[str, str]) -> str:
"""Anonymize sensitive values in content"""
if not content or not sensitive_values:
return content
anonymized = content
for key, value in sensitive_values.items():
if value and len(value) > 1:
# Replace with first char + "***" + last char
replacement = f"{value[0]}***{value[-1]}"
anonymized = anonymized.replace(value, replacement)
return anonymized
def anonymize_file_content(file_path: Path, sensitive_values: Dict[str, str]) -> Optional[str]:
"""
Read and anonymize file content.
Returns anonymized content as string, or None if binary file.
"""
try:
# Try to read as text, replacing invalid UTF-8 bytes
with open(file_path, 'r', encoding='utf-8', errors='replace') as f:
content = f.read()
# Anonymize
return anonymize_content(content, sensitive_values)
except Exception:
# Read error, return None
return None
def anonymize_directory(source_dir: Path, temp_dir: Path, sensitive_values: Dict[str, str]):
"""
Recursively copy directory and anonymize all text files.
Args:
source_dir: Source directory to copy from
temp_dir: Temporary directory to copy to
sensitive_values: Dictionary of sensitive values to anonymize
"""
for item in source_dir.iterdir():
dest_item = temp_dir / item.name
if item.is_dir():
# Recursively process subdirectories
dest_item.mkdir(exist_ok=True)
anonymize_directory(item, dest_item, sensitive_values)
elif item.is_file():
# Try to anonymize text files
anonymized_content = anonymize_file_content(item, sensitive_values)
if anonymized_content is not None:
# Text file - write anonymized content
with open(dest_item, 'w', encoding='utf-8') as f:
f.write(anonymized_content)
else:
# Binary file - copy as is
shutil.copy2(item, dest_item)
def record_job_completion(job_id: str, client_ip: str, start_timestamp: float):
"""Record job completion time and duration in IP submission history"""
try:
end_time = datetime.now()
duration_seconds = int(time.time() - start_timestamp)
# Find the job record for this IP and update it
for record in ip_submission_history[client_ip]:
if record["job_id"] == job_id:
record["completed_at"] = end_time.isoformat()
record["duration_seconds"] = duration_seconds
break
# Persist the updated data
save_rate_limit_data()
log(f"[Server] Recorded job {job_id} completion: duration = {duration_seconds}s ({duration_seconds/60:.1f} min)")
except Exception as e:
log(f"[Server] Warning: Failed to record job completion: {e}")
def is_task_finished(status: dict) -> bool:
"""
Check if a task is finished (including success and failure cases).
Returns True if:
- preprocess failed, OR
- running failed (no evaluation will happen), OR
- running succeeded AND evaluation completed (true or false)
"""
preprocess = status.get('preprocess')
running = status.get('running')
evaluation = status.get('evaluation')
# Case 1: preprocess failed -> task finished (no running, no evaluation)
if preprocess == 'fail':
return True
# Case 2: running failed -> task finished (no evaluation will happen)
if preprocess == 'done' and running == 'fail':
return True
# Case 3: running succeeded (done/timeout/max_turn_exceeded) -> check evaluation
# evaluation must not be None (must be True or False, indicating evaluation completed)
if preprocess == 'done' and running in ['done', 'timeout', 'max_turn_exceeded']:
return evaluation is not None
return False
def check_job_id_exists(job_id: str) -> bool:
"""Check if job_id already exists in dumps directory or is currently running"""
# Check if currently running
if current_job and current_job.get("job_id") == job_id:
return True
# Check if directory exists in dumps
job_dir = Path(DUMPS_DIR) / job_id
return job_dir.exists()
def check_ip_rate_limit(ip: str) -> tuple[bool, str, dict]:
"""
Check if IP has exceeded rate limit.
Returns:
tuple: (allowed: bool, error_message: str, info: dict)
info contains: {
"total_duration_seconds": int,
"remaining_duration_seconds": int,
"request_count": int,
"remaining_requests": int,
"limit_mode": str # "both", "duration_only", "count_only", "unlimited"
}
"""
now = datetime.now()
cutoff = now - timedelta(hours=RATE_LIMIT_HOURS)
# Clean old records (older than RATE_LIMIT_HOURS)
ip_submission_history[ip] = [
record for record in ip_submission_history[ip]
if datetime.fromisoformat(record["submitted_at"]) > cutoff
]
# Calculate stats
completed_jobs = [r for r in ip_submission_history[ip] if r.get("completed_at") is not None]
total_duration_seconds = sum(r.get("duration_seconds", 0) for r in completed_jobs)
request_count = len(ip_submission_history[ip])
# Determine limit mode
has_duration_limit = MAX_DURATION_MINUTES != -1
has_count_limit = MAX_SUBMISSIONS_PER_IP != -1
if not has_duration_limit and not has_count_limit:
# Both unlimited
return True, "", {
"total_duration_seconds": total_duration_seconds,
"remaining_duration_seconds": -1,
"request_count": request_count,
"remaining_requests": -1,
"limit_mode": "unlimited"
}
# Calculate remaining quotas
max_duration_seconds = MAX_DURATION_MINUTES * 60 if has_duration_limit else -1
remaining_duration_seconds = max_duration_seconds - total_duration_seconds if has_duration_limit else -1
remaining_requests = MAX_SUBMISSIONS_PER_IP - request_count if has_count_limit else -1
info = {
"total_duration_seconds": total_duration_seconds,
"remaining_duration_seconds": remaining_duration_seconds,
"request_count": request_count,
"remaining_requests": remaining_requests,
"limit_mode": "both" if (has_duration_limit and has_count_limit) else
("duration_only" if has_duration_limit else "count_only")
}
# Apply rate limit logic based on mode
if has_duration_limit and has_count_limit:
# Both limits active: duration first, then count
if total_duration_seconds < max_duration_seconds:
# Duration not exceeded - allow
return True, "", info
else:
# Duration exceeded - check count limit
if request_count >= MAX_SUBMISSIONS_PER_IP:
# Both exceeded
oldest = ip_submission_history[ip][0]
retry_after = datetime.fromisoformat(oldest["submitted_at"]) + timedelta(hours=RATE_LIMIT_HOURS)
error_msg = (
f"Rate limit exceeded:\n"
f" • Cumulative duration: {total_duration_seconds/60:.1f} / {MAX_DURATION_MINUTES} minutes (EXCEEDED)\n"
f" • Request count: {request_count} / {MAX_SUBMISSIONS_PER_IP} (EXCEEDED)\n"
f" • Time window: {RATE_LIMIT_HOURS} hours\n"
f" • Retry after: {retry_after.isoformat()}"
)
return False, error_msg, info
else:
# Duration exceeded but count ok - allow
return True, "", info
elif has_duration_limit:
# Duration limit only
if total_duration_seconds >= max_duration_seconds:
# Find when the oldest completed job will expire
oldest_completed = min(
(r for r in completed_jobs),
key=lambda r: r["completed_at"],
default=None
)
retry_after = datetime.fromisoformat(oldest_completed["completed_at"]) + timedelta(hours=RATE_LIMIT_HOURS) if oldest_completed else now
error_msg = (
f"Rate limit exceeded:\n"
f" • Cumulative duration: {total_duration_seconds/60:.1f} / {MAX_DURATION_MINUTES} minutes (EXCEEDED)\n"
f" • Time window: {RATE_LIMIT_HOURS} hours\n"
f" • Retry after: {retry_after.isoformat()}"
)
return False, error_msg, info
elif has_count_limit:
# Count limit only
if request_count >= MAX_SUBMISSIONS_PER_IP:
oldest = ip_submission_history[ip][0]
retry_after = datetime.fromisoformat(oldest["submitted_at"]) + timedelta(hours=RATE_LIMIT_HOURS)
error_msg = (
f"Rate limit exceeded:\n"
f" • Request count: {request_count} / {MAX_SUBMISSIONS_PER_IP} (EXCEEDED)\n"
f" • Time window: {RATE_LIMIT_HOURS} hours\n"
f" • Retry after: {retry_after.isoformat()}"
)
return False, error_msg, info
return True, "", info
async def run_command_async(cmd: list, env: dict, log_file: str):
"""Run command asynchronously and capture output to log file"""
with open(log_file, 'a') as log_f:
# Create process in new session so we can kill the entire process tree later
process = await asyncio.create_subprocess_exec(
*cmd,
stdout=log_f,
stderr=asyncio.subprocess.STDOUT,
env=env,
start_new_session=True # Creates new process group for easy cleanup
)
return process
# ===== Background Task Executor =====
async def execute_evaluation(job_id: str, mode: str, config: Dict[str, Any]):
"""Execute evaluation task in background"""
global current_job
start_time = time.time()
job_dir = Path(DUMPS_DIR) / job_id
job_dir.mkdir(parents=True, exist_ok=True)
log_file = str(job_dir / "server_stdout.log")
ws_proxy_process = None
# Save needed fields to local variables in case current_job becomes None during execution
client_ip = current_job.get("client_ip") if current_job else "unknown"
start_timestamp = current_job.get("start_timestamp") if current_job else start_time
try:
with open(log_file, 'w') as f:
f.write(f"=== Toolathlon Evaluation Server Log ===\n")
f.write(f"Job ID: {job_id}\n")
f.write(f"Mode: {mode}\n")
f.write(f"Model: {config['model_name']}\n")
f.write(f"Workers: {config['workers']}\n")
f.write(f"Started: {datetime.now().isoformat()}\n")
if config.get('model_params'):
f.write(f"Custom model parameters: {json.dumps(config['model_params'], indent=2)}\n")
if config.get('skip_container_restart'):
f.write(f"⚠️ WARNING: Container restart skipped (debugging/testing mode)\n")
if config.get('task_list_content'):
f.write(f"Custom task list provided\n")
f.write(f"{'='*50}\n\n")
# Save model_params to file if provided
if config.get('model_params'):
model_params_file = job_dir / "model_params.json"
with open(model_params_file, 'w') as f:
json.dump(config['model_params'], f, indent=2)
log(f"[Server] Saved custom model parameters to: {model_params_file}")
# Save task_list to file if provided
task_list_file = None
if config.get('task_list_content'):
task_list_file = job_dir / "task_list.txt"
with open(task_list_file, 'w') as f:
f.write(config['task_list_content'])
log(f"[Server] Saved custom task list to: {task_list_file}")
# Step 1: Deploy containers (skip if requested)
if config.get('skip_container_restart'):
with open(log_file, 'a') as f:
f.write("=== Step 1: Container deployment SKIPPED (user requested) ===\n")
f.write("⚠️ WARNING: Skipping container restart is recommended ONLY for:\n")
f.write(" - Debugging purposes\n")
f.write(" - Testing a small number of tasks\n")
f.write(" For complete evaluation, it is STRONGLY recommended to restart containers\n")
f.write(" to ensure a clean environment.\n\n")
f.flush()
log(f"[Server] WARNING: Skipping container restart for job {job_id}")
else:
with open(log_file, 'a') as f:
f.write("=== Step 1: Deploying local containers ===\n")
f.flush()
deploy_process = await run_command_async(
["bash", "global_preparation/deploy_containers.sh", "true"],
env=os.environ.copy(),
log_file=log_file
)
await deploy_process.wait()
with open(log_file, 'a') as f:
f.write("\n=== Step 2: Running parallel tests ===\n")
f.flush()
# Step 2: Run tests
env = os.environ.copy()
if mode == "public":
env["TOOLATHLON_OPENAI_BASE_URL"] = config["base_url"]
env["TOOLATHLON_OPENAI_API_KEY"] = config.get("api_key", "")
else: # private
env["TOOLATHLON_OPENAI_BASE_URL"] = f"http://localhost:{WS_PROXY_PORT}/v1"
env["TOOLATHLON_OPENAI_API_KEY"] = "dummy"
# Set model_params file path if provided
if config.get('model_params'):
model_params_file = job_dir / "model_params.json"
env["TOOLATHLON_MODEL_PARAMS_FILE"] = str(model_params_file)
# Set task_list file path if provided (override the empty default in run_parallel.sh)
if task_list_file:
env["TASK_LIST"] = str(task_list_file)
log(f"[Server] Using custom task list: {task_list_file}")
run_process = await run_command_async(
[
"bash", "scripts/run_parallel.sh",
config["model_name"],
str(job_dir),
config["provider"], # Use provider from config (v1.1+)
str(config["workers"])
],
env=env,
log_file=log_file
)
if current_job is not None:
current_job["process"] = run_process
# Monitor execution with timeout
while run_process.returncode is None:
elapsed = time.time() - start_time
if elapsed > TIMEOUT_SECONDS:
with open(log_file, 'a') as f:
f.write(f"\n\n!!! TIMEOUT: Task exceeded {TIMEOUT_SECONDS//60} minutes !!!\n")
run_process.kill()
await run_process.wait()
if current_job is not None:
current_job["status"] = "timeout"
current_job["error"] = f"Task exceeded {TIMEOUT_SECONDS//60} minutes"
log(f"[Server] Job {job_id} timed out after {elapsed//60:.1f} minutes")
# Record completion time and duration
record_job_completion(job_id, client_ip, start_timestamp)
return
await asyncio.sleep(5)
with open(log_file, 'a') as f:
f.write("\n=== Step 3: Task completed ===\n")
f.write(f"Finished: {datetime.now().isoformat()}\n")
# Read results
eval_stats_file = job_dir / "eval_stats.json"
if eval_stats_file.exists():
with open(eval_stats_file, 'r') as f:
eval_stats = json.load(f)
if current_job is not None:
current_job["eval_stats"] = eval_stats
else:
if current_job is not None:
current_job["eval_stats"] = {"error": "eval_stats.json not found"}
# Read traj_log_all.jsonl
traj_log_file = job_dir / "traj_log_all.jsonl"
if traj_log_file.exists():
with open(traj_log_file, 'r') as f:
if current_job is not None:
current_job["traj_log_all"] = f.read()
else:
if current_job is not None:
current_job["traj_log_all"] = None
if current_job is not None:
current_job["status"] = "completed"
log(f"[Server] Job {job_id} completed successfully")
# Record completion time and duration
record_job_completion(job_id, client_ip, start_timestamp)
except Exception as e:
error_msg = str(e)
with open(log_file, 'a') as f:
f.write(f"\n\n!!! ERROR: {error_msg} !!!\n")
if current_job is not None:
current_job["status"] = "failed"
current_job["error"] = error_msg
log(f"[Server] Job {job_id} failed: {error_msg}")
# Record completion time and duration
record_job_completion(job_id, client_ip, start_timestamp)
finally:
# Keep job info for 60 seconds for client to retrieve
await asyncio.sleep(60)
if current_job and current_job.get("job_id") == job_id:
current_job = None
# ===== API Endpoints =====
@app.get("/")
async def root():
return {
"service": "Toolathlon Remote Evaluation Server",
"version": "1.0.0",
"status": "running"
}
@app.get("/check_server_status")
async def check_server_status():
"""Check if server is busy (public endpoint)"""
if current_job:
return {
"busy": True,
"job_id": current_job.get("job_id"),
"mode": current_job.get("mode"),
"model": current_job.get("model_name"),
"started_at": current_job.get("started_at")
}
else:
return {
"busy": False,
"message": "Server is idle and ready to accept tasks"
}
@app.post("/submit_evaluation")
async def submit_evaluation(request: Request, data: SubmitEvaluationRequest):
"""Submit an evaluation task"""
global current_job
client_ip = request.client.host
# Check if client has version (old clients won't have this field)
if data.client_version is None:
raise HTTPException(
status_code=400,
detail={
"error": "Client version missing",
"message": "Your client is too old and does not report a version number.",
"server_version": SERVER_VERSION,
"action": "Please update your client from https://github.com/hkust-nlp/Toolathlon"
}
)
# Check client version compatibility
if data.client_version not in SUPPORTED_CLIENT_VERSIONS:
raise HTTPException(
status_code=400,
detail={
"error": "Client version not supported",
"message": f"Client version '{data.client_version}' is not compatible with server version '{SERVER_VERSION}'.",
"supported_versions": SUPPORTED_CLIENT_VERSIONS,
"action": "Please update your client from https://github.com/hkust-nlp/Toolathlon"
}
)
# Check workers limit
if data.workers > MAX_WORKERS:
raise HTTPException(
status_code=400,
detail={
"error": "Workers limit exceeded",
"message": f"Requested workers ({data.workers}) exceeds server limit ({MAX_WORKERS}).",
"max_workers": MAX_WORKERS
}
)
# Check IP rate limit
allowed, error_msg, limit_info = check_ip_rate_limit(client_ip)
if not allowed:
raise HTTPException(status_code=429, detail=error_msg)
# Check if server is busy
if current_job is not None:
raise HTTPException(
status_code=503,
detail={
"error": "Server is busy",
"message": "Server is currently processing another task. Please try again later.",
"current_job_started_at": current_job.get("started_at")
}
)
# Validate mode
if data.mode not in ["public", "private"]:
raise HTTPException(status_code=400, detail="Mode must be 'public' or 'private'")
# Validate provider (v1.1+)
ALLOWED_PROVIDERS = ["unified", "openai_stateful_responses"]
if data.provider not in ALLOWED_PROVIDERS:
raise HTTPException(
status_code=400,
detail={
"error": "Invalid provider",
"message": f"Provider '{data.provider}' is not supported. Allowed values: {', '.join(ALLOWED_PROVIDERS)}",
"allowed_providers": ALLOWED_PROVIDERS
}
)
# Validate WS client version for private mode (v1.2+)
if data.mode == "private":
if data.ws_client_version is None:
raise HTTPException(
status_code=400,
detail={
"error": "WebSocket client version missing",
"message": "Private mode requires WebSocket client version (v1.2+). Your client files may be outdated.",
"server_version": SERVER_VERSION,
"action": "Please update your client files from https://github.com/hkust-nlp/Toolathlon"
}
)
if data.ws_client_version not in SUPPORTED_WS_CLIENT_VERSIONS:
raise HTTPException(
status_code=400,
detail={
"error": "WebSocket client version not supported",
"message": f"WebSocket client version '{data.ws_client_version}' is not compatible with server version '{SERVER_VERSION}'.",
"your_ws_client_version": data.ws_client_version,
"supported_ws_client_versions": SUPPORTED_WS_CLIENT_VERSIONS,
"action": "Please update simple_client_ws.py from https://github.com/hkust-nlp/Toolathlon"
}
)
# Generate or use custom job_id
warning_msg = None
if data.custom_job_id:
job_id = data.custom_job_id
# Check if job_id already exists
if check_job_id_exists(job_id):
warning_msg = f"Job ID '{job_id}' already exists in the system."
log(f"[Server] WARNING: Job ID {job_id} already exists, but accepting request (possible resume)")
else:
job_id = f"job_{uuid.uuid4().hex[:12]}"
client_id = f"client_{uuid.uuid4().hex[:8]}" if data.mode == "private" else None
# Record IP submission with detailed info
submission_time = datetime.now()
ip_submission_history[client_ip].append({
"job_id": job_id,
"submitted_at": submission_time.isoformat(),
"completed_at": None,
"duration_seconds": None
})
# Save after adding new submission
save_rate_limit_data()
# Initialize job
current_job = {
"job_id": job_id,
"client_id": client_id,
"client_ip": client_ip,
"mode": data.mode,
"model_name": data.model_name,
"workers": data.workers,
"status": "running",
"started_at": submission_time.isoformat(),
"start_timestamp": submission_time.timestamp() # For duration calculation
}
# Start background task
config = {
"base_url": data.base_url,
"api_key": data.api_key,
"model_name": data.model_name,
"workers": data.workers,
"model_params": data.model_params,
"task_list_content": data.task_list_content,
"skip_container_restart": data.skip_container_restart,
"provider": data.provider # Add provider (v1.1+)
}
asyncio.create_task(execute_evaluation(job_id, data.mode, config))
log(f"[Server] Accepted job {job_id} from {client_ip} (mode: {data.mode}, provider: {data.provider})")
if data.model_params:
log(f"[Server] Using custom model parameters: {json.dumps(data.model_params)}")
if data.task_list_content:
# Count number of tasks in the list
task_count = len([line.strip() for line in data.task_list_content.strip().split('\n') if line.strip()])
log(f"[Server] Using custom task list with {task_count} tasks")
if data.skip_container_restart:
log(f"[Server] WARNING: Container restart will be skipped (debugging/testing mode only)")
# Prepare rate limit info for response
rate_limit_info = {
"limit_mode": limit_info["limit_mode"],
"usage": {}
}
if limit_info["limit_mode"] in ["both", "duration_only", "unlimited"]:
if limit_info["remaining_duration_seconds"] == -1:
rate_limit_info["usage"]["duration"] = "unlimited"
else:
rate_limit_info["usage"]["duration"] = {
"used_minutes": round(limit_info["total_duration_seconds"] / 60, 1),
"remaining_minutes": round(limit_info["remaining_duration_seconds"] / 60, 1),
"limit_minutes": MAX_DURATION_MINUTES
}
if limit_info["limit_mode"] in ["both", "count_only", "unlimited"]:
if limit_info["remaining_requests"] == -1:
rate_limit_info["usage"]["requests"] = "unlimited"
else:
rate_limit_info["usage"]["requests"] = {
"used": limit_info["request_count"] + 1, # +1 for current request
"remaining": limit_info["remaining_requests"] - 1, # -1 because we just added one
"limit": MAX_SUBMISSIONS_PER_IP
}
response = {
"status": "accepted",
"job_id": job_id,
"client_id": client_id,
"message": "Task accepted and started",
"rate_limit_info": rate_limit_info
}
if warning_msg:
response["warning"] = warning_msg
return response
@app.get("/poll_job_status")
async def poll_job_status(job_id: str):
"""Poll job status"""
# Load sensitive values for anonymization
sensitive_values = load_sensitive_values()
if not current_job or current_job.get("job_id") != job_id:
# Check if job exists in dumps (completed job)
job_dir = Path(DUMPS_DIR) / job_id
eval_stats_file = job_dir / "eval_stats.json"
if eval_stats_file.exists():
# Use errors='replace' to handle non-UTF-8 bytes gracefully
with open(eval_stats_file, 'r', encoding='utf-8', errors='replace') as f:
eval_stats_content = f.read()
# Anonymize eval_stats
anonymized_eval_stats = anonymize_content(eval_stats_content, sensitive_values)
eval_stats = json.loads(anonymized_eval_stats)
# Also read traj_log_all.jsonl if exists
traj_log_file = job_dir / "traj_log_all.jsonl"
traj_log_all = None
if traj_log_file.exists():
# Use errors='replace' to handle non-UTF-8 bytes gracefully
with open(traj_log_file, 'r', encoding='utf-8', errors='replace') as f:
traj_log_content = f.read()
# Anonymize traj_log
traj_log_all = anonymize_content(traj_log_content, sensitive_values)
return {
"status": "completed",
"eval_stats": eval_stats,
"traj_log_all": traj_log_all
}
else:
return {
"status": "cancelled",
"error": "Job not found or has been cleaned up"
}
status = current_job.get("status", "running")
response = {"status": status}
if status == "completed":
# Anonymize eval_stats if present
eval_stats = current_job.get("eval_stats", {})
eval_stats_str = json.dumps(eval_stats)
anonymized_eval_stats_str = anonymize_content(eval_stats_str, sensitive_values)
response["eval_stats"] = json.loads(anonymized_eval_stats_str)
# Anonymize traj_log_all if present
traj_log_all = current_job.get("traj_log_all")
if traj_log_all:
response["traj_log_all"] = anonymize_content(traj_log_all, sensitive_values)
else:
response["traj_log_all"] = None
elif status in ["failed", "timeout"]:
response["error"] = current_job.get("error", "Unknown error")
return response
@app.get("/internal/validate_job")
async def validate_job(job_id: str, request: Request):
"""
Internal endpoint to validate if a job_id is currently running.
Only accessible from localhost for security.
Used by WebSocket proxy to authenticate connections.
"""
# Security: Only allow localhost
client_host = request.client.host if request.client else "unknown"
if client_host not in ["127.0.0.1", "localhost", "::1"]:
raise HTTPException(status_code=403, detail="Access denied: localhost only")
# Check if this job_id matches the current running job
if current_job and current_job.get("job_id") == job_id:
return {
"valid": True,
"job_id": job_id,
"mode": current_job.get("mode"),
"started_at": current_job.get("started_at")
}
else:
return {
"valid": False,
"message": "No active job with this ID"
}
@app.get("/get_server_log")
async def get_server_log(job_id: str, offset: int = 0):
"""Get server execution log with incremental reading and anonymization"""
log_file = Path(DUMPS_DIR) / job_id / "server_stdout.log"
if not log_file.exists():
return {
"error": "Log file not found",
"content": "",
"offset": 0,
"size": 0,
"complete": False
}
# Load sensitive values for anonymization
sensitive_values = load_sensitive_values()
try:
# Use errors='replace' to handle non-UTF-8 bytes gracefully
with open(log_file, 'r', encoding='utf-8', errors='replace') as f:
f.seek(offset)
new_content = f.read()
new_offset = f.tell()
# Anonymize content
anonymized_content = anonymize_content(new_content, sensitive_values)
file_size = log_file.stat().st_size
# Check if job is complete
job_complete = False
if current_job and current_job.get("job_id") == job_id:
if current_job.get("status") in ["completed", "failed", "timeout", "cancelled"]:
job_complete = True
else:
job_complete = True
return {
"content": anonymized_content,
"offset": new_offset,
"size": file_size,
"complete": job_complete
}
except Exception as e:
return {
"error": str(e),
"content": "",
"offset": offset,
"size": 0,
"complete": False
}
@app.post("/cancel_job")