fix(second-wind): prevent stale native healing replay
CI / build (push) Successful in 56s
CI / build (pull_request) Successful in 49s

This commit is contained in:
dmg committed 2026-10-08 08:52:54 -04:00
1 parent c0b5393646
commit f2f0dd742f
6 files changed
+635 -32

No files matched your search

@@ -91,6 +91,7 @@ public final class SecondWind implements AbilityEffect {
if (!Double.isFinite(proposed) || proposed <= 0) {
execution.resolve("cancelled", Map.of("reason", "healing_nonpositive")); execution.finish(); return;
}
var record = execution.character(); var expected = record.revision();
var event = new EntityRegainHealthEvent(player, proposed, EntityRegainHealthEvent.RegainReason.CUSTOM);
healingEvents.accept(event);
double accepted = Math.min(missing, event.getAmount());
@@ -98,44 +99,126 @@ public final class SecondWind implements AbilityEffect {
execution.resolve("cancelled", Map.of("reason", "native_healing_cancelled_or_nonpositive"));
execution.finish(); return;
}
var record = execution.character(); var expected = record.revision();
BigDecimal target = BigDecimal.valueOf(current + accepted);
if (!execution.stillCurrent() || !execution.character().revision().equals(expected)
|| !nativeUnchanged(player, current, maximum)) {
execution.resolve("interrupted", Map.of("reason", "state_changed_during_healing_event"));
execution.finish(); return;
}
BigDecimal limit = nativeLimit.get();
characters.saveHealth(record.id(), expected, target, limit).whenComplete((saved, failure) -> {
// The pinned native pool stores floats. Round down, so publication and the durable
// target agree without increasing the event's accepted healing budget by a float ULP.
float nativeTarget = (float) Math.min(maximum, current + accepted);
if (!Float.isFinite(nativeTarget)) nativeTarget = Float.MAX_VALUE;
if (nativeTarget > current + accepted || (double) nativeTarget - current > accepted)
nativeTarget = Math.nextDown(nativeTarget);
if (nativeTarget <= current) {
execution.resolve("cancelled", Map.of("reason", "no_positive_representable_heal"));
execution.finish(); return;
}
BigDecimal target = BigDecimal.valueOf((double) nativeTarget);
var callback = new java.util.concurrent.atomic.AtomicBoolean();
characters.prepareSecondWindHealth(record.id(), expected, target, limit).whenComplete((saved, failure) -> {
try {
nextTick.accept(() -> {
if (!callback.compareAndSet(false, true)) return;
try {
if (failure != null || saved == null || saved.isEmpty() || !execution.stillCurrent()) {
execution.resolve(failure != null || saved == null || saved.isEmpty() ? "failed" : "interrupted",
Map.of("reason", failure != null ? "health_save_failed" : saved == null || saved.isEmpty()
? "health_save_unconfirmed" : "session_changed_before_healing"));
player.sendMessage("Second Wind health could not be saved; no healing was applied."); return;
if (failure != null || saved == null || saved.isEmpty()) {
execution.resolve("failed", Map.of("reason", failure != null ? "health_save_failed" : "health_save_unconfirmed"));
if (execution.stillCurrent()) player.sendMessage("Second Wind health could not be saved; no healing was applied.");
return;
}
var persisted = saved.orElseThrow();
if (!sessions.acknowledgeProgress(execution.input().session(), expected, persisted)) {
execution.resolve("interrupted", Map.of("reason", "health_saved_session_changed"));
player.sendMessage("Second Wind was saved, but the session changed; no native healing was applied."); return;
var pending = saved.orElseThrow(); var persisted = pending.saved();
if (!execution.stillCurrent() || !acknowledge(execution.input().session(), expected, persisted)) {
execution.resolve("interrupted", Map.of("reason", "health_saved_session_changed_pending_reconciliation"));
return; // No current native authority: retain durable proof, never replay the target.
}
if (!execution.stillCurrent() || !nativeUnchanged(player, current, maximum)) {
reconcile(execution, pending, "interrupted", "native_state_changed_before_healing"); return;
}
double publish = Math.min(maximum, persisted.health().doubleValue());
if (!Double.isFinite(publish) || publish <= current || publish - current > accepted) {
reconcile(execution, pending, "cancelled", "no_bounded_native_heal_available"); return;
}
double nativeBefore = player.getHealth();
double publish = Math.min(attribute.getValue(), Math.max(nativeBefore, persisted.health().doubleValue()));
try { player.setHealth(publish); }
catch (RuntimeException nativeFailure) {
execution.resolve("failed", Map.of("reason", "native_health_publication_failed"));
throw nativeFailure;
reconcile(execution, pending, "failed", "native_health_publication_failed"); return;
}
double nativeAfter = player.getHealth();
double restored = nativeAfter - nativeBefore;
if (Double.isFinite(restored) && restored > 0) {
try { execution.acceptedHeal(execution.input().session(), player, persisted, proposed,
restored, nativeBefore, nativeAfter, maximum); }
catch (RuntimeException ignored) { /* Auditing cannot change an applied native heal. */ }
execution.resolve("healed", Map.of("reason", "native_self_heal_applied"));
execution.report(AbilityReport.Type.HEALING, player,
BigDecimal.valueOf(restored).stripTrailingZeros());
} else execution.resolve("cancelled", Map.of("reason", "native_heal_not_observed"));
double restored = nativeAfter - current;
if (!execution.stillCurrent() || Double.compare(nativeAfter, publish) != 0) {
reconcile(execution, pending, "interrupted", "native_publication_unconfirmed"); return;
}
try { execution.acceptedHeal(execution.input().session(), player, persisted, proposed,
restored, current, nativeAfter, maximum); }
catch (RuntimeException ignored) { /* Auditing cannot change an applied native heal. */ }
execution.resolve("healed", Map.of("reason", "native_self_heal_applied"));
retire(pending, persisted, execution.input().session());
execution.report(AbilityReport.Type.HEALING, player, BigDecimal.valueOf(restored).stripTrailingZeros());
} finally { execution.finish(); }
});
} catch (RuntimeException rejected) { execution.finish(); }
} catch (RuntimeException rejected) {
execution.resolve("failed", Map.of("reason", "scheduler_rejected_pending_reconciliation"));
execution.finish(); // The durable load barrier remains in place.
}
});
}
private static boolean nativeUnchanged(org.bukkit.entity.Player player, double health, double maximum) {
var attribute = player.getAttribute(Attribute.MAX_HEALTH);
return attribute != null && Double.compare(player.getHealth(), health) == 0
&& Double.compare(attribute.getValue(), maximum) == 0;
}
private boolean acknowledge(EquipmentSessions.Active active, BigInteger expected,
games.dmg.fantasystick.persistence.CharacterRecord saved) {
// A pre-existing identical saved target does not advance a revision. It still needs native validation.
return sessions.currentRecord(active).filter(saved::equals).isPresent()
|| sessions.acknowledgeProgress(active, expected, saved);
}
private void reconcile(AbilityExecution execution, CharacterStorage.PendingHealth pending,
String outcome, String reason) {
execution.resolve(outcome, Map.of("reason", reason));
if (!execution.stillCurrent()) return;
var active = execution.input().session(); var player = execution.input().player();
var attribute = player.getAttribute(Attribute.MAX_HEALTH);
double observed = player.getHealth();
if (attribute == null || !Double.isFinite(observed) || observed < 0
|| !Double.isFinite(attribute.getValue()) || attribute.getValue() <= 0) return;
double maximum = attribute.getValue();
BigDecimal limit = nativeLimit.get().min(BigDecimal.valueOf(maximum));
player.sendMessage("Second Wind was interrupted; no healing was confirmed. Saved health is being reconciled.");
var callback = new java.util.concurrent.atomic.AtomicBoolean();
characters.reconcileSecondWindHealth(pending, BigDecimal.valueOf(observed), limit).whenComplete((saved, failure) -> {
try {
nextTick.accept(() -> {
if (!callback.compareAndSet(false, true)) return;
if (failure != null || saved == null || saved.isEmpty()) {
reconciliationNotice(active); return;
}
var settled = saved.orElseThrow();
if (!sessions.current(active) || !nativeUnchanged(player, observed, maximum)
|| !acknowledge(active, pending.saved().revision(), settled)) {
reconciliationNotice(active); return;
}
retire(pending, settled, active);
});
} catch (RuntimeException rejected) { /* Retain the load barrier; no native replay. */ }
});
}
private void retire(CharacterStorage.PendingHealth pending,
games.dmg.fantasystick.persistence.CharacterRecord settled, EquipmentSessions.Active active) {
characters.completeSecondWindHealth(pending, settled).whenComplete((completed, failure) -> {
if (failure != null || !Boolean.TRUE.equals(completed)) {
try { nextTick.accept(() -> reconciliationNotice(active)); }
catch (RuntimeException rejected) { /* Unresolved proof still blocks later entry. */ }
}
});
}
private void reconciliationNotice(EquipmentSessions.Active active) {
sessions.currentPlayer(active).ifPresent(player -> player.sendMessage(
"Second Wind health reconciliation is unconfirmed; later character entry remains blocked pending recovery."));
}
}
@@ -27,6 +27,7 @@ public final class CharacterStorage implements AutoCloseable {
private final java.util.function.Supplier<games.dmg.fantasystick.progression.CoinRules> coinRules;
private final java.util.random.RandomGenerator coinRandom;
private final CharacterRecoveryStore recoveries;
private final SecondWindHealthStore secondWindHealth;
private games.dmg.fantasystick.events.CharacterRecoveryEventBridge recoveryEvents;
public void attachRecoveryEvents(games.dmg.fantasystick.events.CharacterRecoveryEventBridge bridge) {
@@ -86,6 +87,7 @@ public final class CharacterStorage implements AutoCloseable {
this.coinRules = Objects.requireNonNull(coinRules);
this.coinRandom = Objects.requireNonNull(coinRandom);
this.recoveries = new CharacterRecoveryStore(repository.pluginDataDirectory());
this.secondWindHealth = new SecondWindHealthStore(repository.pluginDataDirectory());
repository.attachMutationUnavailable(recoveries::blocks);
}
@@ -481,6 +483,7 @@ public final class CharacterStorage implements AutoCloseable {
/** Persist a legacy character's one-time configured migration roll before exposing it. */
private Optional<CharacterRecord> load(UUID id) throws IOException {
if (secondWindHealth.blocks(id)) throw new IOException("Second Wind native publication is unresolved; character entry refused");
var found = repository.load(id);
if (found.isEmpty()) {
if (recoveries.find(id).filter(operation -> operation.phase() != CharacterRecoveryStore.Phase.DELIVERED).isPresent())
@@ -944,6 +947,77 @@ public final class CharacterStorage implements AutoCloseable {
});
}
/** Opaque, one-operation authority; only its worker may advance or retire the load barrier. */
public static final class PendingHealth {
private final UUID operation;
private final CharacterRecord saved;
private CharacterRecord latest;
private boolean completed;
private PendingHealth(UUID operation, CharacterRecord saved) {
this.operation = operation; this.saved = saved; this.latest = saved;
}
public CharacterRecord saved() { return saved; }
}
/** Proof is durable before the provisional health target can become visible on disk. */
public CompletableFuture<Optional<PendingHealth>> prepareSecondWindHealth(UUID characterId,
BigInteger expectedRevision, java.math.BigDecimal health, java.math.BigDecimal nativeLimit) {
Objects.requireNonNull(characterId); Objects.requireNonNull(expectedRevision);
if (health.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
return submit(() -> repository.transaction(() -> {
if (secondWindHealth.blocks(characterId) || !repository.mutationAvailable(characterId)) return Optional.empty();
var found = repository.load(characterId);
if (found.isEmpty() || found.orElseThrow().dead()
|| !found.orElseThrow().revision().equals(expectedRevision)) return Optional.empty();
var old = found.orElseThrow();
var saved = withHealth(old, health.min(old.maximumHealth()).min(nativeLimit));
var operation = UUID.randomUUID();
secondWindHealth.prepare(characterId, operation);
if (saved != old) repository.replaceLocked(saved, expectedRevision, true);
return Optional.of(new PendingHealth(operation, saved));
}));
}
/** Refused native publication reconciles only this operation's exact unchanged revision. */
public CompletableFuture<Optional<CharacterRecord>> reconcileSecondWindHealth(PendingHealth pending,
java.math.BigDecimal observedHealth, java.math.BigDecimal nativeLimit) {
Objects.requireNonNull(pending);
if (observedHealth.signum() < 0 || nativeLimit.signum() <= 0) throw new IllegalArgumentException("Invalid health bound");
return submit(() -> repository.transaction(() -> {
if (pending.completed) return Optional.empty();
var id = pending.saved.id();
secondWindHealth.verify(id, pending.operation);
var found = repository.load(id);
if (found.isEmpty() || !found.orElseThrow().equals(pending.latest)) return Optional.empty();
var old = found.orElseThrow();
var saved = withHealth(old, observedHealth.min(old.maximumHealth()).min(nativeLimit));
if (saved != old) repository.replaceLocked(saved, old.revision(), true);
pending.latest = saved;
return Optional.of(saved);
}));
}
/** No newer record or other operation's proof may be cleared by this acknowledgment. */
public CompletableFuture<Boolean> completeSecondWindHealth(PendingHealth pending, CharacterRecord settled) {
Objects.requireNonNull(pending); Objects.requireNonNull(settled);
return submit(() -> repository.transaction(() -> {
if (pending.completed || !pending.latest.equals(settled)) return false;
secondWindHealth.verify(pending.saved.id(), pending.operation);
if (repository.load(pending.saved.id()).filter(settled::equals).isEmpty()) return false;
secondWindHealth.complete(pending.saved.id(), pending.operation);
pending.completed = true;
return true;
}));
}
private static CharacterRecord withHealth(CharacterRecord old, java.math.BigDecimal bounded) {
if (old.health().compareTo(bounded) == 0) return old;
return new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
old.experience(), old.unspentPoints(), bounded, old.learned(), old.loadout(), old.passives(), old.cooldowns(),
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),
old.pvpCoinEscrow(), old.gear(), old.sheetGeneration());
}
/** Session-owned remaining health; retain all other current fields and reject concurrent revision changes. */
public CompletableFuture<Optional<CharacterRecord>> saveHealth(UUID characterId, java.math.BigDecimal health,
java.math.BigDecimal nativeLimit) {
@@ -961,10 +1035,8 @@ public final class CharacterStorage implements AutoCloseable {
var old = found.orElseThrow();
if (expectedRevision != null && !old.revision().equals(expectedRevision)) return Optional.empty();
var bounded = health.min(old.maximumHealth()).min(nativeLimit);
if (old.health().compareTo(bounded) == 0) return Optional.of(old);
var saved = new CharacterRecord(old.id(), old.name(), old.revision().add(BigInteger.ONE), old.stats(), old.level(),
old.experience(), old.unspentPoints(), bounded, old.learned(), old.loadout(), old.passives(), old.cooldowns(),
old.restrictedKills(), false, old.deathId(), old.diedAt(), old.coins(), old.coinsInitialized(), old.rewardReceipts(),old.pvpCoinEscrow(),old.gear(),old.sheetGeneration());
var saved = withHealth(old, bounded);
if (saved == old) return Optional.of(old);
repository.replace(saved, old.revision());
return Optional.of(saved);
});
@@ -0,0 +1,71 @@
package games.dmg.fantasystick.persistence;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
/** Unresolved native-publication proof is a load barrier, never permission to replay a heal. */
final class SecondWindHealthStore {
private final Path directory;
SecondWindHealthStore(Path pluginDataDirectory) {
directory = pluginDataDirectory.resolve("second-wind-health").toAbsolutePath();
}
boolean blocks(UUID character) throws IOException {
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) return false;
safeDirectory();
// Unknown, malformed, unreadable and symlink proof all remain unresolved.
return !Files.notExists(file(character), LinkOption.NOFOLLOW_LINKS);
}
/** Caller holds the character repository lock through proof and character replacement. */
void prepare(UUID character, UUID operation) throws IOException {
if (Files.notExists(directory, LinkOption.NOFOLLOW_LINKS)) {
Files.createDirectory(directory);
DurableFiles.forceDirectory(directory.getParent());
}
safeDirectory();
byte[] bytes = operation.toString().getBytes(StandardCharsets.UTF_8);
try (var channel = FileChannel.open(file(character), StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE, LinkOption.NOFOLLOW_LINKS)) {
var buffer = ByteBuffer.wrap(bytes);
while (buffer.hasRemaining()) channel.write(buffer);
channel.force(true);
}
DurableFiles.forceDirectory(directory);
}
void verify(UUID character, UUID operation) throws IOException {
safeDirectory();
var path = file(character);
if (!Files.isRegularFile(path, LinkOption.NOFOLLOW_LINKS) || Files.size(path) != 36)
throw new IOException("Second Wind publication proof is unsafe or missing");
try (var channel = FileChannel.open(path, StandardOpenOption.READ, LinkOption.NOFOLLOW_LINKS)) {
var bytes = ByteBuffer.allocate(37);
while (bytes.hasRemaining() && channel.read(bytes) > 0) { /* Bound proof reads. */ }
bytes.flip();
if (!StandardCharsets.UTF_8.decode(bytes).toString().equals(operation.toString()))
throw new IOException("Second Wind publication proof does not match its operation");
}
}
void complete(UUID character, UUID operation) throws IOException {
verify(character, operation);
Files.delete(file(character));
DurableFiles.forceDirectory(directory);
}
private Path file(UUID character) { return directory.resolve(character + ".pending"); }
private void safeDirectory() throws IOException {
if (!Files.isDirectory(directory, LinkOption.NOFOLLOW_LINKS))
throw new IOException("Second Wind publication directory is unsafe");
}
}