Skip to content

Commit dfbb08e

Browse files
committed
fix: cancel abandoned worker jobs at safe checkpoints
1 parent 1d4e10b commit dfbb08e

20 files changed

Lines changed: 545 additions & 72 deletions

‎docs/using-endkeep.md‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,8 @@ Commands are available to the console and operators by default (`endkeep.admin`)
3434

3535
Deleting or rolling over a snapshot is a two-step operation: run the command
3636
to view what will change, then run `/backup confirm`. Preview information is
37-
cleared on reload or restart. Export, delete and rollover jobs cannot be
38-
cancelled once accepted. Make an independent copy before changing recovery history.
37+
cleared on reload or restart. Delete and rollover jobs can be cancelled before the atomic commit; exports
38+
can also be cancelled. Make an independent copy before changing recovery history.
3939

4040
## Automatic backups
4141

@@ -74,13 +74,15 @@ Follow the [Recovery guide](recovery.md) before replacing a live world.
7474

7575
## Server shutdown and plugin reload
7676

77-
On server shutdown, the worker finishes its current repository job and exits.
77+
On server shutdown, the worker cancels background work at a safe checkpoint and
78+
exits. An atomic commit already in progress finishes first; uncommitted RAW
79+
snapshots remain available for the next startup.
7880
This also applies after an unexpected server process exit. Unacknowledged
7981
results are recovered on the next startup.
8082

8183
Plugin disable allows 15 seconds for a newly enabled instance to reconnect.
8284
Running repository jobs continue through the handoff. If the plugin stays
83-
unloaded, the worker finishes its job and exits.
85+
unloaded, the worker safely cancels its job and exits.
8486

8587
Startup briefly retries an unavailable worker. If it remains alive but cannot
8688
respond, EndKeep refuses a second writer. Check `backups/worker.log` and keep

