-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathworker.py
More file actions
2632 lines (2265 loc) · 112 KB
/
Copy pathworker.py
File metadata and controls
2632 lines (2265 loc) · 112 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
import base64
import os
import re
import sys
import time
import logging
import subprocess
import signal
import json
import shutil
import threading
import fnmatch
from datetime import datetime, timedelta, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from pathlib import Path
from supabase import create_client, Client
from allrun_validator import audit_allrun_scripts
from case_lint import lint_hints
from token_extractor import extract_token_usage
# --- 1. 初始化与配置 ---
# 配置日志,方便我们观察 Worker 的一举一动
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# --- 新增这两行 ---
from dotenv import load_dotenv
load_dotenv() # 自动读取同目录下的 .env 文件
# ------------------
# --- Worker identification (for multi-worker setups) ---
WORKER_ID = os.environ.get("WORKER_ID", f"worker-{os.getpid()}")
# --- Foam-Agent 目录配置 ---
FOAM_AGENT_DIR = os.environ.get("FOAM_AGENT_DIR")
if not FOAM_AGENT_DIR:
logger.error("FATAL: FOAM_AGENT_DIR is not set. Set it in .env to point to the Foam-Agent directory.")
raise RuntimeError("FOAM_AGENT_DIR is not set in the environment variables.")
FOAM_AGENT_DIR = os.path.abspath(FOAM_AGENT_DIR)
if not os.path.isdir(FOAM_AGENT_DIR):
logger.error(f"FATAL: FOAM_AGENT_DIR={FOAM_AGENT_DIR} does not exist or is not a directory.")
raise RuntimeError(f"FOAM_AGENT_DIR={FOAM_AGENT_DIR} does not exist.")
logger.info(f"FOAM_AGENT_DIR resolved to: {FOAM_AGENT_DIR}")
# Simulation subprocess timeout (seconds). Default: 3600 (1 hour).
SIMULATION_TIMEOUT = int(os.environ.get("SIMULATION_TIMEOUT", "3600"))
logger.info(f"Simulation timeout set to {SIMULATION_TIMEOUT} seconds")
# Stale job recovery threshold (seconds).
# A running job older than this is considered stuck and will be reset to 'queued'.
# Defaults to SIMULATION_TIMEOUT + 10 min buffer (for upload/cleanup time).
_default_stale = SIMULATION_TIMEOUT + 600
STALE_JOB_THRESHOLD = int(os.environ.get("STALE_JOB_THRESHOLD", str(_default_stale)))
logger.info(f"Stale job threshold set to {STALE_JOB_THRESHOLD} seconds ({STALE_JOB_THRESHOLD//60} min)")
# How often (seconds) to check DB for cancellation while subprocess is running.
CANCEL_CHECK_INTERVAL = int(os.environ.get("CANCEL_CHECK_INTERVAL", "5"))
logger.info(f"Cancel check interval set to {CANCEL_CHECK_INTERVAL} seconds")
# Pre-run timeout (seconds). Default: 300 (5 minutes). Much shorter than full simulation.
PRE_RUN_TIMEOUT = int(os.environ.get("PRE_RUN_TIMEOUT", "300"))
logger.info(f"Pre-run timeout set to {PRE_RUN_TIMEOUT} seconds")
# Max disk usage per task (bytes). Default: 1024 MB. Task is killed if exceeded.
# Bumped from 400 MB after task #325 hit ENOSPC after 11 Rewrite loops on a
# real heatTransfer case — the agent often produces several tens of MB per
# loop, so 400 was too tight for cases that need deep error correction.
TASK_DISK_LIMIT_BYTES = int(os.environ.get("TASK_DISK_LIMIT_MB", "1024")) * 1024 * 1024
logger.info(f"Task disk limit set to {TASK_DISK_LIMIT_BYTES // (1024*1024)} MB")
# How often (seconds) to check disk usage during subprocess run.
DISK_CHECK_INTERVAL = int(os.environ.get("DISK_CHECK_INTERVAL", "30"))
logger.info(f"Disk check interval set to {DISK_CHECK_INTERVAL} seconds")
# Health check HTTP server port. Set to 0 to disable.
HEALTH_CHECK_PORT = int(os.environ.get("HEALTH_CHECK_PORT", "8001"))
# Default OpenAI-compatible endpoints for non-OpenAI providers, used when the
# user picks BYOK with `qwen` or `deepseek` but doesn't supply an explicit
# `base_url`. Without these, the request goes to api.openai.com and gets
# rejected with "Incorrect API key" — see 2026-05-21 incident
# (zhuge7777@139.com, 10 BYOK failures across qwen/deepseek/openai that were
# all our routing bug, not the user's keys).
PROVIDER_DEFAULT_BASE_URLS = {
'qwen': 'https://dashscope.aliyuncs.com/compatible-mode/v1',
'deepseek': 'https://api.deepseek.com',
}
# --- Subscription-Claude bridge (opt-in, machine-specific) ---
# Jobs with llm_config.model_provider == 'claude-bridge' run against a local
# claude-bridge sidecar (platform repo claude-bridge/) that fronts subscription
# Claude Code (`claude -p`, no API key). Only workers with CLAUDE_BRIDGE_URL
# configured can run them; workers without it re-queue the job so a
# bridge-equipped worker (currently: the desktop) picks it up.
CLAUDE_BRIDGE_URL = os.environ.get('CLAUDE_BRIDGE_URL', '').strip()
CLAUDE_BRIDGE_TOKEN = os.environ.get('CLAUDE_BRIDGE_TOKEN', '').strip()
# --- Controlled pipeline: exclusive worker lock ---
# When a worker is bound to a controlled-pipeline job, it must not claim
# other jobs until that job completes/fails/is cancelled.
# Stores the job ID (int/str) or None.
_bound_pipeline_job_id = None
# Timestamp (UTC) when the bound job entered its current checkpoint.
_bound_checkpoint_since = None
# How long (seconds) to wait for user confirmation before auto-failing.
# 2 hours: users may need time to inspect generated files before confirming.
CHECKPOINT_TIMEOUT = int(os.environ.get("CHECKPOINT_TIMEOUT", "7200")) # 2 h
# Max review→fix iterations in controlled-mode pre-run before giving up.
# 8 chosen after observing real failures (jobs 433/443) where 5 iterations
# weren't enough for the LLM to converge on dictionary/boundary-field fixes.
PRE_RUN_MAX_FIX_ATTEMPTS = int(os.environ.get("PRE_RUN_MAX_FIX_ATTEMPTS", "8"))
# --- Middleware directory configuration ---
MIDDLEWARE_DIR = os.environ.get("MIDDLEWARE_DIR")
if MIDDLEWARE_DIR:
MIDDLEWARE_DIR = os.path.abspath(MIDDLEWARE_DIR)
pre_run_module_path = os.path.join(MIDDLEWARE_DIR, "Foam-Agent", "pre-run")
if os.path.isdir(pre_run_module_path):
sys.path.insert(0, pre_run_module_path)
logger.info(f"Middleware pre-run path added to sys.path: {pre_run_module_path}")
else:
logger.warning(f"MIDDLEWARE_DIR set but pre-run path not found: {pre_run_module_path}")
else:
logger.info("MIDDLEWARE_DIR not set, checkpoint pre-run disabled.")
# 从环境变量加载 Supabase 配置
SUPABASE_URL = os.environ.get("SUPABASE_URL")
SUPABASE_SERVICE_KEY = os.environ.get("SUPABASE_SERVICE_KEY")
if not SUPABASE_URL or not SUPABASE_SERVICE_KEY:
logger.error("FATAL: Supabase credentials are not set in the environment variables.")
raise RuntimeError("Supabase credentials are not set in the environment variables.")
logger.info("Initializing Supabase client for Worker...")
supabase: Client = create_client(SUPABASE_URL, SUPABASE_SERVICE_KEY)
logger.info(f"Supabase client initialized successfully. WORKER_ID={WORKER_ID}")
# --- Security: subprocess environment and log sanitization ---
# Server-side env vars that must NOT be passed to Foam-Agent subprocess.
# The subprocess only needs: system vars, OpenFOAM vars, and LLM credentials.
_SUBPROCESS_ENV_BLOCKLIST = frozenset({
'SUPABASE_URL',
'SUPABASE_SERVICE_KEY',
'SUPABASE_JWT_SECRET',
'EXTRA_CORS_ORIGINS',
'WORKER_ID',
'HEALTH_CHECK_PORT',
'WORKER_HEALTH_URL',
'USER_STORAGE_LIMIT_MB',
'USER_DAILY_TASK_LIMIT',
'FOAM_AGENT_HOST_PATH',
'MIDDLEWARE_HOST_PATH',
'MIDDLEWARE_DIR',
'SIMULATION_TIMEOUT',
'STALE_JOB_THRESHOLD',
'TASK_DISK_LIMIT_MB',
'DISK_CHECK_INTERVAL',
'MCP_SERVER_PORT',
})
# Patterns to redact from simulation.log before uploading to user-accessible storage
_SENSITIVE_LOG_PATTERNS = [
(re.compile(r'sk-proj-[A-Za-z0-9_-]{20,}'), '[REDACTED_OPENAI_KEY]'),
(re.compile(r'sk-ant-[A-Za-z0-9_-]{20,}'), '[REDACTED_ANTHROPIC_KEY]'),
# Generic sk- keys (OpenAI/DeepSeek format, 30+ chars to catch all variants)
(re.compile(r'(?<![A-Za-z0-9_-])sk-[A-Za-z0-9]{30,}'), '[REDACTED_API_KEY]'),
# JWT tokens (three dot-separated base64 segments, e.g. Supabase service key)
(re.compile(r'eyJ[A-Za-z0-9_/+-]{50,}\.[A-Za-z0-9_/+-]{50,}\.[A-Za-z0-9_/+-]{20,}'),
'[REDACTED_TOKEN]'),
]
def _build_subprocess_env():
"""Build a sanitized environment dict for simulation subprocesses.
Starts from the current process environment and removes server-side secrets
(Supabase credentials, worker config, etc.) so that the subprocess cannot
read or leak them.
"""
return {k: v for k, v in os.environ.items() if k not in _SUBPROCESS_ENV_BLOCKLIST}
def _sanitize_log_file(log_path):
"""Redact sensitive patterns (API keys, JWT tokens) from a log file in-place.
Called before uploading simulation.log to user-accessible Supabase Storage
to prevent accidental credential exposure through subprocess output.
"""
if not log_path or not os.path.isfile(log_path):
return
try:
with open(log_path, 'r', errors='replace') as f:
content = f.read()
redacted = False
for pattern, replacement in _SENSITIVE_LOG_PATTERNS:
new_content = pattern.sub(replacement, content)
if new_content != content:
redacted = True
content = new_content
if redacted:
with open(log_path, 'w') as f:
f.write(content)
logger.warning(f"Sanitized sensitive patterns from {log_path}")
except Exception as e:
logger.warning(f"Failed to sanitize log file {log_path}: {e}")
def _diagnose_error_text(text, effective_provider, is_byok=False):
"""Match known error patterns in arbitrary text and return a user-friendly message.
Args:
text: Error text to scan (log content or exception message).
effective_provider: Provider name after BYOK→openai mapping (e.g. 'openai', 'openai-codex').
is_byok: True if user supplied their own API key / Codex token. Used to
tailor the error message: BYOK users see "your key invalid", platform
default users see "platform unavailable".
Returns a tuple (user_message, error_category) or (None, None) if no known
pattern is detected.
"""
if not text:
return None, None
lower = text.lower()
# Rate limit / quota exceeded (OpenAI, Codex, Anthropic, DeepSeek)
if any(p in lower for p in [
'rate_limit_exceeded', 'ratelimiterror', 'rate limit reached',
'too many requests', 'quota exceeded', 'insufficient_quota',
'you exceeded your current quota',
]):
if effective_provider == 'openai-codex' and not is_byok:
return (
"Platform Codex quota temporarily exhausted. "
"It resets every few hours — please wait and try again, or use BYOK with your own API key."
), 'codex_quota_exceeded'
return (
"LLM API rate limit or quota exceeded. "
"Please try again later, or use a different API key / model."
), 'rate_limit'
# Authentication errors
# Note: avoid bare '401' — it false-matches FAISS similarity scores like 0.401...
if any(p in lower for p in [
'authenticationerror', 'invalid api key', 'invalid_api_key',
'incorrect api key', 'unauthorized', 'http 401', 'status 401',
'error code: 401', '401 unauthorized', 'token_expired',
]):
if is_byok:
# User-provided credential is the problem
if effective_provider == 'openai-codex':
return (
"Your Codex OAuth token is invalid or expired. "
"Codex tokens expire every ~10 days — please re-authenticate and try again, "
"or switch to BYOK with a regular API key (OpenAI / Anthropic / DeepSeek)."
), 'auth_error_byok'
return (
"Your API key is invalid or expired. "
"Please verify the key in your provider's dashboard and resubmit."
), 'auth_error_byok'
# Platform default credential is the problem
return (
"Platform default model is temporarily unavailable (authentication failed). "
"The administrator has been notified. "
"Meanwhile you can use BYOK with your own API key to keep working."
), 'auth_error_platform'
return None, None
def _diagnose_subprocess_failure(log_path, effective_provider, is_byok=False):
"""Scan a subprocess log file for known error patterns.
Thin wrapper around _diagnose_error_text() that loads the file first.
Returns (user_message, error_category) or (None, None).
"""
if not log_path or not os.path.isfile(log_path):
return None, None
try:
with open(log_path, 'r', errors='replace') as f:
content = f.read()
except Exception:
return None, None
return _diagnose_error_text(content, effective_provider, is_byok)
def _check_platform_codex_token():
"""Validate the platform Codex OAuth token at startup.
Reads ``$CODEX_HOME/auth.json`` (default ``~/.codex/auth.json``), parses
``access_token`` as a JWT, and inspects the ``exp`` claim. Catches the
common failure that caused the 2026-04-09 incident (mass auth_error_platform
when the platform's ChatGPT Plus codex token silently expired).
Returns dict {status, detail} where status ∈ {healthy, expiring_soon,
expired, missing, malformed}.
"""
codex_home = os.environ.get("CODEX_HOME") or os.path.expanduser("~/.codex")
auth_path = os.path.join(codex_home, "auth.json")
if not os.path.isfile(auth_path):
return {"status": "missing", "detail": f"no auth.json at {auth_path}"}
try:
with open(auth_path) as f:
data = json.load(f)
except Exception as e:
return {"status": "malformed", "detail": f"cannot parse {auth_path}: {e}"}
token = (data or {}).get("access_token") or ""
parts = token.split(".")
if len(parts) != 3:
return {"status": "malformed", "detail": "access_token is not a JWT"}
try:
payload_b64 = parts[1] + "=" * (-len(parts[1]) % 4)
payload = json.loads(base64.urlsafe_b64decode(payload_b64))
except Exception as e:
return {"status": "malformed", "detail": f"cannot decode JWT payload: {e}"}
exp = payload.get("exp")
if not exp:
return {"status": "malformed", "detail": "JWT missing exp claim"}
expires_at = datetime.fromtimestamp(exp, tz=timezone.utc)
now = datetime.now(timezone.utc)
if expires_at < now:
return {"status": "expired",
"detail": f"token expired at {expires_at.isoformat()} ({now - expires_at} ago)"}
delta = expires_at - now
if delta.total_seconds() < 86400:
return {"status": "expiring_soon",
"detail": f"token expires at {expires_at.isoformat()} (in {delta})"}
return {"status": "healthy",
"detail": f"token valid until {expires_at.isoformat()}"}
# --- 2. 辅助函数:文件树构建和上传 ---
def build_file_tree(directory_path):
"""
递归扫描目录,构建文件树结构。
返回格式:
{
"files": [
{"path": "prompt.txt", "name": "prompt.txt", "size": 1234, "type": "txt"},
{"path": "output/Allrun", "name": "Allrun", "size": 5678, "type": "sh"},
...
],
"directories": [
{"path": "output", "name": "output"},
{"path": "output/0", "name": "0"},
...
]
}
"""
file_tree = {
"files": [],
"directories": []
}
base_path = Path(directory_path)
if not base_path.exists():
logger.warning(f"Directory {directory_path} does not exist")
return file_tree
# Directories to exclude from file tree (sensitive or ephemeral)
excluded_dirs = {'.codex_auth'}
# 使用os.walk遍历所有文件和目录
for root, dirs, files in os.walk(directory_path):
# Skip excluded directories (modifying dirs in-place prunes os.walk)
dirs[:] = [d for d in dirs if d not in excluded_dirs]
# 计算相对于base_path的路径
rel_root = os.path.relpath(root, directory_path)
# 添加目录信息(排除根目录)
if rel_root != '.':
file_tree["directories"].append({
"path": rel_root.replace('\\', '/'), # 统一使用正斜杠
"name": os.path.basename(root)
})
# 添加文件信息
for file in files:
file_path = os.path.join(root, file)
rel_file_path = os.path.relpath(file_path, directory_path)
try:
file_size = os.path.getsize(file_path)
# 根据文件扩展名判断文件类型
_, ext = os.path.splitext(file)
file_type = ext[1:].lower() if ext else 'unknown'
file_tree["files"].append({
"path": rel_file_path.replace('\\', '/'), # 统一使用正斜杠
"name": file,
"size": file_size,
"type": file_type
})
except Exception as e:
logger.warning(f"Failed to get info for file {file_path}: {e}")
# 按路径排序,便于前端显示
file_tree["files"].sort(key=lambda x: x["path"])
file_tree["directories"].sort(key=lambda x: x["path"])
logger.info(f"Built file tree for {directory_path}: {len(file_tree['files'])} files, {len(file_tree['directories'])} directories")
return file_tree
def get_content_type(file_type):
"""
根据文件扩展名返回 MIME 类型。
"""
content_types = {
'txt': 'text/plain',
'log': 'text/plain',
'err': 'text/plain',
'out': 'text/plain',
'dict': 'text/plain',
'boundary': 'text/plain',
'json': 'application/json',
'xml': 'application/xml',
'py': 'text/x-python',
'sh': 'text/x-shellscript',
'c': 'text/x-c',
'cpp': 'text/x-c++',
'h': 'text/x-c',
'hpp': 'text/x-c++',
'csv': 'text/csv',
'html': 'text/html',
'md': 'text/markdown',
'pdf': 'application/pdf',
'zip': 'application/zip',
'foam': 'text/plain', # ParaView文件
'vtk': 'application/octet-stream',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
}
return content_types.get(file_type, 'application/octet-stream')
def upload_directory_to_storage(local_dir, storage_base_path, supabase_client):
"""
将本地目录中的所有文件上传到 Supabase Storage。
参数:
local_dir: 本地目录路径(如 "runs/10")
storage_base_path: Storage中的基础路径(如 "public/{user_id}/10")
supabase_client: Supabase客户端实例
返回:
(uploaded_count, failed_count, total_bytes): 成功/失败的文件数量和总字节数
"""
uploaded_count = 0
failed_count = 0
total_bytes = 0
base_path = Path(local_dir)
if not base_path.exists():
logger.error(f"Local directory {local_dir} does not exist")
return uploaded_count, failed_count, total_bytes
# Directories to exclude from upload (sensitive or ephemeral)
excluded_dirs = {'.codex_auth'}
# 遍历所有文件
for root, dirs, files in os.walk(local_dir):
# Skip excluded directories (modifying dirs in-place prunes os.walk)
dirs[:] = [d for d in dirs if d not in excluded_dirs]
for file in files:
local_file_path = os.path.join(root, file)
# 计算相对于local_dir的路径
rel_file_path = os.path.relpath(local_file_path, local_dir)
storage_file_path = f"{storage_base_path}/{rel_file_path}".replace('\\', '/')
try:
# 读取文件内容
with open(local_file_path, 'rb') as f:
file_content = f.read()
total_bytes += len(file_content)
# 获取文件类型
_, ext = os.path.splitext(file)
file_type = ext[1:].lower() if ext else 'unknown'
content_type = get_content_type(file_type)
# 上传到Storage
# 注意:如果文件已存在,需要先删除或使用upsert
try:
# 尝试删除已存在的文件(如果有)
supabase_client.storage.from_("simulation_results").remove([storage_file_path])
except Exception:
pass # Ignore if file doesn't exist
# 上传文件
supabase_client.storage.from_("simulation_results").upload(
path=storage_file_path,
file=file_content,
file_options={"content-type": content_type}
)
uploaded_count += 1
if uploaded_count % 10 == 0: # 每上传10个文件记录一次
logger.info(f"Uploaded {uploaded_count} files...")
except Exception as e:
failed_count += 1
logger.error(f"Failed to upload file {local_file_path} to {storage_file_path}: {e}")
# 继续上传其他文件,不因单个文件失败而中断
logger.info(f"Upload complete: {uploaded_count} files uploaded, {failed_count} files failed, {total_bytes} bytes total")
return uploaded_count, failed_count, total_bytes
# --- 3. Stale job recovery ---
def recover_stale_jobs():
"""
Recover jobs stuck in 'running' status due to a previous Worker crash.
Finds ALL 'running' jobs and checks if their created_at is older than
STALE_JOB_THRESHOLD (default: 2 hours). Uses created_at instead of
updated_at because the cancel-check polling loop updates updated_at
continuously, making it unreliable for staleness detection.
Called once at Worker startup.
"""
try:
response = (
supabase.table('simulations')
.select('id, created_at')
.eq('status', 'running')
.execute()
)
if not response.data:
logger.info("No stale jobs found during startup recovery.")
return
now = datetime.now(timezone.utc)
stale_jobs = []
for job in response.data:
try:
created = datetime.fromisoformat(job['created_at'].replace('Z', '+00:00'))
age_seconds = (now - created).total_seconds()
if age_seconds > STALE_JOB_THRESHOLD:
job['_age_hours'] = age_seconds / 3600
stale_jobs.append(job)
except Exception:
stale_jobs.append(job) # Can't parse date → treat as stale
if not stale_jobs:
logger.info(f"No stale jobs found ({len(response.data)} running job(s) are within threshold).")
return
logger.warning(f"Found {len(stale_jobs)} stale job(s) stuck in 'running' status.")
for job in stale_jobs:
job_id = job['id']
age_h = job.get('_age_hours', '?')
logger.warning(
f"Recovering stale job {job_id} "
f"(created {age_h:.1f}h ago, threshold {STALE_JOB_THRESHOLD/3600:.1f}h). "
f"Resetting to 'queued'."
)
# Clear worker affinity so any available worker can pick it up.
# Fetch current pipeline_state to remove assigned_worker_id.
full_job = supabase.table('simulations').select(
'pipeline_state'
).eq('id', job_id).execute()
update_data = {'status': 'queued'}
if full_job.data:
ps = full_job.data[0].get('pipeline_state') or {}
if ps.pop('assigned_worker_id', None):
update_data['pipeline_state'] = ps
logger.info(f"Stale job {job_id}: cleared worker affinity.")
supabase.table('simulations').update(update_data).eq('id', job_id).execute()
logger.info(f"Stale job {job_id} reset to 'queued' successfully.")
except Exception as e:
logger.error(f"Error during stale job recovery: {e}", exc_info=True)
# --- 4. Purge & TTL auto-expiry ---
# Throttle: run at most once per hour
_last_purge_time = 0.0
PURGE_INTERVAL = 3600 # seconds between purge runs
PURGE_RETENTION_DAYS = 7 # keep soft-deleted rows for 7 days before hard-delete
TTL_FAILED_DAYS = 30 # auto-expire failed/cancelled tasks after 30 days
TTL_COMPLETED_DAYS = 90 # auto-expire completed tasks after 90 days
def run_purge_cycle():
"""
Single throttled entry point for all purge/TTL work.
Runs at most once per PURGE_INTERVAL seconds.
1. Auto-expire old tasks (soft-delete via TTL)
2. Hard-delete tasks whose deleted_at is older than PURGE_RETENTION_DAYS
"""
global _last_purge_time
now = time.time()
if now - _last_purge_time < PURGE_INTERVAL:
return
_last_purge_time = now
_purge_expired_simulations()
_purge_deleted_simulations()
def _purge_expired_simulations():
"""
Auto-expire old simulations by setting deleted_at (soft-delete).
- failed/cancelled tasks older than TTL_FAILED_DAYS
- completed tasks older than TTL_COMPLETED_DAYS
"""
now_utc = datetime.now(timezone.utc)
try:
# 1. Auto-expire failed/cancelled > TTL_FAILED_DAYS
failed_cutoff = (now_utc - timedelta(days=TTL_FAILED_DAYS)).isoformat()
resp1 = (
supabase.table('simulations')
.update({'deleted_at': now_utc.isoformat()})
.is_('deleted_at', 'null')
.in_('status', ['failed', 'cancelled'])
.lt('created_at', failed_cutoff)
.execute()
)
expired_failed = len(resp1.data) if resp1.data else 0
# 2. Auto-expire completed > TTL_COMPLETED_DAYS
completed_cutoff = (now_utc - timedelta(days=TTL_COMPLETED_DAYS)).isoformat()
resp2 = (
supabase.table('simulations')
.update({'deleted_at': now_utc.isoformat()})
.is_('deleted_at', 'null')
.eq('status', 'completed')
.lt('created_at', completed_cutoff)
.execute()
)
expired_completed = len(resp2.data) if resp2.data else 0
if expired_failed or expired_completed:
logger.info(f"TTL auto-expire: {expired_failed} failed/cancelled, {expired_completed} completed tasks marked for deletion")
except Exception as e:
logger.error(f"TTL auto-expire: error: {e}", exc_info=True)
def _remove_storage_directory(prefix):
"""
Recursively list and remove all files under a Supabase Storage prefix.
Supabase list() only returns one level, so we must recurse into subdirectories.
"""
bucket = supabase.storage.from_('simulation_results')
listed = bucket.list(prefix)
if not listed:
return
files = []
for item in listed:
item_path = f"{prefix}/{item['name']}"
if item.get('id') is None:
# Directory entry (no id) — recurse
_remove_storage_directory(item_path)
else:
files.append(item_path)
if files:
bucket.remove(files)
def _purge_deleted_simulations():
"""
Hard-delete simulations where deleted_at is older than PURGE_RETENTION_DAYS.
Cleanup order: Supabase Storage files -> local runs/ directory -> DB row.
"""
cutoff = (datetime.now(timezone.utc) - timedelta(days=PURGE_RETENTION_DAYS)).isoformat()
try:
response = (
supabase.table('simulations')
.select('id, user_id, result_data, mesh_file')
.not_.is_('deleted_at', 'null')
.lt('deleted_at', cutoff)
.execute()
)
rows = response.data
if not rows:
logger.info("Purge: no expired soft-deleted simulations.")
return
logger.info(f"Purge: found {len(rows)} simulation(s) to hard-delete.")
for row in rows:
job_id = row['id']
user_id = row.get('user_id')
result_data = row.get('result_data') or {}
# 1. Delete files from Supabase Storage (recursive).
# Fall back to canonical path for older rows missing storage_base_path
# (the upload code consistently uses f"public/{user_id}/{job_id}").
storage_base = result_data.get('storage_base_path')
if not storage_base and user_id:
storage_base = f"public/{user_id}/{job_id}"
storage_clean = True
if storage_base:
try:
_remove_storage_directory(storage_base)
# Verify the directory is actually empty before allowing DB delete.
remaining = supabase.storage.from_('simulation_results').list(storage_base)
if remaining:
storage_clean = False
logger.warning(
f"Purge: Storage path {storage_base} still has {len(remaining)} entries; "
f"keeping DB row {job_id} for retry next cycle"
)
else:
logger.info(f"Purge: removed Storage files for job {job_id}")
except Exception as e:
storage_clean = False
logger.warning(
f"Purge: failed to remove Storage files for job {job_id}: {e}; "
f"keeping DB row for retry next cycle"
)
elif not user_id:
# No user_id and no storage_base_path — refuse to delete (would orphan Storage).
storage_clean = False
logger.warning(f"Purge: job {job_id} has no user_id and no storage_base_path; keeping DB row")
# 2. Delete uploaded mesh file from Supabase Storage
mesh_file = row.get('mesh_file') or {}
mesh_path = mesh_file.get('storage_path')
mesh_clean = True
if mesh_path:
try:
supabase.storage.from_('simulation_results').remove([mesh_path])
logger.info(f"Purge: removed mesh file {mesh_path} for job {job_id}")
except Exception as e:
mesh_clean = False
logger.warning(f"Purge: failed to remove mesh file for job {job_id}: {e}")
# 3. Delete local runs/ directory (best-effort; not a gate for DB delete)
local_run_dir = os.path.join(FOAM_AGENT_DIR, "runs", str(job_id))
if os.path.isdir(local_run_dir):
try:
shutil.rmtree(local_run_dir)
logger.info(f"Purge: removed local dir {local_run_dir}")
except Exception as e:
logger.warning(f"Purge: failed to remove local dir {local_run_dir}: {e}")
# 4. Delete DB row only if cloud storage cleanup actually succeeded.
# Otherwise leave the soft-deleted row in place; the next purge cycle retries.
if storage_clean and mesh_clean:
try:
supabase.table('simulations').delete().eq('id', job_id).execute()
logger.info(f"Purge: hard-deleted simulation {job_id} from DB")
except Exception as e:
logger.error(f"Purge: failed to delete DB row for job {job_id}: {e}")
except Exception as e:
logger.error(f"Purge: error during purge cycle: {e}", exc_info=True)
# --- 5. Cancellation helpers ---
def check_job_cancelled(job_id):
"""Check if a job has been cancelled by the user (status == 'cancelled' in DB)."""
try:
response = supabase.table('simulations').select('status').eq('id', job_id).execute()
if response.data and response.data[0]['status'] == 'cancelled':
return True
except Exception as e:
logger.warning(f"Job {job_id}: failed to check cancel status: {e}")
return False
def _kill_process_tree(process):
"""
Kill a subprocess and all its children by sending signals to the process group.
Uses SIGTERM first (graceful), then SIGKILL (force) if still alive after 10s.
Requires the process to have been started with start_new_session=True.
"""
try:
pgid = os.getpgid(process.pid)
except ProcessLookupError:
return # Already dead
try:
os.killpg(pgid, signal.SIGTERM)
process.wait(timeout=10)
except subprocess.TimeoutExpired:
os.killpg(pgid, signal.SIGKILL)
process.wait()
except ProcessLookupError:
pass # Already dead
# --- 6. Prompt pre-check ---
import re as _re
# OpenFOAM version patterns: "openfoam 13", "OF13", "openfoam v13", "of 13", etc.
# We detect versions that are NOT v10 (the platform version).
# Must require the full word "openfoam" — bare "of" matches noisy phrases like
# "of 300K" / "Reynolds of 4000" / "molWeight of 28.9" and produces false
# positives that previously hid the lack of platform-note injection in
# controlled mode (see Task 433/434 root-cause analysis).
# Limit to 1-2 digit versions (OF Foundation goes up to v13 currently).
_OF_VERSION_RE = _re.compile(
r'\bopenfoam[-\s_]*(?:v|version\s*)?(\d{1,2})(?!\d)',
_re.IGNORECASE
)
# Convergence tolerance pattern: "1e-7", "10^-8", "10的-7次方", "残差.*1e-7"
_CONVERGENCE_RE = _re.compile(
r'(?:residual|残差|convergence|收敛).*?'
r'(?:1e-?(\d+)|10\^-?(\d+)|10的-?(\d+)次)',
_re.IGNORECASE
)
# Platform capabilities note — always appended so Foam-Agent knows constraints.
# v10 syntax + compressible thermal gotchas verified empirically against Tasks
# 433/443/458/459/465 (buoyantFoam). Each line is here because removing it
# caused a real failure on a real user task — keep it terse but don't trim.
_PLATFORM_NOTE = (
"[PLATFORM CONSTRAINTS] "
"OpenFOAM v10 — use v10 API and syntax (not v11/v12/v13). "
"Single-core serial only — no decomposePar / runParallel. "
"Mesh: warn if > 2M cells. "
"snappyHexMesh OK with searchable primitives (Box/Cylinder/Sphere/etc.), "
"but NO STL generation — if needed, ask user to upload a Gmsh .msh. "
f"Max output: {{}}" "MB; use purgeWrite. "
# v10 syntax (always)
"v10: 'stopAt endTime' (not maxClockTime); 'Gauss upwind' (not 'bounded Gauss'). "
# Initial conditions: avoid #codeStream (sandboxed root user blocks runtime
# C++ compilation — see Foam-Agent-Comments.md §6).
"Non-uniform initial conditions: use setFields + setFieldsDict. "
"Do NOT use #codeStream — runtime C++ compilation is blocked in this sandbox. "
# Compressible thermal solvers (buoyantFoam, rhoPimpleFoam, etc.).
"Compressible thermal solvers (buoyantFoam, rhoPimpleFoam, etc.) require: "
"(1) wall function patch types with 'compressible::' prefix "
"(e.g. compressible::alphatJayatillekeWallFunction, NOT alphatWallFunction); "
"(2) fvSolution.solvers final-iteration entries for PIMPLE "
"(rhoFinal, pFinal, p_rghFinal, UFinal, hFinal, kFinal, epsilonFinal, TFinal as applicable); "
"(3) fvSchemes.divSchemes MUST include 'div(phi,K) Gauss linear' and "
"'div(phi,Ekp) Gauss linear' (kinetic / total energy projection); "
"(4) the turbulence dissipation div term uses the COMPRESSIBLE form "
"'div(((rho*nuEff)*dev2(T(grad(U))))) Gauss linear' "
"(NOT the incompressible 'div((muEff*dev2(T(grad(U)))))')."
)
def _check_prompt(prompt, job_id):
"""
Pre-check user prompt for known issues before running Foam-Agent.
Returns a list of warning dicts: [{'type': str, 'message': str}, ...]
Each warning is appended to the prompt as [PLATFORM NOTE] and logged.
The platform capabilities note is always included.
"""
warnings = []
# Always include platform capabilities
limit_mb = TASK_DISK_LIMIT_BYTES // (1024 * 1024)
warnings.append({
'type': 'platform_info',
'message': _PLATFORM_NOTE.format(limit_mb),
})
# 1. OpenFOAM version mismatch
for m in _OF_VERSION_RE.finditer(prompt):
version = int(m.group(1))
if version != 10:
warnings.append({
'type': 'of_version_mismatch',
'message': (
f"User prompt mentions OpenFOAM {version}, but this "
f"platform runs OpenFOAM v10. Use v10-compatible syntax "
f"(e.g. 'stopAt endTime' not 'stopAt maxClockTime', "
f"'Gauss upwind' not 'bounded Gauss ...', "
f"'compressible::alphatJayatillekeWallFunction' with "
f"namespace prefix)."
),
})
break
# 2. Overly strict convergence criteria
for m in _CONVERGENCE_RE.finditer(prompt):
exponent = int(m.group(1) or m.group(2) or m.group(3))
if exponent >= 6:
warnings.append({
'type': 'strict_convergence',
'message': (
f"Convergence target 1e-{exponent} is very strict for "
f"RANS simulations. Residuals of 1e-4 ~ 1e-5 are typically "
f"sufficient. Overly strict targets may cause timeout."
),
})
break
# 3. Complex simulations likely to exceed disk/memory limits
prompt_lower = prompt.lower()
_heavy_keywords = [
('LES', r'\bles\b|large.eddy.simul'),
('DES', r'\bdes\b|detached.eddy'),
('DPM', r'\bdpm\b|discrete.phase|lagrangian.particle'),
('VOF+3D', None), # handled specially below
('FWH/acoustics', r'\bfwh\b|ffowcs|acoustic|噪声仿真|声压'),
('FSI', r'\bfsi\b|fluid.structure|流固耦合|solids4foam'),
('reacting flow', r'reactingfoam|反应流|supercritical.*water.*oxidation|scwo'),
# RSM (Reynolds Stress Model): solves 6 transport equations + e/omega,
# heavier than k-eps/k-omega and prone to convergence issues. Job 445
# (Stairmand cyclone with RSM) hit OOM after uploading 195 MB.
('RSM (Reynolds Stress)', r'\brsm\b|reynolds.{0,3}stress|雷诺应力|launder.*reynolds'),
# Cyclone separators: high aspect ratio + swirling flow → typically
# large cell counts and slow convergence. Stairmand geometry is the
# canonical example.
('cyclone separator', r'cyclone.{0,5}separat|stairmand|旋风分离|cyclonic.{0,5}separat'),
]
heavy_matches = []
for label, pattern in _heavy_keywords:
if pattern and _re.search(pattern, prompt, _re.IGNORECASE):
heavy_matches.append(label)
# VOF+3D: interFoam in 3D (not 2D) tends to be very large
if _re.search(r'interfoam', prompt, _re.IGNORECASE) and not _re.search(r'2d|二维|empty.*type|两相.*2', prompt, _re.IGNORECASE):
heavy_matches.append('VOF+3D')
if heavy_matches:
warnings.append({
'type': 'heavy_simulation',
'message': (
f"This simulation involves {', '.join(heavy_matches)} which "
f"typically requires large mesh and/or high output frequency. "
f"On this single-core platform with {limit_mb}MB disk limit, "
f"use a very coarse mesh (< 500K cells), set purgeWrite to "
f"limit stored timesteps, and use a large writeInterval to "
f"reduce output size. Keep the geometry and physics as simple "
f"as possible to avoid disk/memory limits."
),
})
# Log non-platform warnings
real_warnings = [w for w in warnings if w['type'] != 'platform_info']
if real_warnings:
types = [w['type'] for w in real_warnings]
logger.info(f"Job {job_id}: prompt pre-check warnings: {types}")
for w in real_warnings:
logger.info(f" [{w['type']}] {w['message']}")
return warnings
# --- 7. Disk monitoring & subprocess helpers ---
def _get_dir_size_bytes(path):
"""Get total size of a directory in bytes (non-recursive os.scandir for speed)."""
total = 0
try:
for entry in os.scandir(path):
if entry.is_file(follow_symlinks=False):
total += entry.stat(follow_symlinks=False).st_size
elif entry.is_dir(follow_symlinks=False):
total += _get_dir_size_bytes(entry.path)
except (OSError, PermissionError):
pass
return total
def _run_subprocess_with_polling(command, cwd, env, log_path, job_id, timeout,
run_dir=None):
"""
Run a subprocess with polling for timeout, cancellation, and disk usage.
Returns:
(returncode, cancelled, timed_out, disk_exceeded) tuple.
returncode is None if cancelled, timed_out, or disk_exceeded before
natural completion.
"""
with open(log_path, 'w') as log_file:
process = subprocess.Popen(
command,
cwd=cwd,
env=env,
stdout=log_file,
stderr=log_file,
text=True,
start_new_session=True,
)
start_time = time.time()
last_disk_check = 0
cancelled = False
timed_out = False