task_executor.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. """Task executor for local simulation system (P4-M2).
  2. Listens for tasks dispatched from Web backend, executes Motor-CAD
  3. simulations via RobustMotorCADSolver, reports progress and results.
  4. NOTE: All strings must be ASCII only. Chinese text uses \\uXXXX escapes.
  5. """
  6. import json
  7. import os
  8. import sys
  9. import time
  10. import uuid
  11. import threading
  12. from datetime import datetime
  13. from pathlib import Path
  14. from typing import Dict, List, Optional, Any, Callable
  15. try:
  16. import requests
  17. except ImportError:
  18. requests = None
  19. # Add scripts directory to path for robust_motorcad import
  20. _SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
  21. if _SCRIPTS_DIR not in sys.path:
  22. sys.path.insert(0, _SCRIPTS_DIR)
  23. class TaskExecutor:
  24. """Executes simulation tasks dispatched from Web backend."""
  25. def __init__(
  26. self,
  27. web_base_url: str = "http://127.0.0.1:8000",
  28. task_dir: Optional[str] = None,
  29. on_progress: Optional[Callable] = None,
  30. on_complete: Optional[Callable] = None,
  31. on_error: Optional[Callable] = None,
  32. enable_mock: bool = False,
  33. executor_id: Optional[str] = None,
  34. ):
  35. self.web_base_url = web_base_url.rstrip("/")
  36. self.task_dir = task_dir or os.path.join(
  37. os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  38. "output", "tasks"
  39. )
  40. os.makedirs(self.task_dir, exist_ok=True)
  41. self.on_progress = on_progress
  42. self.on_complete = on_complete
  43. self.on_error = on_error
  44. self.enable_mock = enable_mock
  45. self._running = False
  46. self._current_task: Optional[Dict[str, Any]] = None
  47. self._stop_event = threading.Event()
  48. if executor_id is not None:
  49. self.executor_id = executor_id
  50. else:
  51. self.executor_id = "motorcad-executor-%s-%s" % (os.getpid(), uuid.uuid4().hex[:4])
  52. def fetch_pending_tasks(self) -> List[Dict[str, Any]]:
  53. """Fetch claimable tasks from Web backend.
  54. Web's start-simulation marks tasks as 'dispatched' immediately, while
  55. tasks created via the tasks API stay 'pending'. The executor claims
  56. BOTH states so every task gets picked up regardless of creation path.
  57. """
  58. if requests is None:
  59. return self._scan_local_task_files()
  60. tasks = []
  61. for st in ("pending", "dispatched"):
  62. try:
  63. resp = requests.get(
  64. f"{self.web_base_url}/api/tasks",
  65. params={"status": st, "limit": 20},
  66. timeout=10,
  67. )
  68. if resp.status_code == 200:
  69. data = resp.json()
  70. tasks.extend(data.get("tasks", []))
  71. except Exception as e:
  72. if self.on_error:
  73. self.on_error(f"Fetch tasks failed: {str(e)}")
  74. # De-duplicate by task_id (keep first occurrence)
  75. seen = set()
  76. result = []
  77. for t in tasks:
  78. tid = t.get("task_id")
  79. if tid and tid not in seen:
  80. seen.add(tid)
  81. result.append(t)
  82. return result
  83. def _hydrate_task(self, task: Dict[str, Any]) -> Dict[str, Any]:
  84. """Fetch full task payload (parameters + plan_data) from Web backend.
  85. The list API only returns task metadata; the actual parameter sets
  86. live in the task.json file exposed by the download endpoint.
  87. """
  88. if requests is None:
  89. return task
  90. tid = task.get("task_id")
  91. if not tid:
  92. return task
  93. try:
  94. resp = requests.get(
  95. f"{self.web_base_url}/api/tasks/{tid}/download",
  96. timeout=10,
  97. )
  98. if resp.status_code == 200:
  99. full = resp.json()
  100. if isinstance(full, dict):
  101. if full.get("parameters"):
  102. task = {**task, **full}
  103. elif task.get("_local_file"):
  104. # local file fallback
  105. try:
  106. with open(task["_local_file"], "r", encoding="utf-8") as f:
  107. local = json.load(f)
  108. if local.get("parameters"):
  109. task = {**task, **local}
  110. except Exception:
  111. pass
  112. except Exception as e:
  113. if self.on_error:
  114. self.on_error(f"Hydrate task {tid} failed: {str(e)}")
  115. return task
  116. def _scan_local_task_files(self) -> List[Dict[str, Any]]:
  117. """Scan local task directory for task files (fallback mode).
  118. Only picks up *_task.json files. Completed tasks are renamed
  119. to *_task.done.json to prevent infinite re-execution (B7 fix).
  120. """
  121. tasks = []
  122. for fname in os.listdir(self.task_dir):
  123. if fname.endswith("_task.json") and not fname.endswith("_task.done.json"):
  124. fpath = os.path.join(self.task_dir, fname)
  125. try:
  126. with open(fpath, "r", encoding="utf-8") as f:
  127. task = json.load(f)
  128. task["_local_file"] = fpath
  129. tasks.append(task)
  130. except Exception:
  131. continue
  132. return tasks
  133. def _mark_local_task_done(self, task: Dict[str, Any]) -> None:
  134. """Rename completed local task file to prevent re-execution (B7 fix)."""
  135. fpath = task.get("_local_file")
  136. if fpath and os.path.exists(fpath):
  137. done_path = fpath.replace("_task.json", "_task.done.json")
  138. try:
  139. os.rename(fpath, done_path)
  140. except Exception as e:
  141. if self.on_error:
  142. self.on_error(f"Failed to mark task done: {str(e)}")
  143. def dispatch_task(self, task_id: str) -> bool:
  144. """Mark task as dispatched on Web backend."""
  145. if requests is None:
  146. return True
  147. try:
  148. resp = requests.post(
  149. f"{self.web_base_url}/api/tasks/{task_id}/dispatch",
  150. timeout=10,
  151. )
  152. return resp.status_code in (200, 201)
  153. except Exception as e:
  154. if self.on_error:
  155. self.on_error(f"Dispatch task {task_id} failed: {str(e)}")
  156. return False
  157. def report_progress(
  158. self,
  159. task_id: str,
  160. current_point: int,
  161. total_points: int,
  162. current_params: Optional[Dict[str, Any]] = None,
  163. elapsed_time: Optional[float] = None,
  164. ) -> bool:
  165. """Report simulation progress to Web backend."""
  166. if requests is None:
  167. if self.on_progress:
  168. self.on_progress(task_id, current_point, total_points)
  169. return True
  170. try:
  171. payload = {
  172. "current_point": current_point,
  173. "total_points": total_points,
  174. "current_params": current_params,
  175. "elapsed_time": elapsed_time,
  176. }
  177. resp = requests.post(
  178. f"{self.web_base_url}/api/tasks/{task_id}/progress",
  179. json=payload,
  180. timeout=10,
  181. )
  182. return resp.status_code == 200
  183. except Exception as e:
  184. if self.on_error:
  185. self.on_error(f"Report progress failed: {str(e)}")
  186. return False
  187. def report_results(
  188. self,
  189. task_id: str,
  190. results: List[Dict[str, Any]],
  191. metrics: Optional[Dict[str, Any]] = None,
  192. logs: Optional[str] = None,
  193. duration: Optional[float] = None,
  194. status: str = "completed",
  195. ) -> bool:
  196. """Report final results to Web backend."""
  197. if requests is None:
  198. if self.on_complete:
  199. self.on_complete(task_id, results, metrics)
  200. return True
  201. try:
  202. payload = {
  203. "results": results,
  204. "metrics": metrics,
  205. "logs": logs,
  206. "duration": duration,
  207. "status": status,
  208. }
  209. resp = requests.post(
  210. f"{self.web_base_url}/api/tasks/{task_id}/results",
  211. json=payload,
  212. timeout=30,
  213. )
  214. return resp.status_code == 200
  215. except Exception as e:
  216. if self.on_error:
  217. self.on_error(f"Report results failed: {str(e)}")
  218. return False
  219. def _report_to_adaptive_loop(
  220. self, task: Dict[str, Any], results: List[Dict[str, Any]]
  221. ) -> None:
  222. """Feed an adaptive_batch task's results back into its loop.
  223. Maps each point result to {point_id, metrics, status} and posts to the
  224. loop's report-results endpoint. Best-effort: a failure here must not
  225. break normal task reporting (results are already stored on the task).
  226. """
  227. if requests is None:
  228. return
  229. if task.get("task_type") != "adaptive_batch":
  230. return
  231. loop_id = task.get("loop_id")
  232. if not loop_id:
  233. return
  234. point_results = []
  235. for r in results:
  236. pid = r.get("point_id")
  237. if pid is None:
  238. continue
  239. point_results.append({
  240. "point_id": pid,
  241. "metrics": r.get("metrics") or {},
  242. "status": "ok" if r.get("status") == "OK" else "failed",
  243. })
  244. if not point_results:
  245. return
  246. try:
  247. resp = requests.post(
  248. f"{self.web_base_url}/api/adaptive/loops/{loop_id}/report-results",
  249. json={"point_results": point_results},
  250. timeout=120,
  251. )
  252. if self.on_progress:
  253. self.on_progress(
  254. f"Adaptive loop {loop_id}: reported {len(point_results)} "
  255. f"points (HTTP {resp.status_code})"
  256. )
  257. except Exception as e:
  258. if self.on_error:
  259. self.on_error(f"Adaptive loop report failed ({loop_id}): {str(e)}")
  260. def execute_task(self, task: Dict[str, Any]) -> None:
  261. """Execute a single simulation task.
  262. This is a template method. Override _run_simulation_point in
  263. subclasses to implement actual Motor-CAD simulation.
  264. """
  265. task = self._hydrate_task(task)
  266. task_id = task.get("task_id", str(uuid.uuid4())[:8])
  267. parameters = task.get("parameters", [])
  268. total_points = len(parameters)
  269. results = []
  270. start_time = time.time()
  271. self._current_task = task
  272. # start-simulation already marks a task 'dispatched' at creation, while
  273. # tasks created via the tasks API stay 'pending'. Only claim (dispatch)
  274. # a task that is still pending; re-dispatching an already-dispatched
  275. # task is rejected by the backend (pending -> dispatched only) and
  276. # would otherwise be misreported as "not claimable".
  277. claimed = True
  278. if task.get("status") == "pending":
  279. claimed = self.dispatch_task(task_id)
  280. if not claimed:
  281. # Another instance already claimed this task; skip it so
  282. # parallel executors never duplicate the same simulation.
  283. if self.on_error:
  284. self.on_error("Task %s not claimable (claimed/network); skip" % task_id)
  285. self._current_task = None
  286. return
  287. for idx, params in enumerate(parameters):
  288. if self._stop_event.is_set():
  289. break
  290. elapsed = time.time() - start_time
  291. self.report_progress(task_id, idx, total_points, params, elapsed)
  292. try:
  293. point_result = self._run_simulation_point(params, idx)
  294. point_result["point_index"] = idx
  295. if "point_id" in params:
  296. point_result["point_id"] = params["point_id"]
  297. point_result["params"] = params
  298. results.append(point_result)
  299. except Exception as e:
  300. # A2 fix: failed points are recorded as failed, NOT mock data
  301. failed_result = {
  302. "point_index": idx,
  303. "params": params,
  304. "status": "FAILED",
  305. "error": str(e),
  306. }
  307. if "point_id" in params:
  308. failed_result["point_id"] = params["point_id"]
  309. results.append(failed_result)
  310. if self.on_error:
  311. self.on_error(f"Point {idx} failed: {str(e)}")
  312. duration = time.time() - start_time
  313. metrics = self._compute_metrics(results)
  314. # Status reflects actual outcome: completed/cancelled/failed
  315. if self._stop_event.is_set():
  316. status = "cancelled"
  317. elif any(r.get("status") == "FAILED" for r in results):
  318. status = "completed_with_errors" if any(
  319. r.get("status") == "OK" for r in results
  320. ) else "failed"
  321. else:
  322. status = "completed"
  323. self.report_results(task_id, results, metrics, None, duration, status)
  324. self.report_progress(task_id, total_points, total_points, None, duration)
  325. # Adaptive-loop bridge: an adaptive_batch task belongs to a loop; feed
  326. # per-point results back to /adaptive/loops/{loop_id}/report-results so
  327. # the search advances without manual intervention (P3-M5 gap closure).
  328. self._report_to_adaptive_loop(task, results)
  329. # B7 fix: mark local task file as done to prevent re-execution
  330. if requests is None:
  331. self._mark_local_task_done(task)
  332. self._current_task = None
  333. if self.on_complete:
  334. self.on_complete(task_id, results, metrics)
  335. def _run_simulation_point(self, params: Dict[str, Any], index: int) -> Dict[str, Any]:
  336. """Run a single simulation point. Override in subclass.
  337. Mock data is ONLY returned when enable_mock=True (explicit opt-in).
  338. Mock results are tagged with source="mock" so they can never be
  339. confused with real simulation data (A2 fix).
  340. """
  341. if not self.enable_mock:
  342. raise RuntimeError(
  343. "No simulation backend configured. "
  344. "Use MotorCADTaskExecutor for real Motor-CAD simulation, "
  345. "or set enable_mock=True for testing."
  346. )
  347. import random
  348. rng = random.Random(index + hash(json.dumps(params, sort_keys=True)) % 10000)
  349. airgap = params.get("airgap_mm", 1.0)
  350. current = params.get("current_a", 15.0)
  351. return {
  352. "tavg_nm": round(current * 2.5 / (airgap ** 0.5) + rng.gauss(0, 0.3), 4),
  353. "efficiency_pct": round(88 + rng.gauss(0, 2), 2),
  354. "total_losses_w": round(50 + rng.gauss(0, 10), 2),
  355. "winding_temp_c": round(90 + rng.gauss(0, 10), 1),
  356. "status": "OK",
  357. "source": "mock",
  358. }
  359. def _compute_metrics(self, results: List[Dict[str, Any]]) -> Dict[str, Any]:
  360. """Compute aggregated metrics from results."""
  361. ok_results = [r for r in results if r.get("status") == "OK"]
  362. if not ok_results:
  363. return {
  364. "total_points": len(results),
  365. "successful_points": 0,
  366. "failed_points": len(results),
  367. }
  368. metrics = {
  369. "total_points": len(results),
  370. "successful_points": len(ok_results),
  371. "failed_points": len(results) - len(ok_results),
  372. }
  373. for key in ["tavg_nm", "efficiency_pct", "total_losses_w", "winding_temp_c"]:
  374. values = [r[key] for r in ok_results if key in r]
  375. if values:
  376. metrics[f"{key}_min"] = min(values)
  377. metrics[f"{key}_max"] = max(values)
  378. metrics[f"{key}_mean"] = round(sum(values) / len(values), 4)
  379. return metrics
  380. def _send_heartbeat(self) -> None:
  381. """Register this executor with the Web backend (online status)."""
  382. if requests is None:
  383. return
  384. try:
  385. status = "running" if self._current_task is not None else "idle"
  386. current_task = None
  387. progress = None
  388. if self._current_task is not None:
  389. current_task = self._current_task.get("task_id")
  390. total = self._current_task.get("total_points") or 0
  391. done = self._current_task.get("completed_points") or 0
  392. progress = {
  393. "completed_points": done,
  394. "total_points": total,
  395. }
  396. requests.post(
  397. f"{self.web_base_url}/api/executor/heartbeat",
  398. json={
  399. "executor_id": self.executor_id,
  400. "status": status,
  401. "current_task": current_task,
  402. "progress": progress,
  403. },
  404. timeout=5,
  405. )
  406. except Exception:
  407. # Heartbeat failures are non-fatal
  408. pass
  409. def start_polling(self, interval: int = 5) -> threading.Thread:
  410. """Start background threads: one polls/executes tasks, one heartbeats.
  411. Heartbeat runs on its own thread so a long-running Motor-CAD point
  412. (~2 min each) never starves the heartbeat - otherwise the backend
  413. would mark this executor offline mid-task (observed 2026-09-04).
  414. """
  415. self._running = True
  416. self._stop_event.clear()
  417. def heartbeat_loop():
  418. while self._running and not self._stop_event.is_set():
  419. self._send_heartbeat()
  420. self._stop_event.wait(interval)
  421. def poll_loop():
  422. while self._running and not self._stop_event.is_set():
  423. try:
  424. tasks = self.fetch_pending_tasks()
  425. for task in tasks:
  426. if self._stop_event.is_set():
  427. break
  428. self.execute_task(task)
  429. except Exception as e:
  430. if self.on_error:
  431. self.on_error(f"Poll loop error: {str(e)}")
  432. self._stop_event.wait(interval)
  433. hb_thread = threading.Thread(target=heartbeat_loop, daemon=True)
  434. hb_thread.start()
  435. thread = threading.Thread(target=poll_loop, daemon=True)
  436. thread.start()
  437. return thread
  438. def stop(self):
  439. """Stop the executor."""
  440. self._running = False
  441. self._stop_event.set()
  442. class MotorCADTaskExecutor(TaskExecutor):
  443. """Task executor backed by a registered simulation-tool adapter.
  444. Uses afmcore.adapters.get_adapter(tool) so the executor never
  445. hard-codes a specific solver. Default tool "motorcad" wraps
  446. RobustMotorCADSolver (open_new_instance, set_visible, baseline
  447. reload per point, popup suppression, write-back verification,
  448. per-point disk flush).
  449. Result mapping: adapter returns {metrics, status, error, ...}; the
  450. metrics dict is flattened to the point's top level so downstream
  451. aggregation (TaskExecutor._compute_metrics) keeps working unchanged.
  452. """
  453. def __init__(self, *args, model_path: Optional[str] = None,
  454. tool: str = "motorcad",
  455. enable_thermal: bool = False, **kwargs):
  456. # Mock fallback is disabled by default for real solver adapter.
  457. kwargs.setdefault("enable_mock", False)
  458. super().__init__(*args, **kwargs)
  459. self.model_path = model_path
  460. self.tool = tool
  461. # P5-M6: pass through to the adapter so each EM point can also run a
  462. # steady-state thermal solve and merge thermal metrics.
  463. self.enable_thermal = bool(enable_thermal)
  464. self._adapter = None
  465. def _ensure_adapter(self):
  466. """Lazily create the tool adapter via the platform registry."""
  467. if self._adapter is not None:
  468. return self._adapter
  469. _root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  470. _src = os.path.join(_root, "src")
  471. if _src not in sys.path:
  472. sys.path.insert(0, _src)
  473. from afmcore.adapters import get_adapter
  474. # Dynamically import the adapter module matching self.tool so it
  475. # self-registers in ADAPTER_REGISTRY. Unknown tools rely on
  476. # pre-registered adapters (caller may have imported them).
  477. if self.tool == "motorcad":
  478. import afmcore.adapters.motorcad # noqa: F401
  479. elif self.tool == "maxwell":
  480. import afmcore.adapters.maxwell # noqa: F401
  481. elif self.tool == "jmag":
  482. import afmcore.adapters.jmag # noqa: F401
  483. if not self.model_path:
  484. raise RuntimeError("model_path is required for MotorCADTaskExecutor")
  485. output_dir = os.path.join(
  486. _root, "output", "task_%s" % datetime.now().strftime("%Y%m%d_%H%M%S")
  487. )
  488. self._adapter = get_adapter(
  489. self.tool, model_path=self.model_path, output_dir=output_dir,
  490. enable_thermal=self.enable_thermal,
  491. )
  492. self._adapter.connect()
  493. return self._adapter
  494. def _run_simulation_point(self, params: Dict[str, Any], index: int) -> Dict[str, Any]:
  495. """Run one point through the adapter and flatten metrics to top level.
  496. The adapter owns the robust protocol (baseline reload, write-back
  497. verification, export parsing). A non-OK point raises so execute_task
  498. records status=FAILED (no mock fallback).
  499. When enable_mock=True the base-class mock implementation is used
  500. instead, so no Motor-CAD instance is launched at all (P5-M2).
  501. """
  502. if self.enable_mock:
  503. return super()._run_simulation_point(params, index)
  504. adapter = self._ensure_adapter()
  505. result = adapter.run_point(
  506. self.model_path, params=params,
  507. output_dir=os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
  508. tag=str(index),
  509. )
  510. if result.get("status") != "OK":
  511. raise RuntimeError(
  512. result.get("error") or ("Simulation failed (adapter status=%s)"
  513. % result.get("status"))
  514. )
  515. metrics = result.get("metrics") or {}
  516. point = dict(metrics)
  517. point["status"] = "OK"
  518. point["metrics"] = metrics
  519. point["error"] = result.get("error")
  520. point["solve_time_s"] = result.get("solve_time_s")
  521. return point
  522. def cleanup(self):
  523. """Disconnect the adapter and release the tool instance."""
  524. if self._adapter is not None:
  525. try:
  526. self._adapter.disconnect()
  527. except Exception:
  528. pass
  529. self._adapter = None
  530. if __name__ == "__main__":
  531. # Standalone test: run executor with mock data (explicit)
  532. executor = TaskExecutor(
  533. web_base_url=os.environ.get("WEB_BASE_URL", "http://127.0.0.1:8000"),
  534. on_progress=lambda tid, cur, tot: print(f"[{tid}] Progress: {cur}/{tot}"),
  535. on_complete=lambda tid, res, met: print(f"[{tid}] Complete: {len(res)} points"),
  536. on_error=lambda msg: print(f"ERROR: {msg}"),
  537. enable_mock=True,
  538. )
  539. print("Task executor started (mock mode). Press Ctrl+C to stop.")
  540. try:
  541. thread = executor.start_polling(interval=5)
  542. while thread.is_alive():
  543. time.sleep(1)
  544. except KeyboardInterrupt:
  545. executor.stop()
  546. print("Executor stopped.")