‎src/endstone_endkeep/logical/diff.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ def compose_delta_pair(
121121
first: Iterable[DeltaOperation],
122122
second: Iterable[DeltaOperation],
123123
stats: DiffStats,
124+
*,
125+
progress: Callable[[int], None] | None = None,
124126
) -> Iterator[DeltaOperation]:
125127
"""Build the minimal previous-to-successor DELTA in one bounded-memory pass.
126128
@@ -136,8 +138,13 @@ def compose_delta_pair(
136138
first_item = next(first_it, missing)
137139
second_item = next(second_it, missing)
138140
last_key: bytes | None = None
141+
processed = 0
139142

140143
while previous_item is not missing or first_item is not missing or second_item is not missing:
144+
if progress is not None:
145+
processed += 1
146+
if processed % 16384 == 0:
147+
progress(16384)
141148
keys = []
142149
if previous_item is not missing:
143150
keys.append(previous_item[0])

‎src/endstone_endkeep/logical/merge.py‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,20 @@ class MergeError(ValueError):
1717
def apply_delta(
1818
state: Iterable[tuple[bytes, bytes]],
1919
delta: Iterable[DeltaOperation],
20+
*,
21+
cancel_check: Callable[[], None] | None = None,
2022
) -> Iterator[tuple[bytes, bytes]]:
2123
state_it = iter(state)
2224
delta_it = iter(delta)
2325
state_item = next(state_it, _SENTINEL)
2426
operation = next(delta_it, _SENTINEL)
27+
consumed = 0
2528

2629
while state_item is not _SENTINEL or operation is not _SENTINEL:
30+
if cancel_check is not None:
31+
consumed += 1
32+
if consumed % 16384 == 0:
33+
cancel_check()
2734
if operation is _SENTINEL:
2835
yield state_item
2936
state_item = next(state_it, _SENTINEL)

‎src/endstone_endkeep/logical/sidecar.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from __future__ import annotations
22

33
import os
4-
from collections.abc import Iterable
4+
from collections.abc import Callable, Iterable
55
from dataclasses import dataclass
66
from pathlib import Path, PurePosixPath
77
from typing import BinaryIO
@@ -23,6 +23,8 @@ def write_sidecar(
2323
stream: BinaryIO,
2424
raw_snapshot_root: Path,
2525
entries: Iterable[SnapshotEntry],
26+
*,
27+
cancel_check: Callable[[], None] | None = None,
2628
) -> SidecarStats:
2729
stream.write(SIDECAR_MAGIC)
2830
ordered = sorted(entries, key=lambda entry: entry.path.as_posix())
@@ -31,6 +33,8 @@ def write_sidecar(
3133
total_bytes = 0
3234

3335
for entry in ordered:
36+
if cancel_check is not None:
37+
cancel_check()
3438
path_text = entry.path.as_posix()
3539
if previous is not None and path_text <= previous:
3640
raise LogicalFormatError("SIDECAR paths must be strictly increasing")
@@ -43,6 +47,8 @@ def write_sidecar(
4347
with path.open("rb") as source:
4448
remaining = entry.snapshot_bytes
4549
while remaining:
50+
if cancel_check is not None:
51+
cancel_check()
4652
chunk = source.read(min(1024 * 1024, remaining))
4753
if not chunk:
4854
raise LogicalFormatError(f"SIDECAR source is short: {entry.path}")
@@ -65,6 +71,7 @@ def extract_sidecar(
6571
destination_root: Path,
6672
*,
6773
strip_prefix: str | None = None,
74+
cancel_check: Callable[[], None] | None = None,
6875
) -> SidecarStats:
6976
if _read_exact(stream, len(SIDECAR_MAGIC)) != SIDECAR_MAGIC:
7077
raise LogicalFormatError("invalid SIDECAR magic/version")
@@ -75,6 +82,8 @@ def extract_sidecar(
7582
total_bytes = 0
7683

7784
while True:
85+
if cancel_check is not None:
86+
cancel_check()
7887
first = stream.read(1)
7988
if not first:
8089
break
@@ -117,6 +126,8 @@ def extract_sidecar(
117126
try:
118127
remaining = size
119128
while remaining:
129+
if cancel_check is not None:
130+
cancel_check()
120131
chunk = stream.read(min(1024 * 1024, remaining))
121132
if not chunk:
122133
raise LogicalFormatError(f"truncated SIDECAR file: {path_text!r}")

‎src/endstone_endkeep/offline/cli.py‎

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,7 @@ def _verify_restore_dependencies(
129129
*,
130130
verbose: bool,
131131
show_progress: bool,
132+
cancel_check: Callable[[], None] | None = None,
132133
) -> None:
133134
"""Deep-verify only the immutable objects required to restore one snapshot."""
134135

@@ -151,7 +152,7 @@ def _verify_restore_dependencies(
151152
f"logical_bytes={metadata.logical_bytes} compressed_bytes={metadata.compressed_bytes}",
152153
enabled=verbose,
153154
)
154-
objects.verify(metadata)
155+
objects.verify(metadata, cancel_check=cancel_check)
155156
if bar is not None:
156157
bar.update(1)
157158
_verbose(
@@ -391,7 +392,10 @@ def command_restore(
391392
preflight: Callable[[SnapshotNode], None] | None = None,
392393
space_guard: Callable[[], None] | None = None,
393394
progress: Callable[[int, int], None] | None = None,
395+
cancel_check: Callable[[], None] | None = None,
394396
) -> int:
397+
if cancel_check is not None:
398+
cancel_check()
395399
if destination.exists():
396400
raise FileExistsError(f"restore destination already exists: {destination}")
397401

@@ -417,6 +421,7 @@ def command_restore(
417421
node,
418422
verbose=verbose,
419423
show_progress=show_progress,
424+
cancel_check=cancel_check,
420425
)
421426

422427
destination.parent.mkdir(parents=True, exist_ok=True)
@@ -427,7 +432,7 @@ def command_restore(
427432
print(file=sys.stderr)
428433
_stage(2, 5, "Restoring SIDECAR")
429434
with objects.open_logical(node.sidecar) as stream:
430-
sidecar = extract_sidecar(stream, destination, strip_prefix=node.world_name)
435+
sidecar = extract_sidecar(stream, destination, strip_prefix=node.world_name, cancel_check=cancel_check)
431436
_verbose(
432437
f"SIDECAR files={sidecar.files} bytes={sidecar.bytes} elapsed={time.perf_counter() - started:.3f}s",
433438
enabled=verbose,
@@ -437,7 +442,7 @@ def command_restore(
437442

438443
if space_guard is not None:
439444
space_guard()
440-
state = reader.iter_state(manifest, snapshot=node.snapshot)
445+
state = reader.iter_state(manifest, snapshot=node.snapshot, cancel_check=cancel_check)
441446
if show_progress:
442447
print(file=sys.stderr)
443448
_stage(3, 5, "Rebuilding LevelDB")
@@ -456,6 +461,8 @@ def command_restore(
456461

457462
def on_written(amount: int) -> None:
458463
nonlocal completed_records
464+
if cancel_check is not None:
465+
cancel_check()
459466
completed_records += amount
460467
if rebuild_bar is not None:
461468
rebuild_bar.update(amount)
@@ -464,7 +471,9 @@ def on_written(amount: int) -> None:
464471
if space_guard is not None:
465472
space_guard()
466473

467-
callback_enabled = rebuild_bar is not None or progress is not None or space_guard is not None
474+
callback_enabled = (
475+
rebuild_bar is not None or progress is not None or space_guard is not None or cancel_check is not None
476+
)
468477
try:
469478
records, value_bytes = write_fresh_leveldb(
470479
destination / "db",
@@ -498,11 +507,18 @@ def on_written(amount: int) -> None:
498507
if show_progress
499508
else None
500509
)
510+
511+
def on_verified(amount: int) -> None:
512+
if cancel_check is not None:
513+
cancel_check()
514+
if verify_bar is not None:
515+
verify_bar.update(amount)
516+
501517
try:
502518
with iter_visible_state(destination / "db") as reopened:
503519
reopened_stats = hash_state(
504520
reopened,
505-
progress=verify_bar.update if verify_bar is not None else None,
521+
progress=on_verified if verify_bar is not None or cancel_check is not None else None,
506522
)
507523
finally:
508524
if verify_bar is not None:
@@ -525,7 +541,9 @@ def on_written(amount: int) -> None:
525541
print(file=sys.stderr)
526542
_stage(5, 5, "Flushing restored world")
527543
started = time.perf_counter()
528-
_fsync_tree(destination)
544+
if cancel_check is not None:
545+
cancel_check()
546+
_fsync_tree(destination, cancel_check=cancel_check)
529547
_verbose(
530548
f"fsync destination={destination} elapsed={time.perf_counter() - started:.3f}s",
531549
enabled=verbose,
@@ -544,12 +562,14 @@ def on_written(amount: int) -> None:
544562
return 0
545563

546564

547-
def _fsync_tree(root: Path) -> None:
565+
def _fsync_tree(root: Path, *, cancel_check: Callable[[], None] | None = None) -> None:
548566
directories: list[Path] = []
549567
for current, _dirnames, filenames in os.walk(root):
550568
current_path = Path(current)
551569
directories.append(current_path)
552570
for filename in filenames:
571+
if cancel_check is not None:
572+
cancel_check()
553573
# Windows' CRT _commit needs a writable handle to flush file data.
554574
# Do not skip fsync: failed flushes must abort recovery.
555575
flags = os.O_RDWR if os.name == "nt" else os.O_RDONLY
@@ -559,6 +579,8 @@ def _fsync_tree(root: Path) -> None:
559579
finally:
560580
os.close(fd)
561581
for directory in reversed(directories):
582+
if cancel_check is not None:
583+
cancel_check()
562584
_fsync_directory(directory)
563585
_fsync_directory(root.parent)
564586

‎src/endstone_endkeep/repository/logicalize.py‎

Lines changed: 17 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515

1616
from .manifest import ManifestStore, RepositoryManifest, SnapshotNode, snapshot_order_key
1717
from .objects import ObjectMetadata, ObjectStore
18+
from .progress import JobCancelled
1819
from .reader import RepositoryReader
1920
from .transaction import RepositoryTransaction
2021

@@ -89,10 +90,11 @@ def logicalize(
8990
raise ValueError(f"raw snapshot {raw.snapshot_id} is not newer than repository tail {tail.snapshot}")
9091

9192
self._report(progress, "clone", None, None, None, raw.snapshot_id)
92-
clone_world(raw.path, raw.manifest.world_name, self.work_root, raw.snapshot_id)
93+
clone_world(raw.path, raw.manifest.world_name, self.work_root, raw.snapshot_id, cancel_check=cancel_check)
9394
self._checkpoint(cancel_check)
9495

9596
db_path = self.work_root / raw.snapshot_id / raw.manifest.world_name / "db"
97+
cancelled = False
9698
try:
9799
if current_manifest is None:
98100
node, diff_counts = self._create_base(
@@ -124,8 +126,14 @@ def logicalize(
124126
new_manifest = RepositoryManifest(generation=generation, chain=tuple(new_chain))
125127
self._report(progress, "commit", None, None, None, raw.snapshot_id)
126128
RepositoryTransaction(self.manifests).commit(new_manifest)
129+
self._report(progress, "committed", None, None, None, raw.snapshot_id)
130+
self._checkpoint(cancel_check)
131+
except JobCancelled:
132+
cancelled = True
133+
raise
127134
finally:
128-
remove_processing_clone(self.work_root, raw.snapshot_id)
135+
if not cancelled:
136+
remove_processing_clone(self.work_root, raw.snapshot_id)
129137

130138
raw_deleted = True
131139
try:
@@ -171,7 +179,8 @@ def advance(amount: int) -> None:
171179
stream,
172180
current,
173181
progress=advance if progress is not None or cancel_check is not None else None,
174-
)
182+
),
183+
cancel_check=cancel_check,
175184
)
176185
assert isinstance(stats, BaseStats)
177186
self._checkpoint(cancel_check)
@@ -205,7 +214,7 @@ def _create_delta(
205214
cancel_check: CancelCheck | None,
206215
) -> tuple[SnapshotNode, tuple[int, int, int, int]]:
207216
stats = DiffStats()
208-
previous = self.reader.iter_state(current_manifest)
217+
previous = self.reader.iter_state(current_manifest, cancel_check=cancel_check)
209218
previous_total = current_manifest.chain[-1].records
210219

211220
def advance(_amount: int) -> None:
@@ -238,7 +247,8 @@ def advance(_amount: int) -> None:
238247
stats,
239248
progress=advance if progress is not None or cancel_check is not None else None,
240249
),
241-
)
250+
),
251+
cancel_check=cancel_check,
242252
)
243253
assert isinstance(delta_stats, DeltaStats)
244254
if delta_stats.records != stats.delta_records:
@@ -275,7 +285,8 @@ def _create_sidecar(
275285
self._report(progress, "sidecar", None, None, None, raw.snapshot_id)
276286
self._checkpoint(cancel_check)
277287
metadata, stats = self.objects.create(
278-
lambda stream: write_sidecar(stream, raw.path, raw.manifest.sidecar_entries)
288+
lambda stream: write_sidecar(stream, raw.path, raw.manifest.sidecar_entries, cancel_check=cancel_check),
289+
cancel_check=cancel_check,
279290
)
280291
self._checkpoint(cancel_check)
281292
return metadata, stats

0 commit comments

Comments
 (0)