Skip to content

Commit 0800990

Browse files
committed
fix: fence delayed handoffs and drain worker safely after persistence errors
1 parent 6066404 commit 0800990

4 files changed

Lines changed: 241 additions & 35 deletions

File tree

‎docs/using-endkeep.md‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -74,16 +74,14 @@ Follow the [Recovery guide](recovery.md) before replacing a live world.
7474

7575
## Server shutdown and plugin reload
7676

77-
EndKeep lets a running repository job finish when the server stops, including
78-
an unexpected server process exit. The worker then exits on its own; completed
79-
results remain available on the next startup even if the old plugin did not
80-
acknowledge them. Large jobs can take longer to finish than an idle worker.
81-
82-
Plugin disable starts a 15-second handoff window. A newly enabled instance can
83-
reconnect during that window without cancelling an ongoing repository job. If
84-
the plugin stays unloaded, the worker finishes its current job and exits.
85-
86-
Startup retries a temporarily unavailable worker for a bounded period. If a
87-
verified live worker still cannot respond, EndKeep refuses to start another
88-
writer and logs its PID, creation identity and last RPC error. Preserve the
89-
backup directory and inspect `backups/worker.log` before taking further action.
77+
On server shutdown, the worker finishes its current repository job and exits.
78+
This also applies after an unexpected server process exit. Unacknowledged
79+
results are recovered on the next startup.
80+
81+
Plugin disable allows 15 seconds for a newly enabled instance to reconnect.
82+
Running repository jobs continue through the handoff. If the plugin stays
83+
unloaded, the worker finishes its job and exits.
84+
85+
Startup briefly retries an unavailable worker. If it remains alive but cannot
86+
respond, EndKeep refuses a second writer. Check `backups/worker.log` and keep
87+
the backup directory intact.

‎src/endstone_endkeep/worker/client.py‎

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ def __init__(self, runtime_path: Path, runtime: RuntimeInfo, *, desired_priority
4343
self.runtime = runtime
4444
self.desired_priority = desired_priority
4545
self._status: dict[str, Any] = {"job": {"state": "idle"}}
46+
self._controller_generation: int | None = None
4647

4748
@classmethod
4849
def connect_or_start(cls, storage_root: Path, *, priority: str) -> RepositoryWorkerClient:
@@ -83,15 +84,29 @@ def connect_or_start(cls, storage_root: Path, *, priority: str) -> RepositoryWor
8384
raise WorkerError("cannot identify the current controller process")
8485
try:
8586
response = client._rpc(
86-
{"command": "attach", "controller_pid": os.getpid(), "controller_start": identity},
87+
{
88+
"command": "attach",
89+
"controller_pid": os.getpid(),
90+
"controller_start": identity,
91+
"controller_generation": worker.get("controller_generation"),
92+
},
8793
timeout=1.0,
8894
)
89-
except WorkerRejected as exc:
90-
if str(exc) != "repository worker is exiting":
91-
raise
92-
cls._wait_for_exit(existing.pid, runtime_path, process_start=existing.process_start)
93-
break
95+
except WorkerError as exc:
96+
if isinstance(exc, WorkerRejected):
97+
if str(exc) == "repository worker is exiting":
98+
cls._wait_for_exit(existing.pid, runtime_path, process_start=existing.process_start)
99+
break
100+
if str(exc) != "repository worker controller ownership changed":
101+
raise
102+
last_error = exc
103+
if not cls._runtime_alive(existing):
104+
break
105+
if attempt < 3:
106+
time.sleep(0.2)
107+
continue
94108
client._status = response["status"]
109+
client._controller_generation = client._status["worker"].get("controller_generation")
95110
needs_restart = existing.priority != priority or existing.version != package_version()
96111
if needs_restart and not client.busy:
97112
client.shutdown()
@@ -188,6 +203,7 @@ def _start(cls, storage_root: Path, runtime_path: Path, priority: str) -> Reposi
188203
last_error = exc
189204
else:
190205
client._status = response["status"]
206+
client._controller_generation = client._status["worker"].get("controller_generation")
191207
return client
192208
time.sleep(0.05)
193209

@@ -439,7 +455,7 @@ def detach(self) -> None:
439455
# A reload can reclaim the worker within the handoff window; the worker
440456
# also watches the BDS process identity to detect an actual server exit.
441457
try:
442-
self._rpc({"command": "detach"}, timeout=0.5)
458+
self._rpc({"command": "detach", "controller_generation": self._controller_generation}, timeout=0.5)
443459
except WorkerRejected as exc:
444460
if "unknown worker command" not in str(exc):
445461
raise

‎src/endstone_endkeep/worker/server.py‎

Lines changed: 49 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import sys
1111
import threading
1212
import time
13+
import traceback
1314
import uuid
1415
from collections import deque
1516
from 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

474511
class _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

Comments
 (0)