1010import sys
1111import threading
1212import time
13+ import traceback
1314import uuid
1415from collections import deque
1516from dataclasses import asdict
@@ -47,6 +48,7 @@ def __init__(
4748 self .priority = priority
4849 self .controller_pid = controller_pid
4950 self .controller_start = controller_start
51+ self .controller_generation = 0
5052 self .detached_until : float | None = None
5153 self ._results_path = storage_root / "worker-results.json"
5254 self .tracker = ProgressTracker ()
@@ -78,6 +80,8 @@ def handle(self, request: dict[str, Any]) -> dict[str, Any]:
7880 if command == "ping" :
7981 return {"ok" : True , "status" : self ._status_locked ()}
8082 if command == "attach" :
83+ if request .get ("controller_generation" ) != self .controller_generation :
84+ return {"ok" : False , "error" : "repository worker controller ownership changed" }
8185 pid = int (request .get ("controller_pid" , 0 ))
8286 started = str (request .get ("controller_start" , "" ))
8387 if not started or process_identity (pid ) != started :
@@ -90,10 +94,13 @@ def handle(self, request: dict[str, Any]) -> dict[str, Any]:
9094 return {"ok" : False , "error" : "repository worker belongs to a live controller" }
9195 self .controller_pid = pid
9296 self .controller_start = started
97+ self .controller_generation += 1
9398 self .detached_until = None
9499 self .shutdown_requested = False
95100 return {"ok" : True , "status" : self ._status_locked ()}
96101 if command == "detach" :
102+ if request .get ("controller_generation" ) != self .controller_generation :
103+ return {"ok" : False , "error" : "repository worker controller ownership changed" }
97104 self .detached_until = time .monotonic () + _HANDOFF_GRACE_SECONDS
98105 return {"ok" : True , "status" : self ._status_locked ()}
99106 if command == "configure" :
@@ -322,6 +329,7 @@ def _status_locked(self, *, include_repository: bool = False) -> dict[str, Any]:
322329 "alive" : True ,
323330 "controller_pid" : self .controller_pid ,
324331 "controller_start" : self .controller_start ,
332+ "controller_generation" : self .controller_generation ,
325333 },
326334 "job" : self .tracker .snapshot ().to_dict (),
327335 "job_occupied" : service is not None and service .busy ,
@@ -369,6 +377,18 @@ def _repository_status_locked(self) -> dict[str, Any]:
369377 }
370378
371379 def monitor (self ) -> None :
380+ try :
381+ self ._monitor ()
382+ except Exception :
383+ with self ._lock :
384+ self .shutdown_requested = True
385+ self ._stopping = True
386+ try :
387+ traceback .print_exc ()
388+ finally :
389+ self ._stop_callback ()
390+
391+ def _monitor (self ) -> None :
372392 next_owner_check = 0.0
373393 last_owner : tuple [int , str ] | None = None
374394 controller_gone = False
@@ -429,10 +449,11 @@ def monitor(self) -> None:
429449
430450 def _queue_result (self , payload : dict [str , Any ]) -> None :
431451 result = {"id" : self ._next_result_id , "payload" : payload }
432- self ._save_results ([* self .results , result ], self ._last_acked_result_id )
433- self ._results_dirty = False
434452 self .results .append (result )
435453 self ._next_result_id += 1
454+ self ._results_dirty = True
455+ self ._save_results (list (self .results ), self ._last_acked_result_id )
456+ self ._results_dirty = False
436457
437458 def _load_results (self ) -> None :
438459 try :
@@ -463,12 +484,28 @@ def _save_results(self, results: list[dict[str, Any]], last_acked: int) -> None:
463484 def close (self ) -> None :
464485 with self ._lock :
465486 service = self .service
466- self .service = None
467- if self ._results_dirty :
468- self ._save_results (list (self .results ), self ._last_acked_result_id )
469- self ._results_dirty = False
470- if service is not None :
471- service .close ()
487+ self ._stopping = True
488+ try :
489+ if service is not None :
490+ service .close ()
491+ try :
492+ result = service .poll ()
493+ except Exception as exc :
494+ payload = {"kind" : "error" , "error" : str (exc )}
495+ else :
496+ payload = asdict (result ) if result is not None else None
497+ if payload is not None :
498+ with self ._lock :
499+ if self ._active_request_id is not None :
500+ payload ["request_id" ] = self ._active_request_id
501+ self ._queue_result (payload )
502+ self ._active_request_id = None
503+ finally :
504+ with self ._lock :
505+ self .service = None
506+ if self ._results_dirty :
507+ self ._save_results (list (self .results ), self ._last_acked_result_id )
508+ self ._results_dirty = False
472509
473510
474511class _RequestHandler (socketserver .BaseRequestHandler ):
@@ -622,6 +659,8 @@ def _run_worker(
622659 try :
623660 server .serve_forever (poll_interval = 0.2 )
624661 finally :
625- app .close ()
626- _remove_runtime (runtime_file , instance_id )
662+ try :
663+ app .close ()
664+ finally :
665+ _remove_runtime (runtime_file , instance_id )
627666 return 0
0 commit comments