From 677dbedeea9ddb5264c4d792600a16b9a96ad0e9 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Mon, 23 Nov 2026 03:33:31 +0200 Subject: [PATCH 01/13] Release `v1.1.4`. --- CHANGELOG.md | 4 ++++ README.md | 4 ++-- pom.xml | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 11a1a74e..60c8ffda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ ## Release Notes +`1.1.4` + +--- + `1.1.3` - Added `ExtendedField.valueNotNull()` to check whether the field value is not `null`, usable as a predicate for `ExtendedFields.findAllNonStatic`. diff --git a/README.md b/README.md index 3de9bb15..9e76dc69 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ A library that exposes general Java utility and reflection methods and a package ### Releases -Current release `1.1.3` +Current release `1.1.4` ### Documentation @@ -88,6 +88,6 @@ Maven: add this dependency to your `pom.xml` io.github.raduking morphix-all - 1.1.3 + 1.1.4 ``` diff --git a/pom.xml b/pom.xml index 4c2cdaff..a1534c10 100644 --- a/pom.xml +++ b/pom.xml @@ -19,7 +19,7 @@ io.github.raduking morphix-all - 1.1.3 + 1.1.4 jar ${project.groupId}:${project.artifactId} From bdc42f91d3b5f98268244b5a3c4d2bc917783f84 Mon Sep 17 00:00:00 2001 From: raduking Date: Mon, 23 Nov 2026 03:53:38 +0200 Subject: [PATCH 02/13] More test coverage. --- .../reflection/FieldsSafeGetByPathsTest.java | 14 ++++++++++++++ .../org/morphix/reflection/FieldsSafeGetTest.java | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java index 046db0e9..baa3f30e 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetByPathsTest.java @@ -140,6 +140,20 @@ void shouldSkipNullPathInVarargs() { assertThat(result, equalTo("Alice")); } + @Test + void shouldReturnNullWhenObjectIsNullOnCommaSeparatedPaths() { + var result = Fields.Safe.getByPaths(null, "person.name"); + + assertThat(result, nullValue()); + } + + @Test + void shouldReturnNullWhenObjectIsNullOnVarargs() { + var result = Fields.Safe.getByPaths(null, "unknown", "person.name"); + + assertThat(result, nullValue()); + } + @Test void shouldReturnNullWhenPathsArrayIsNull() { var result = Fields.Safe.getByPaths(data, (String[]) null); diff --git a/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java b/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java index 3013ea8c..308d7aa0 100644 --- a/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java +++ b/src/test/java/org/morphix/reflection/FieldsSafeGetTest.java @@ -207,6 +207,13 @@ void shouldReturnNullIfObjectFieldNameIsNull() { assertThat(result, equalTo(null)); } + @Test + void shouldReturnNullIfObjectIsNullOnCallWithFieldName() { + Object result = Fields.Safe.get(null, "s"); + + assertThat(result, equalTo(null)); + } + @Test void shouldReturnClassClassloaderField() { Class clazz = Class.class; From 460d8d1bc0348986e7a90f737b2baa62b3979036 Mon Sep 17 00:00:00 2001 From: raduking Date: Wed, 25 Nov 2026 02:55:00 +0200 Subject: [PATCH 03/13] Added `Threads.safeJoin`. --- CHANGELOG.md | 2 + .../java/org/morphix/lang/thread/Threads.java | 23 +++++++++ .../org/morphix/lang/thread/ThreadsTest.java | 49 +++++++++++++++++++ 3 files changed, 74 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 60c8ffda..12b9ec93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ `1.1.4` +- Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling. + --- `1.1.3` diff --git a/src/main/java/org/morphix/lang/thread/Threads.java b/src/main/java/org/morphix/lang/thread/Threads.java index 4470100c..6ba45fb4 100644 --- a/src/main/java/org/morphix/lang/thread/Threads.java +++ b/src/main/java/org/morphix/lang/thread/Threads.java @@ -248,6 +248,29 @@ public static boolean safeJoin(final Thread thread) { } } + /** + * Helper method that calls {@link Thread#join(long)} on the given thread with the given timeout, with + * {@link InterruptedException} handling. + *

+ * Returns when either the thread terminates or the timeout elapses, whichever comes first. The returned value does not + * indicate whether the thread has terminated; check {@link Thread#isAlive()} for that. If the calling thread is + * interrupted while waiting, the interrupt status is restored via {@link #handleInterruptedException()}. + * + * @param thread thread object + * @param timeout the maximum time to wait for the thread to terminate + * @return true if the join returned normally (the thread terminated or the timeout elapsed), false if the calling + * thread was interrupted while waiting + */ + public static boolean safeJoin(final Thread thread, final Duration timeout) { + try { + thread.join(timeout.toMillis()); + return true; + } catch (InterruptedException e) { + handleInterruptedException(); + return false; + } + } + /** * Runs each runnable in the list with the given execution type. It only returns after all threads have completed.
* By default, when using: {@code Threads.execute(runnables, ExecutionType.EXECUTOR)} the single thread executor will be diff --git a/src/test/java/org/morphix/lang/thread/ThreadsTest.java b/src/test/java/org/morphix/lang/thread/ThreadsTest.java index 3330d8c2..059d83b1 100644 --- a/src/test/java/org/morphix/lang/thread/ThreadsTest.java +++ b/src/test/java/org/morphix/lang/thread/ThreadsTest.java @@ -405,6 +405,55 @@ void shouldSafelyWaitForCountdownLatchWithDurationAndHandleInterruptedExceptionO assertFalse(countReached.get()); assertFalse(result); } + + @Test + void shouldSafelyJoinWithTimeoutWhenThreadTerminatesBeforeTimeout() { + AtomicBoolean ran = new AtomicBoolean(false); + Thread thread = Thread.ofPlatform().start(() -> ran.set(true)); + + boolean result = Threads.safeJoin(thread, Duration.ofSeconds(10)); + + assertTrue(result); + assertTrue(ran.get()); + assertFalse(thread.isAlive()); + } + + @Test + void shouldSafelyJoinWithTimeoutAndReturnTrueWhenTimeoutElapsesAndThreadIsStillAlive() { + CountDownLatch latch = new CountDownLatch(1); + Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch)); + + try { + boolean result = Threads.safeJoin(thread, Duration.ofMillis(10)); + + assertTrue(result); + assertTrue(thread.isAlive()); + } finally { + latch.countDown(); + Threads.safeJoin(thread); + } + } + + @Test + void shouldSafelyJoinWithTimeoutAndHandleInterruptedException() { + CountDownLatch latch = new CountDownLatch(1); + Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch)); + + try { + // interrupt the joining thread not the thread being joined + Thread.currentThread().interrupt(); + boolean result = Threads.safeJoin(thread, Duration.ofSeconds(10)); + + assertFalse(result); + assertTrue(Thread.currentThread().isInterrupted()); + assertTrue(thread.isAlive()); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + latch.countDown(); + Threads.safeJoin(thread); + } + } } @Nested From 96faa144616886c83af31a36ec3900744c1adf54 Mon Sep 17 00:00:00 2001 From: raduking Date: Wed, 25 Nov 2026 03:19:29 +0200 Subject: [PATCH 04/13] More mutation coverage. --- .../lang/thread/ReschedulingTaskTest.java | 273 ++++++++++++++++++ .../lang/thread/StackedContextHolderTest.java | 47 +++ .../morphix/lang/thread/SynchronizedTest.java | 53 ++++ .../org/morphix/lang/thread/ThreadsTest.java | 216 ++++++++++++++ 4 files changed, 589 insertions(+) diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index 1049a724..e00585a4 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -47,6 +47,7 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; @@ -1334,5 +1335,277 @@ void shouldEnableAndDisableTaskAndLogExecution() throws InterruptedException { verify(logger, atLeast(executionCount - 1)).debug("[{}] Scheduling next execution in {}ms.", TASK_NAME, DELAY.toMillis()); verify(logger).debug("[{}] Disabling rescheduling task.", TASK_NAME); } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenCancellingScheduledTask() { + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + doReturn(true).when(scheduledFuture).cancel(anyBoolean()); + LoggerAdapter logger = mock(LoggerAdapter.class); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> Duration.ofSeconds(5)) + .logger(logger) + .build(); + + task.enable(); + task.disable(); + + verify(logger).debug(eq("[{}] Called cancel scheduled task: {}."), eq(TASK_NAME), any()); + verify(logger).debug(eq("[{}] Attempting to cancel scheduled task: {}."), eq(TASK_NAME), any()); + verify(scheduledFuture).cancel(anyBoolean()); + } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenSkippingExecutionBecauseTaskIsDisabled() { + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + + Method executeMethod = Methods.getOneDeclared("execute", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(executeMethod, task); + + verify(logger).debug("[{}] Scheduler is disabled, skipping execution.", TASK_NAME); + } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenSkippingSchedulingBecauseTaskIsDisabled() { + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + + Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + + verify(logger).debug("[{}] Scheduler is disabled, skipping scheduling next execution.", TASK_NAME); + assertThat(task.isScheduled(), is(false)); + } + + @Test + @SuppressWarnings("resource") + void shouldLogErrorWhenTaskExecutionFails() { + IllegalStateException exception = new IllegalStateException("test failure"); + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(() -> { + throw exception; + }) + .nextDelay(() -> Duration.ofHours(1)) + .logger(logger) + .build(); + + task.enable(); + task.disable(); + + verify(logger).error("[{}] Error during task execution.", TASK_NAME, exception); + } + + @Test + @SuppressWarnings("resource") + void shouldCancelAndLogWhenTaskIsDisabledWhileSchedulingNext() { + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + doReturn(true).when(scheduledFuture).cancel(anyBoolean()); + LoggerAdapter logger = mock(LoggerAdapter.class); + AtomicReference taskReference = new AtomicReference<>(); + // disable the task right after the check at the beginning of scheduleNext + doAnswer(invocation -> { + taskReference.get().disable(); + return scheduledFuture; + }).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> Duration.ofSeconds(5)) + .logger(logger) + .build(); + taskReference.set(task); + + task.enable(); + + verify(logger).debug("[{}] Task was disabled during scheduling. Cancelling immediate orphan.", TASK_NAME); + verify(scheduledFuture).cancel(anyBoolean()); + assertThat(task.isScheduled(), is(false)); + } + } + + @Nested + class ExecutionWrapperInvocationTests { + + @Test + @SuppressWarnings("resource") + void shouldRunTaskThroughExecutionWrapper() { + AtomicInteger wrapperCounter = new AtomicInteger(); + AtomicInteger executionCounter = new AtomicInteger(); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(executionCounter::incrementAndGet) + .wrap(wrapped -> () -> { + wrapperCounter.incrementAndGet(); + return wrapped.get(); + }) + .nextDelay(() -> Duration.ofHours(1)) + .build(); + + task.enable(); + task.disable(); + + assertThat(wrapperCounter.get(), is(1)); + assertThat(executionCounter.get(), is(1)); + } + } + + @Nested + class CancellationOutcomeTests { + + private final ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + private final ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + + private ReschedulingTask managedTask(final LoggerAdapter logger) { + doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + return ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.managed(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> Duration.ofSeconds(5)) + .logger(logger) + .build(); + } + + @Test + @SuppressWarnings("resource") + void shouldCloseSchedulerGracefullyWhenCancellationSucceeds() throws Exception { + doReturn(true).when(scheduledFuture).cancel(anyBoolean()); + ReschedulingTask task = managedTask(LoggerAdapter.none()); + + task.enable(); + task.close(); + + verify(scheduledFuture).cancel(anyBoolean()); + verify(scheduledExecutor).close(); + verify(scheduledExecutor, never()).shutdownNow(); + } + + @Test + @SuppressWarnings("resource") + void shouldCloseSchedulerGracefullyWhenThereIsNoScheduledTask() throws Exception { + ReschedulingTask task = managedTask(LoggerAdapter.none()); + + task.close(); + + verify(scheduledExecutor).close(); + verify(scheduledExecutor, never()).shutdownNow(); + } + + @Test + @SuppressWarnings("resource") + void shouldCloseSchedulerGracefullyWhenScheduledTaskIsAlreadyDone() throws Exception { + doReturn(true).when(scheduledFuture).isDone(); + ReschedulingTask task = managedTask(LoggerAdapter.none()); + + task.enable(); + task.close(); + + verify(scheduledFuture, never()).cancel(anyBoolean()); + verify(scheduledExecutor).close(); + verify(scheduledExecutor, never()).shutdownNow(); + } + + @Test + @SuppressWarnings("resource") + void shouldShutdownSchedulerNowAndLogRemainingTasksWhenCancellationFails() throws Exception { + doReturn(false).when(scheduledFuture).cancel(anyBoolean()); + doReturn(List.of(mock(Runnable.class))).when(scheduledExecutor).shutdownNow(); + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = managedTask(logger); + + task.enable(); + task.close(); + + verify(scheduledExecutor).shutdownNow(); + verify(scheduledExecutor, never()).close(); + verify(logger).warn("[{}] Scheduler closed with {} remaining tasks.", TASK_NAME, 1); + } + } + + @Nested + class DebugInfoTests { + + @Test + @SuppressWarnings("resource") + void shouldReturnNotAvailableWhenDebugIsDisabled() { + LoggerAdapter logger = mock(LoggerAdapter.class); + doReturn(true).when(logger).isDisabled(LoggerAdapter.LoggingLevel.DEBUG); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + + String info = task.debugInfo(mock(ScheduledFuture.class)); + + assertThat(info, equalTo("N/A")); + } + + @Test + @SuppressWarnings("resource") + void shouldReturnHashCodeAndStateWhenDebugIsEnabled() { + ScopedResource scheduler = scheduler(); + ScheduledFuture future = scheduler.unwrap().schedule(Runnables.doNothing(), 1, TimeUnit.HOURS); + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + + String info = task.debugInfo(future); + + assertThat(info, equalTo("hashCode:[" + future.hashCode() + "], state:[" + future.state() + "]")); + } + + @Test + @SuppressWarnings("resource") + void shouldReturnNullValuesWhenDebugIsEnabledAndTaskIsNull() { + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(scheduler()) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + + String info = task.debugInfo(null); + + assertThat(info, equalTo("hashCode:[null], state:[null]")); + } } } diff --git a/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java b/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java index 23c93451..99cb5434 100644 --- a/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java +++ b/src/test/java/org/morphix/lang/thread/StackedContextHolderTest.java @@ -209,6 +209,53 @@ void shouldNotChangeTenantIdWhenStackIsEmpty() { assertThat(TenantContextHolder.getTenantId(), equalTo(null)); } + @Test + void shouldSetFunctionAndRemoveElementAroundFunctionCall() { + List calls = new ArrayList<>(); + + String result = StackedContextHolder.on(TENANT_ID, + element -> calls.add("set:" + element), + element -> calls.add("remove:" + element), + (String arg) -> { + calls.add("run:" + arg); + return arg; + }, + TEST_STRING); + + assertThat(result, equalTo(TEST_STRING)); + assertThat(calls, equalTo(List.of("set:" + TENANT_ID, "run:" + TEST_STRING, "remove:" + TENANT_ID))); + } + + @Test + void shouldRemoveElementWhenFunctionThrows() { + List calls = new ArrayList<>(); + + assertThrows(IllegalStateException.class, () -> StackedContextHolder.on(TENANT_ID, + element -> calls.add("set:" + element), + element -> calls.add("remove:" + element), + (String arg) -> { + throw new IllegalStateException(); + }, + TEST_STRING)); + + assertThat(calls, equalTo(List.of("set:" + TENANT_ID, "remove:" + TENANT_ID))); + } + + @Test + void shouldClearThreadStackWhenRemovingElementFromEmptyStack() { + int removeCallsBefore = DummyTenantContextHolder.stack.removeCalls; + + try { + DummyTenantContextHolder.INSTANCE.clearElement(); + + assertThat(DummyTenantContextHolder.stack.removeCalls, equalTo(removeCallsBefore + 1)); + assertThat(DummyTenantContextHolder.getTenantId(), equalTo(null)); + } finally { + // restore the shared counter so other tests asserting on it are not affected by execution order + DummyTenantContextHolder.stack.removeCalls = removeCallsBefore; + } + } + @Test void shouldClearManuallySetTenantId() { DummyTenantContextHolder.INSTANCE.setElement(TENANT_ID); diff --git a/src/test/java/org/morphix/lang/thread/SynchronizedTest.java b/src/test/java/org/morphix/lang/thread/SynchronizedTest.java index 32e7ef65..8236940f 100644 --- a/src/test/java/org/morphix/lang/thread/SynchronizedTest.java +++ b/src/test/java/org/morphix/lang/thread/SynchronizedTest.java @@ -115,6 +115,59 @@ void shouldTryRunnableWithTimeout() throws InterruptedException { }); } + @Test + void shouldReleaseLockAfterTrySupplier() { + ReentrantLock lock = new ReentrantLock(); + + assertThat(Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> VALUE, () -> DEFAULT), equalTo(VALUE)); + + assertFalse(lock.isLocked()); + } + + @Test + void shouldReleaseLockAfterTrySupplierThrows() { + ReentrantLock lock = new ReentrantLock(); + + assertThrows(IllegalStateException.class, () -> Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> { + throw new IllegalStateException(); + })); + + assertFalse(lock.isLocked()); + } + + @Test + void shouldReleaseLockAfterTryRunnable() { + ReentrantLock lock = new ReentrantLock(); + + Synchronized.tryWith(lock, 1, TimeUnit.SECONDS, () -> { + // nothing to do + }); + + assertFalse(lock.isLocked()); + } + + @Test + void shouldRunRunnableWithDurationTimeout() { + ReentrantLock lock = new ReentrantLock(); + AtomicBoolean ran = new AtomicBoolean(); + + Synchronized.tryWith(lock, Duration.ofSeconds(1), () -> ran.set(true)); + + assertTrue(ran.get()); + assertFalse(lock.isLocked()); + } + + @Test + void shouldRunRunnableWithDefaultTimeout() { + ReentrantLock lock = new ReentrantLock(); + AtomicBoolean ran = new AtomicBoolean(); + + Synchronized.tryWith(lock, () -> ran.set(true)); + + assertTrue(ran.get()); + assertFalse(lock.isLocked()); + } + @Test void shouldReturnDefaultWhenInterrupted() throws InterruptedException { ReentrantLock lock = new ReentrantLock(); diff --git a/src/test/java/org/morphix/lang/thread/ThreadsTest.java b/src/test/java/org/morphix/lang/thread/ThreadsTest.java index 059d83b1..89f004f4 100644 --- a/src/test/java/org/morphix/lang/thread/ThreadsTest.java +++ b/src/test/java/org/morphix/lang/thread/ThreadsTest.java @@ -21,10 +21,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -34,6 +40,8 @@ import java.util.List; import java.util.Queue; import java.util.Set; +import java.util.concurrent.Callable; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; @@ -249,6 +257,45 @@ void shouldNotThrowExeptionOnTimeoutWhenRunningSupplierWithTimeout() { void shouldNotThrowExeptionOnTimeoutWhenRunningRunnableWithTimeout() { assertDoesNotThrow(() -> Threads.execute(Duration.ofSeconds(10), Runnables.doNothing())); } + + @Test + @SuppressWarnings({ "unchecked", "resource" }) + void shouldCancelTaskWhenExecutionFails() throws Exception { + Future task = mock(Future.class); + doThrow(new TimeoutException()).when(task).get(anyLong(), any(TimeUnit.class)); + ExecutorService executor = mock(ExecutorService.class); + doReturn(task).when(executor).submit(any(Callable.class)); + + try (MockedStatic executors = Mockito.mockStatic(Executors.class)) { + executors.when(Executors::newVirtualThreadPerTaskExecutor).thenReturn(executor); + + assertThrows(TimeoutException.class, () -> Threads.execute(Duration.ofSeconds(10), () -> TEST_STRING)); + + verify(task).cancel(true); + verify(executor).shutdownNow(); + } + } + + @Test + @SuppressWarnings({ "unchecked", "resource" }) + void shouldRestoreInterruptedStatusWhenInterruptedWhileWaitingForTaskTermination() throws InterruptedException { + ExecutorService executor = mock(ExecutorService.class); + doReturn(CompletableFuture.completedFuture(TEST_STRING)).when(executor).submit(any(Callable.class)); + doThrow(new InterruptedException()).when(executor).awaitTermination(anyLong(), any(TimeUnit.class)); + + try (MockedStatic executors = Mockito.mockStatic(Executors.class)) { + executors.when(Executors::newVirtualThreadPerTaskExecutor).thenReturn(executor); + + String result = Threads.execute(Duration.ofSeconds(10), () -> TEST_STRING); + + assertThat(result, equalTo(TEST_STRING)); + verify(executor).shutdownNow(); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + } + } } @Nested @@ -406,6 +453,68 @@ void shouldSafelyWaitForCountdownLatchWithDurationAndHandleInterruptedExceptionO assertFalse(result); } + @Test + void shouldRestoreInterruptedStatusWhenSafeWaitIsInterrupted() { + CountDownLatch latch = new CountDownLatch(1); + + try { + Thread.currentThread().interrupt(); + Threads.safeWait(latch); + + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + } + } + + @Test + void shouldReturnFalseWhenSafeWaitWithDurationTimesOut() { + CountDownLatch latch = new CountDownLatch(1); + + boolean result = Threads.safeWait(latch, Duration.ofMillis(10)); + + assertFalse(result); + assertFalse(Thread.currentThread().isInterrupted()); + } + + @Test + void shouldRestoreInterruptedStatusWhenSafeWaitWithDurationIsInterrupted() { + CountDownLatch latch = new CountDownLatch(1); + + try { + Thread.currentThread().interrupt(); + boolean result = Threads.safeWait(latch, Duration.ofSeconds(10)); + + assertFalse(result); + assertTrue(Thread.currentThread().isInterrupted()); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + } + } + + @Test + void shouldRestoreInterruptedStatusWhenSafeJoinIsInterrupted() { + CountDownLatch latch = new CountDownLatch(1); + Thread thread = Thread.ofPlatform().start(() -> Threads.safeWait(latch)); + + try { + // interrupt the joining thread not the thread being joined + Thread.currentThread().interrupt(); + boolean result = Threads.safeJoin(thread); + + assertFalse(result); + assertTrue(Thread.currentThread().isInterrupted()); + assertTrue(thread.isAlive()); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + latch.countDown(); + Threads.safeJoin(thread); + } + } + @Test void shouldSafelyJoinWithTimeoutWhenThreadTerminatesBeforeTimeout() { AtomicBoolean ran = new AtomicBoolean(false); @@ -621,6 +730,66 @@ void shouldNotWaitForTimeoutIfInterrupted() { assertFalse(condition.get()); } + + @Test + @Timeout(5) + void shouldReturnTrueWhenConditionIsMet() { + AtomicInteger checks = new AtomicInteger(0); + + boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3); + + assertTrue(result); + } + + @Test + @Timeout(5) + void shouldReturnFalseWhenInterruptedWhileWaitingWithoutTimeout() { + try { + Thread.currentThread().interrupt(); + boolean result = Threads.waitUntil(() -> false); + + assertFalse(result); + } finally { + // clear the interrupted flag so it does not leak into other tests + Thread.interrupted(); + } + } + + @Test + @Timeout(5) + void shouldReturnTrueWhenConditionIsMetWithinTimeout() { + AtomicInteger checks = new AtomicInteger(0); + + boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3, Duration.ofSeconds(3)); + + assertTrue(result); + } + + @Test + @Timeout(5) + void shouldReturnFalseWhenConditionIsNotMetWithinTimeout() { + boolean result = Threads.waitUntil(() -> false, Duration.ofMillis(20)); + + assertFalse(result); + } + + @Test + @Timeout(5) + void shouldReturnTrueWhenConditionIsMetWithinTimeoutAndPollInterval() { + AtomicInteger checks = new AtomicInteger(0); + + boolean result = Threads.waitUntil(() -> checks.incrementAndGet() >= 3, Duration.ofSeconds(3), Duration.ofMillis(1)); + + assertTrue(result); + } + + @Test + @Timeout(5) + void shouldReturnFalseWhenConditionIsNotMetWithinTimeoutAndPollInterval() { + boolean result = Threads.waitUntil(() -> false, Duration.ofMillis(20), Duration.ofMillis(1)); + + assertFalse(result); + } } @Nested @@ -707,6 +876,53 @@ void shouldExecuteThrottledWithExecutorAsAlias() { assertThat(executions.get(), equalTo(THREAD_COUNT)); } + + @Test + void shouldNotWaitForIntervalAfterLastBatch() { + AtomicInteger executions = new AtomicInteger(0); + List runnables = IntStream.range(0, 4) + .mapToObj(i -> (Runnable) executions::incrementAndGet) + .toList(); + + // a single batch (exactly threadCount items) must not wait for the interval + assertTimeoutPreemptively(Duration.ofSeconds(2), + () -> Threads.execute(runnables, 4, Duration.ofSeconds(30), ExecutionType.SEQUENTIAL)); + + assertThat(executions.get(), equalTo(4)); + } + + @Test + void shouldExecuteExactBatchesWithoutEmptyBatch() { + List runnables = IntStream.range(0, 4) + .mapToObj(i -> (Runnable) new AtomicInteger(i)::incrementAndGet) + .toList(); + Executor executor = Runnable::run; + + try (MockedStatic threadsMock = Mockito.mockStatic(Threads.class, Mockito.CALLS_REAL_METHODS)) { + Threads.execute(runnables, 2, Duration.ofMillis(1), executor); + + threadsMock.verify(() -> Threads.execute(runnables.subList(0, 2), executor)); + threadsMock.verify(() -> Threads.execute(runnables.subList(2, 4), executor)); + threadsMock.verify(() -> Threads.execute(anyList(), eq(executor)), times(2)); + } + } + + @Test + void shouldExecuteLastPartialBatch() { + List runnables = IntStream.range(0, 5) + .mapToObj(i -> (Runnable) new AtomicInteger(i)::incrementAndGet) + .toList(); + Executor executor = Runnable::run; + + try (MockedStatic threadsMock = Mockito.mockStatic(Threads.class, Mockito.CALLS_REAL_METHODS)) { + Threads.execute(runnables, 2, Duration.ofMillis(1), executor); + + threadsMock.verify(() -> Threads.execute(runnables.subList(0, 2), executor)); + threadsMock.verify(() -> Threads.execute(runnables.subList(2, 4), executor)); + threadsMock.verify(() -> Threads.execute(runnables.subList(4, 5), executor)); + threadsMock.verify(() -> Threads.execute(anyList(), eq(executor)), times(3)); + } + } } @Nested From 15e742465971654ff6a8b6452367e2655586bb19 Mon Sep 17 00:00:00 2001 From: raduking Date: Thu, 26 Nov 2026 11:49:34 +0200 Subject: [PATCH 05/13] Cancel previous task if one overlaps. --- .../morphix/lang/thread/ReschedulingTask.java | 6 +- .../lang/thread/ReschedulingTaskTest.java | 244 ++++++++++++++++-- 2 files changed, 227 insertions(+), 23 deletions(-) diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index 76718b50..2fe90b6f 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -326,7 +326,11 @@ private void scheduleNext() { ScheduledFuture newTask = executor.schedule(this::execute, delay.toMillis(), TimeUnit.MILLISECONDS); if (isEnabled()) { logger.debug("[{}] Scheduled new task: {}.", name, debugInfo(newTask)); - scheduledTask.set(newTask); + ScheduledFuture previous = scheduledTask.getAndSet(newTask); + if (null != previous && previous != newTask) { + logger.debug("[{}] Replacing previously scheduled task with a new one: cancelling {}.", name, debugInfo(previous)); + cancel(previous); + } if (isDisabled()) { logger.debug("[{}] Task was disabled during scheduling.", name); if (scheduledTask.compareAndSet(newTask, null)) { diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index e00585a4..616330df 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -19,6 +19,7 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.sameInstance; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; @@ -46,6 +47,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; @@ -58,12 +60,14 @@ import org.junit.jupiter.api.Timeout; import org.morphix.lang.function.ExecutionWrapper; import org.morphix.lang.function.LoggerAdapter; +import org.morphix.lang.function.Predicates; import org.morphix.lang.function.Runnables; import org.morphix.lang.logging.JulLoggerAdapter; import org.morphix.lang.resource.ScopedResource; import org.morphix.lang.retry.Retry; import org.morphix.lang.retry.WaitCounter; import org.morphix.reflection.Constructors; +import org.morphix.reflection.Fields; import org.morphix.reflection.Methods; import org.morphix.utils.Tests; @@ -1034,28 +1038,27 @@ void shouldRescheduleMultipleTimesAndCloseAllFinishedTasks() throws Exception { task.close(); executor.close(); - // execution 1 (sync) schedules Future 1 (Execution 2). - // execution 2 runs, schedules Future 2 (Execution 3). - // execution 3 runs, disable() is called, skips further scheduling. + // execution 1 runs on the enable thread and schedules future 1 + // execution 2 runs on the scheduler thread, schedules future 2, and may cancel future 1 on publish when still pending + // execution 3 runs, then disable() cancels the scheduled future and skips further scheduling assertThat(scheduledFutures.size(), is(executionCount - 1)); - // future 1 completed naturally and should NOT have been explicitly cancelled - // future 2 was active when disable() was invoked, so it MUST have been cancelled - // future 3 was never scheduled, so it should not be in the list of scheduled futures at all - // the order is not guaranteed, but we can check that one future was cancelled and the other was not - ScheduledFuture firstFuture = scheduledFutures.stream() - .filter(f -> !f.isCancelled()) // The one that finished - .findFirst() - .orElseThrow(); - - ScheduledFuture lastFuture = scheduledFutures.stream() + // 1. both futures are spied instances returned from executor.schedule(...) + // 2. publishing a newer future or calling disable() cancels an older one, so at least one must be marked cancelled + // 3. any future not marked cancelled must not have had cancel() called on it by the task + ScheduledFuture cancelledFuture = scheduledFutures.stream() .filter(Future::isCancelled) .findFirst() - .orElseThrow(); - - // Now verify regardless of insertion order - verify(firstFuture, never()).cancel(anyBoolean()); - verify(lastFuture, atLeastOnce()).cancel(anyBoolean()); + .orElse(null); + assertNotNull(cancelledFuture); + verify(cancelledFuture, atLeastOnce()).cancel(anyBoolean()); + + List> notCancelledFutures = scheduledFutures.stream() + .filter(Predicates.not(Future::isCancelled)) + .toList(); + for (ScheduledFuture notCancelledFuture : notCancelledFutures) { + verify(notCancelledFuture, never()).cancel(anyBoolean()); + } assertThat(completed, is(true)); assertThat(counter.get(), equalTo(executionCount)); @@ -1110,9 +1113,8 @@ void shouldCancelTaskIfDisabledAfterSettingReference() throws Exception { continueScheduling.countDown(); cancelAttempted.await(5, TimeUnit.SECONDS); - verify(spyLogger, timeout(1000)).debug( - startsWith("[{}] Cancelling orphaned task."), - eq("test-task")); + verify(spyLogger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", "test-task"); + verify(spyLogger, timeout(1000)).debug(startsWith("[{}] Cancelling orphaned task."), eq("test-task")); verify(mockFuture).cancel(anyBoolean()); } @@ -1181,7 +1183,7 @@ void shouldNotCancelTaskIfEnabledBackAfterDisabled() throws Exception { task.close(); verify(spyLogger, timeout(1000)).debug("[{}] New task was already scheduled, cancelling not needed.", TASK_NAME); - verify(mockFuture1, never()).cancel(anyBoolean()); + // a later publish may still supersede and cancel the earlier scheduled future verify(mockFuture2).cancel(anyBoolean()); } } @@ -1356,11 +1358,151 @@ void shouldLogWhenCancellingScheduledTask() { task.enable(); task.disable(); + verify(logger).debug(eq("[{}] Scheduled new task: {}."), eq(TASK_NAME), any()); verify(logger).debug(eq("[{}] Called cancel scheduled task: {}."), eq(TASK_NAME), any()); verify(logger).debug(eq("[{}] Attempting to cancel scheduled task: {}."), eq(TASK_NAME), any()); verify(scheduledFuture).cancel(anyBoolean()); } + @Test + @SuppressWarnings("resource") + void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() throws Exception { + ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + LoggerAdapter logger = mock(LoggerAdapter.class); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> Duration.ofSeconds(5)) + .logger(logger) + .build(); + ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + + verify(logger).debug("[{}] Scheduling next execution in {}ms.", TASK_NAME, Duration.ofSeconds(5).toMillis()); + verify(logger).debug(eq("[{}] Scheduled new task: {}."), eq(TASK_NAME), any()); + } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenReplacingPreviouslyScheduledTaskWithNewOne() throws Exception { + ScheduledFuture future1 = mock(ScheduledFuture.class); + ScheduledFuture future2 = mock(ScheduledFuture.class); + doReturn(true).when(future1).cancel(anyBoolean()); + doReturn(false).when(future1).isDone(); + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + doReturn(future1).doReturn(future2).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any()); + + LoggerAdapter logger = mock(LoggerAdapter.class); + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> Duration.ofSeconds(5)) + .logger(logger) + .build(); + ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + + verify(logger).debug(eq("[{}] Replacing previously scheduled task with a new one: cancelling {}."), eq(TASK_NAME), + any()); + } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenTaskWasDisabledDuringSchedulingAndOrphanIsCancelled() throws Exception { + CountDownLatch taskIsSet = new CountDownLatch(1); + CountDownLatch continueScheduling = new CountDownLatch(1); + + ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); + ScheduledFuture mockFuture = mock(ScheduledFuture.class); + doReturn(true).when(mockFuture).cancel(anyBoolean()); + doReturn(mockFuture).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any()); + + LoggerAdapter logger = mock(LoggerAdapter.class); + doAnswer(invocation -> { + taskIsSet.countDown(); + continueScheduling.await(); + return null; + }).when(logger).debug(startsWith("[{}] Scheduled new task"), any(), any()); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(mockExecutor)) + .task(Runnables.doNothing()) + .nextDelay(Duration.ofMillis(500)) + .logger(logger) + .build(); + + Thread.ofVirtual().start(task::enable); + taskIsSet.await(5, TimeUnit.SECONDS); + task.disable(); + continueScheduling.countDown(); + + verify(logger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", TASK_NAME); + verify(logger, timeout(1000)).debug(startsWith("[{}] Cancelling orphaned task."), eq(TASK_NAME)); + } + + @Test + @SuppressWarnings("resource") + void shouldLogWhenNewTaskWasAlreadyScheduledCancellingNotNeeded() throws Exception { + CountDownLatch firstTaskIsSet = new CountDownLatch(1); + CountDownLatch secondTaskIsSet = new CountDownLatch(1); + CountDownLatch continueScheduling = new CountDownLatch(1); + CountDownLatch disableCalled = new CountDownLatch(1); + CountDownLatch enableCalled = new CountDownLatch(1); + + ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); + ScheduledFuture mockFuture1 = mock(ScheduledFuture.class); + ScheduledFuture mockFuture2 = mock(ScheduledFuture.class); + doReturn(mockFuture1).doReturn(mockFuture2).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any()); + + LoggerAdapter logger = mock(LoggerAdapter.class); + doAnswer(invocation -> { + if (firstTaskIsSet.getCount() > 0) { + firstTaskIsSet.countDown(); + } else { + secondTaskIsSet.countDown(); + } + continueScheduling.await(); + return null; + }).when(logger).debug(startsWith("[{}] Scheduled new task"), any(), any()); + doAnswer(invocation -> { + disableCalled.countDown(); + enableCalled.await(); + return null; + }).when(logger).debug(startsWith("[{}] Task was disabled during scheduling"), any()); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(mockExecutor)) + .task(Runnables.doNothing()) + .nextDelay(Duration.ofMillis(500)) + .logger(logger) + .build(); + + Thread.ofVirtual().start(task::enable); + firstTaskIsSet.await(5, TimeUnit.SECONDS); + task.disable(); + continueScheduling.countDown(); + disableCalled.await(5, TimeUnit.SECONDS); + task.enable(); + secondTaskIsSet.await(5, TimeUnit.SECONDS); + enableCalled.countDown(); + task.close(); + + verify(logger, timeout(1000)).debug("[{}] Task was disabled during scheduling.", TASK_NAME); + verify(logger, timeout(1000)).debug("[{}] New task was already scheduled, cancelling not needed.", TASK_NAME); + } + @Test @SuppressWarnings("resource") void shouldLogWhenSkippingExecutionBecauseTaskIsDisabled() { @@ -1419,6 +1561,64 @@ void shouldLogErrorWhenTaskExecutionFails() { verify(logger).error("[{}] Error during task execution.", TASK_NAME, exception); } + } + + @Nested + class ConcurrentSchedulingTests { + + @Test + @SuppressWarnings("resource") + void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending() throws Exception { + ScheduledFuture future1 = mock(ScheduledFuture.class); + ScheduledFuture future2 = mock(ScheduledFuture.class); + doReturn(true).when(future1).cancel(anyBoolean()); + doReturn(true).when(future2).cancel(anyBoolean()); + doReturn(false).when(future1).isDone(); + ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); + doReturn(future1).doReturn(future2).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any()); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(mockExecutor)) + .task(Runnables.doNothing()) + .nextDelay(Duration.ofSeconds(5)) + .build(); + ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + + verify(future1).cancel(anyBoolean()); + verify(future2, never()).cancel(anyBoolean()); + } + + @Test + @SuppressWarnings("resource") + void shouldNotCancelScheduledTaskWhenReplacingWithTheSameFutureReference() throws Exception { + ScheduledFuture future = mock(ScheduledFuture.class); + ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); + doReturn(future).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any()); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(mockExecutor)) + .task(Runnables.doNothing()) + .nextDelay(Duration.ofSeconds(5)) + .build(); + ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + + verify(future, never()).cancel(anyBoolean()); + } + } + + @Nested + class SchedulingWhileDisabledTests { + @Test @SuppressWarnings("resource") void shouldCancelAndLogWhenTaskIsDisabledWhileSchedulingNext() { From ab83a7e86a7f122e233724f3fdbec3cd3c250ed2 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 27 Nov 2026 12:09:19 +0200 Subject: [PATCH 06/13] Cannot re-enable `ReschedulngTask` after `close`. --- CHANGELOG.md | 2 + .../morphix/lang/thread/ReschedulingTask.java | 42 +++++++++--- .../lang/thread/ReschedulingTaskTest.java | 66 +++++++++++++++++++ 3 files changed, 101 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 12b9ec93..84ad589c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ `1.1.4` - Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling. +- Fixed `ReschedulingTask.enable()` to throw `IllegalStateException` after the task has been closed. +- Changed `ReschedulingTask.close()` to mark the task permanently closed before cleaning up resources. --- diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index 2fe90b6f..bdb2fe97 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -20,7 +20,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; @@ -55,6 +54,27 @@ */ public class ReschedulingTask implements AutoCloseable { + /** + * Lifecycle states. A closed task cannot be enabled again. + */ + private enum State { + + /** + * The task is inactive and can be enabled. + */ + DISABLED, + + /** + * The task is active and can execute and reschedule itself. + */ + ENABLED, + + /** + * The task is permanently inactive and cannot be enabled again. + */ + CLOSED + } + /** * Name space class for default values. Other defaults which are not constants: *

    @@ -168,10 +188,9 @@ private Default() { private final Duration terminationTimeout; /** - * Atomic flag to indicate whether the task is enabled or disabled. When disabled, the task will not execute or - * reschedule itself. + * Atomic lifecycle state. Only enabled tasks execute or reschedule themselves, and closing is permanent. */ - private final AtomicBoolean enabled = new AtomicBoolean(false); + private final AtomicReference state = new AtomicReference<>(State.DISABLED); /** * Atomic reference to the currently scheduled task. This allows for safe cancellation and rescheduling across threads. @@ -224,7 +243,7 @@ public String getName() { } /** - * Closes the task, ensuring that any scheduled executions are cancelled and resources are released. + * Permanently closes the task, ensuring that any scheduled executions are cancelled and resources are released. *

    * Note: the scheduled task (future) and the scheduler will only be closed if the scheduler is managed by this instance. * @@ -232,7 +251,7 @@ public String getName() { */ @Override public void close() throws Exception { - enabled.set(false); + state.set(State.CLOSED); boolean cancelled = cancelScheduledTask(); scheduler.closeIfManaged(() -> closeRefreshScheduler(cancelled)); } @@ -350,9 +369,14 @@ private void scheduleNext() { * Starts the self-rescheduling task (if not already running). * * @return true if the task was started, false if it was already enabled + * @throws IllegalStateException if the task has been closed */ public boolean enable() { - if (!enabled.compareAndSet(false, true)) { + State previous = state.compareAndExchange(State.DISABLED, State.ENABLED); + if (State.CLOSED == previous) { + throw new IllegalStateException("Cannot enable a closed rescheduling task"); + } + if (State.ENABLED == previous) { return false; } logger.debug("[{}] Enabling rescheduling task.", name); @@ -366,7 +390,7 @@ public boolean enable() { * @return true if the task was disabled, false if it was already disabled */ public boolean disable() { - if (!enabled.compareAndSet(true, false)) { + if (!state.compareAndSet(State.ENABLED, State.DISABLED)) { return false; } logger.debug("[{}] Disabling rescheduling task.", name); @@ -394,7 +418,7 @@ protected String debugInfo(final ScheduledFuture task) { * @return true if enabled, false if disabled */ public boolean isEnabled() { - return enabled.get(); + return State.ENABLED == state.get(); } /** diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index 616330df..ae36daf4 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -58,6 +58,8 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.morphix.lang.function.ExecutionWrapper; import org.morphix.lang.function.LoggerAdapter; import org.morphix.lang.function.Predicates; @@ -673,6 +675,70 @@ void shouldSkipExecutionWhenDisabled() { @Nested class CloseAndResourceManagementTests { + @ParameterizedTest + @CsvSource({ + "true, true", + "true, false", + "false, true", + "false, false" + }) + @SuppressWarnings("resource") + void shouldRejectEnableAfterClose(final boolean managed, final boolean initiallyEnabled) throws Exception { + Runnable refreshTask = mock(Runnable.class); + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + doReturn(true).when(scheduledFuture).cancel(anyBoolean()); + ScopedResource resource = managed + ? ScopedResource.managed(scheduledExecutor) + : ScopedResource.unmanaged(scheduledExecutor); + ReschedulingTask task = ReschedulingTask.builder() + .scheduler(resource) + .task(refreshTask) + .nextDelay(DELAY) + .build(); + if (initiallyEnabled) { + task.enable(); + } + + task.close(); + + assertThrows(IllegalStateException.class, task::enable); + assertThat(task.disable(), is(false)); + task.close(); + assertThrows(IllegalStateException.class, task::enable); + assertThat(task.isEnabled(), is(false)); + assertThat(task.isDisabled(), is(true)); + assertThat(task.isScheduled(), is(false)); + verify(refreshTask, times(initiallyEnabled ? 1 : 0)).run(); + verify(scheduledExecutor, times(initiallyEnabled ? 1 : 0)) + .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + } + + @Test + @SuppressWarnings("resource") + void shouldRejectEnableWhileCloseIsCleaningUpEvenIfCleanupFails() { + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + Runnable refreshTask = mock(Runnable.class); + ReschedulingTask task = ReschedulingTask.builder() + .scheduler(ScopedResource.managed(scheduledExecutor)) + .task(refreshTask) + .nextDelay(DELAY) + .build(); + IllegalStateException failure = new IllegalStateException("Scheduler cleanup failed"); + doAnswer(invocation -> { + assertThrows(IllegalStateException.class, task::enable); + throw failure; + }).when(scheduledExecutor).close(); + + assertThat(assertThrows(IllegalStateException.class, task::close), is(sameInstance(failure))); + + assertThrows(IllegalStateException.class, task::enable); + assertThat(task.isDisabled(), is(true)); + verify(refreshTask, never()).run(); + verify(scheduledExecutor, never()).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + } + @Test @SuppressWarnings("resource") void shouldDisableTaskWhenClosed() throws Exception { From 601cfebb453ebfd3b18d52a5dfe3c923efd4fbb4 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Fri, 27 Nov 2026 12:20:46 +0200 Subject: [PATCH 07/13] Fix tests. --- .../lang/thread/ReschedulingTaskTest.java | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index ae36daf4..ea2d982a 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -47,7 +47,6 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; @@ -69,7 +68,6 @@ import org.morphix.lang.retry.Retry; import org.morphix.lang.retry.WaitCounter; import org.morphix.reflection.Constructors; -import org.morphix.reflection.Fields; import org.morphix.reflection.Methods; import org.morphix.utils.Tests; @@ -1445,10 +1443,8 @@ void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() throws Exception { .nextDelay(() -> Duration.ofSeconds(5)) .logger(logger) .build(); - ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); - Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); - Methods.IgnoreAccess.invoke(scheduleNextMethod, task); + task.enable(); verify(logger).debug("[{}] Scheduling next execution in {}ms.", TASK_NAME, Duration.ofSeconds(5).toMillis()); verify(logger).debug(eq("[{}] Scheduled new task: {}."), eq(TASK_NAME), any()); @@ -1472,11 +1468,11 @@ void shouldLogWhenReplacingPreviouslyScheduledTaskWithNewOne() throws Exception .nextDelay(() -> Duration.ofSeconds(5)) .logger(logger) .build(); - ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + task.enable(); Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); Methods.IgnoreAccess.invoke(scheduleNextMethod, task); - Methods.IgnoreAccess.invoke(scheduleNextMethod, task); verify(logger).debug(eq("[{}] Replacing previously scheduled task with a new one: cancelling {}."), eq(TASK_NAME), any()); @@ -1649,11 +1645,11 @@ void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending( .task(Runnables.doNothing()) .nextDelay(Duration.ofSeconds(5)) .build(); - ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + task.enable(); Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); Methods.IgnoreAccess.invoke(scheduleNextMethod, task); - Methods.IgnoreAccess.invoke(scheduleNextMethod, task); verify(future1).cancel(anyBoolean()); verify(future2, never()).cancel(anyBoolean()); @@ -1672,11 +1668,11 @@ void shouldNotCancelScheduledTaskWhenReplacingWithTheSameFutureReference() throw .task(Runnables.doNothing()) .nextDelay(Duration.ofSeconds(5)) .build(); - ((AtomicBoolean) Fields.IgnoreAccess.get(task, ReschedulingTask.class.getDeclaredField("enabled"))).set(true); + + task.enable(); Method scheduleNextMethod = Methods.getOneDeclared("scheduleNext", ReschedulingTask.class); Methods.IgnoreAccess.invoke(scheduleNextMethod, task); - Methods.IgnoreAccess.invoke(scheduleNextMethod, task); verify(future, never()).cancel(anyBoolean()); } From af194032e3e1bee250678300a34b6894b58a8e46 Mon Sep 17 00:00:00 2001 From: raduking Date: Sun, 29 Nov 2026 03:39:16 +0200 Subject: [PATCH 08/13] Sync ReschedulingTask formal verification with State lifecycle and reconcileSchedule. Add TLC model for lifecycle enum, reconcile after cancel/publish, and the verification skill. Co-authored-by: Cursor --- .../ReschedulingTask.cfg | 15 + .../ReschedulingTask.tla | 340 ++++++++++++++++++ .../skills/verify-rescheduling-task/check.py | 256 +++++++++++++ CHANGELOG.md | 1 + .../morphix/lang/thread/ReschedulingTask.java | 28 +- 5 files changed, 638 insertions(+), 2 deletions(-) create mode 100644 .cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg create mode 100644 .cursor/skills/verify-rescheduling-task/ReschedulingTask.tla create mode 100755 .cursor/skills/verify-rescheduling-task/check.py diff --git a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg new file mode 100644 index 00000000..a13e10f3 --- /dev/null +++ b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg @@ -0,0 +1,15 @@ +SPECIFICATION Spec + +CONSTANTS + Clients = {c1, c2} + Workers = {w1, w2} + MaxOps = 2 + MaxFutures = 5 + +INVARIANTS + TypeOK + NoFutureLeftAfterDisable + AtMostOneFutureWhileEnabled + NextExecutionTrackedWhileEnabled + +CHECK_DEADLOCK FALSE diff --git a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla new file mode 100644 index 00000000..47d1e2f5 --- /dev/null +++ b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla @@ -0,0 +1,340 @@ +---------------------------- MODULE ReschedulingTask ---------------------------- +(***************************************************************************) +(* Model of the enable / disable / close / reschedule protocol of *) +(* src/main/java/org/morphix/lang/thread/ReschedulingTask.java *) +(* *) +(* One step of this model is one atomic operation of the Java code: one *) +(* AtomicReference state transition, one read of isEnabled() or *) +(* isDisabled(), one ScheduledExecutorService.schedule(...) call, or one *) +(* Future.cancel(...) call (with the isDone check in front of it). The *) +(* label of each step names the Java method and statement it models. *) +(* *) +(* The scheduled futures are the ones the scheduler holds. A future that *) +(* is "pending" will run execute() on a scheduler thread when it fires. *) +(***************************************************************************) +EXTENDS Naturals, FiniteSets + +CONSTANTS + Clients, \* threads that call enable(), disable() and close() + Workers, \* scheduler threads that run execute() when a future fires + MaxOps, \* how many calls each client thread makes + MaxFutures \* how many scheduled futures the run may create + +NONE == 0 \* no future (a null scheduledTask) + +Threads == Clients \union Workers +FutureIds == 1..MaxFutures +LifecycleStates == {"disabled", "enabled", "closed"} + +VARIABLES + lifecycle, \* ReschedulingTask.State (DISABLED / ENABLED / CLOSED) + scheduledTask, \* ReschedulingTask.scheduledTask (NONE = null) + fut, \* state of every future the scheduler created + nextId, \* id of the next future schedule(...) creates + pc, \* where each thread is in the Java code + newTask, \* scheduleNext(): local variable newTask of each thread + victim, \* cancelScheduledTask(): local variable taskToCancel of each thread + opsLeft, \* calls each client thread may still make + last \* thread and Java statement of the latest step (trace readability only) + +vars == <> + +Pending == {f \in FutureIds : fut[f] = "pending"} + +IsEnabled == lifecycle = "enabled" + +\* No thread is inside enable(), disable(), close(), execute() or scheduleNext(). +Quiescent == \A t \in Threads : pc[t] = "idle" + +Init == + /\ lifecycle = "disabled" + /\ scheduledTask = NONE + /\ fut = [f \in FutureIds |-> "unused"] + /\ nextId = 1 + /\ pc = [t \in Threads |-> "idle"] + /\ newTask = [t \in Threads |-> NONE] + /\ victim = [t \in Threads |-> NONE] + /\ opsLeft = [c \in Clients |-> MaxOps] + /\ last = [thread |-> "-", step |-> "initial state"] + +\* Future.cancel: only a future that has not fired yet is stopped. +CancelFuture(f) == + fut' = IF f \in Pending THEN [fut EXCEPT ![f] = "cancelled"] ELSE fut + +GoTo(t, label) == pc' = [pc EXCEPT ![t] = label] + +Mark(t, what) == last' = [thread |-> t, step |-> what] + +(***************************************************************************) +(* Client calls *) +(***************************************************************************) + +CallEnable(c) == + /\ pc[c] = "idle" /\ opsLeft[c] > 0 + /\ Mark(c, "enable() is called") + /\ GoTo(c, "enable.cas") + /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] + /\ UNCHANGED <> + +CallDisable(c) == + /\ pc[c] = "idle" /\ opsLeft[c] > 0 + /\ Mark(c, "disable() is called") + /\ GoTo(c, "disable.cas") + /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] + /\ UNCHANGED <> + +CallClose(c) == + /\ pc[c] = "idle" /\ opsLeft[c] > 0 + /\ Mark(c, "close() is called") + /\ GoTo(c, "close.set") + /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] + /\ UNCHANGED <> + +(***************************************************************************) +(* enable(): state.compareAndExchange(DISABLED, ENABLED), then execute() *) +(***************************************************************************) + +EnableCas(c) == + /\ pc[c] = "enable.cas" + /\ Mark(c, "enable(): state.compareAndExchange(DISABLED, ENABLED)") + /\ IF lifecycle = "disabled" + THEN /\ lifecycle' = "enabled" + /\ GoTo(c, "execute.check") + ELSE /\ lifecycle' = lifecycle + /\ GoTo(c, "idle") + /\ UNCHANGED <> + +(***************************************************************************) +(* disable(): state.compareAndSet(ENABLED, DISABLED), cancelScheduledTask()*) +(* close(): state.set(CLOSED), then cancelScheduledTask() *) +(***************************************************************************) + +DisableCas(c) == + /\ pc[c] = "disable.cas" + /\ Mark(c, "disable(): state.compareAndSet(ENABLED, DISABLED)") + /\ IF lifecycle = "enabled" + THEN /\ lifecycle' = "disabled" + /\ GoTo(c, "cancelScheduled.take") + ELSE /\ lifecycle' = lifecycle + /\ GoTo(c, "idle") + /\ UNCHANGED <> + +CloseSet(c) == + /\ pc[c] = "close.set" + /\ Mark(c, "close(): state.set(CLOSED)") + /\ lifecycle' = "closed" + /\ GoTo(c, "cancelScheduled.take") + /\ UNCHANGED <> + +\* cancelScheduledTask(): scheduledTask.getAndSet(null) +CancelScheduledTake(c) == + /\ pc[c] = "cancelScheduled.take" + /\ Mark(c, "cancelScheduledTask(): scheduledTask.getAndSet(null)") + /\ victim' = [victim EXCEPT ![c] = scheduledTask] + /\ scheduledTask' = NONE + /\ GoTo(c, IF scheduledTask = NONE THEN "cancelScheduled.ensure" ELSE "cancelScheduled.cancel") + /\ UNCHANGED <> + +\* cancelScheduledTask(): cancel(taskToCancel) +CancelScheduledCancel(c) == + /\ pc[c] = "cancelScheduled.cancel" + /\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)") + /\ CancelFuture(victim[c]) + /\ GoTo(c, "cancelScheduled.ensure") + /\ UNCHANGED <> + +CancelScheduledEnsure(c) == + /\ pc[c] = "cancelScheduled.ensure" + /\ Mark(c, "cancelScheduledTask(): reconcileSchedule()") + /\ IF /\ IsEnabled + /\ ~(scheduledTask \in Pending) + THEN /\ lifecycle' = "disabled" + ELSE /\ lifecycle' = lifecycle + /\ GoTo(c, "idle") + /\ UNCHANGED <> + +(***************************************************************************) +(* Scheduler: a pending future fires and its execute() runs on a worker *) +(***************************************************************************) + +Fire(w, f) == + /\ pc[w] = "idle" /\ f \in Pending + /\ Mark(w, "the scheduler fires a pending future: execute() starts on a worker") + /\ fut' = [fut EXCEPT ![f] = "fired"] + /\ scheduledTask' = IF scheduledTask = f THEN NONE ELSE scheduledTask + /\ GoTo(w, "execute.check") + /\ UNCHANGED <> + +(***************************************************************************) +(* execute() *) +(***************************************************************************) + +\* if (isDisabled()) { return; } +ExecuteCheck(t) == + /\ pc[t] = "execute.check" + /\ Mark(t, "execute(): if (isDisabled())") + /\ GoTo(t, IF IsEnabled THEN "execute.run" ELSE "idle") + /\ UNCHANGED <> + +\* try { refreshTask } catch (...) { } finally { scheduleNext(); } +ExecuteRun(t) == + /\ pc[t] = "execute.run" + /\ Mark(t, "execute(): refreshTask runs") + /\ GoTo(t, "execute.dropDone") + /\ UNCHANGED <> + +ExecuteDropDone(t) == + /\ pc[t] = "execute.dropDone" + /\ Mark(t, "execute(): clear done scheduledTask before scheduleNext") + /\ scheduledTask' = IF /\ scheduledTask # NONE + /\ fut[scheduledTask] = "fired" + THEN NONE + ELSE scheduledTask + /\ GoTo(t, "next.check") + /\ UNCHANGED <> + +(***************************************************************************) +(* scheduleNext() *) +(***************************************************************************) + +\* if (isDisabled()) { return; } +NextCheck(t) == + /\ pc[t] = "next.check" + /\ Mark(t, "scheduleNext(): if (isDisabled())") + /\ GoTo(t, IF IsEnabled THEN "next.schedule" ELSE "idle") + /\ UNCHANGED <> + +\* ScheduledFuture newTask = executor.schedule(this::execute, ...); +NextSchedule(t) == + /\ pc[t] = "next.schedule" + /\ Mark(t, "scheduleNext(): executor.schedule(this::execute, ...)") + /\ nextId <= MaxFutures + /\ fut' = [fut EXCEPT ![nextId] = "pending"] + /\ newTask' = [newTask EXCEPT ![t] = nextId] + /\ nextId' = nextId + 1 + /\ GoTo(t, "next.checkEnabled") + /\ UNCHANGED <> + +\* if (isEnabled()) { ... } else { cancel(newTask); } +NextCheckEnabled(t) == + /\ pc[t] = "next.checkEnabled" + /\ Mark(t, "scheduleNext(): if (isEnabled())") + /\ GoTo(t, IF IsEnabled THEN "next.publish" ELSE "next.cancelImmediate") + /\ UNCHANGED <> + +\* scheduledTask.getAndSet(newTask); +NextPublish(t) == + /\ pc[t] = "next.publish" + /\ Mark(t, "scheduleNext(): scheduledTask.getAndSet(newTask)") + /\ LET prev == scheduledTask IN + /\ scheduledTask' = newTask[t] + /\ fut' = IF prev # NONE /\ prev # newTask[t] /\ prev \in Pending + THEN [fut EXCEPT ![prev] = "cancelled"] + ELSE fut + /\ GoTo(t, "next.recheck") + /\ UNCHANGED <> + +\* if (isDisabled()) { ... } +NextRecheck(t) == + /\ pc[t] = "next.recheck" + /\ Mark(t, "scheduleNext(): reconcileSchedule()") + /\ IF ~IsEnabled + THEN /\ GoTo(t, "next.take") + /\ UNCHANGED <> + ELSE IF scheduledTask \in Pending + THEN /\ GoTo(t, "idle") + /\ UNCHANGED <> + ELSE /\ lifecycle' = "disabled" + /\ scheduledTask' = NONE + /\ GoTo(t, "idle") + /\ UNCHANGED <> + +\* if (scheduledTask.compareAndSet(newTask, null)) { cancel(newTask); } +NextTake(t) == + /\ pc[t] = "next.take" + /\ Mark(t, "scheduleNext(): scheduledTask.compareAndSet(newTask, null)") + /\ IF scheduledTask = newTask[t] + THEN /\ scheduledTask' = NONE + /\ GoTo(t, "next.cancelOrphan") + ELSE /\ scheduledTask' = scheduledTask + /\ GoTo(t, "idle") + /\ UNCHANGED <> + +NextCancelOrphan(t) == + /\ pc[t] = "next.cancelOrphan" + /\ Mark(t, "scheduleNext(): cancel(newTask) for the orphan") + /\ CancelFuture(newTask[t]) + /\ GoTo(t, "idle") + /\ UNCHANGED <> + +NextCancelImmediate(t) == + /\ pc[t] = "next.cancelImmediate" + /\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing") + /\ CancelFuture(newTask[t]) + /\ GoTo(t, "idle") + /\ UNCHANGED <> + +\* Nothing is left to do (also used when MaxFutures is exhausted). +Done == + /\ \A c \in Clients : opsLeft[c] = 0 \/ pc[c] /= "idle" + /\ UNCHANGED vars + +Next == + \/ \E c \in Clients : CallEnable(c) + \/ \E c \in Clients : CallDisable(c) + \/ \E c \in Clients : CallClose(c) + \/ \E c \in Clients : EnableCas(c) + \/ \E c \in Clients : DisableCas(c) + \/ \E c \in Clients : CloseSet(c) + \/ \E c \in Clients : CancelScheduledTake(c) + \/ \E c \in Clients : CancelScheduledCancel(c) + \/ \E c \in Clients : CancelScheduledEnsure(c) + \/ \E w \in Workers, f \in FutureIds : Fire(w, f) + \/ \E t \in Threads : ExecuteCheck(t) + \/ \E t \in Threads : ExecuteRun(t) + \/ \E t \in Threads : ExecuteDropDone(t) + \/ \E t \in Threads : NextCheck(t) + \/ \E t \in Threads : NextSchedule(t) + \/ \E t \in Threads : NextCheckEnabled(t) + \/ \E t \in Threads : NextPublish(t) + \/ \E t \in Threads : NextRecheck(t) + \/ \E t \in Threads : NextTake(t) + \/ \E t \in Threads : NextCancelOrphan(t) + \/ \E t \in Threads : NextCancelImmediate(t) + +Spec == Init /\ [][Next]_vars + +(***************************************************************************) +(* Properties. Each one is checked only when no thread is inside one of *) +(* the methods above, because while a method runs the state is allowed to *) +(* be in between. *) +(***************************************************************************) + +TypeOK == + /\ lifecycle \in LifecycleStates + /\ scheduledTask \in {NONE} \union FutureIds + /\ fut \in [FutureIds -> {"unused", "pending", "cancelled", "fired"}] + /\ nextId \in 1..(MaxFutures + 1) + /\ pc \in [Threads -> {"idle", "enable.cas", "disable.cas", "close.set", + "cancelScheduled.take", "cancelScheduled.cancel", "cancelScheduled.ensure", + "execute.check", "execute.run", "execute.dropDone", "next.check", + "next.schedule", "next.checkEnabled", "next.publish", + "next.recheck", "next.take", "next.cancelOrphan", + "next.cancelImmediate"}] + +\* Once disable() or close() has returned and nothing else is running, no +\* future of this task is still waiting to fire. +NoFutureLeftAfterDisable == + (Quiescent /\ ~IsEnabled) => Pending = {} + +\* While the task is enabled and nothing else is running, at most one future +\* is waiting to fire: the task never runs two chains of executions. +AtMostOneFutureWhileEnabled == + (Quiescent /\ IsEnabled) => Cardinality(Pending) <= 1 + +\* While the task is enabled and nothing else is running, its next execution +\* is scheduled and scheduledTask points to it, so disable() can cancel it. +NextExecutionTrackedWhileEnabled == + (Quiescent /\ IsEnabled) => (scheduledTask \in Pending /\ Pending = {scheduledTask}) + +============================================================================= \ No newline at end of file diff --git a/.cursor/skills/verify-rescheduling-task/check.py b/.cursor/skills/verify-rescheduling-task/check.py new file mode 100755 index 00000000..16d96f30 --- /dev/null +++ b/.cursor/skills/verify-rescheduling-task/check.py @@ -0,0 +1,256 @@ +#!/usr/bin/env python3 +"""Runs the TLC model checker on ReschedulingTask.tla, one property at a time. + +Usage: + ./check.py check every property, report each one + ./check.py --mutants also prove that each property can fail: apply each broken variant + of the model and require that its property is reported as violated + ./check.py --drift only report whether the Java file changed since the sync commit + ./check.py --max-ops N change MaxOps (calls per client thread), default from the .cfg + +Exit code: 0 when every property holds or only known findings (known-findings.txt) fail, +1 when a property that is not a known finding fails or a mutant is not caught, +2 on a setup problem, 3 when the Java file changed since the sync commit (--drift only). + +Needs Java (any recent JDK) and, on the first run, network access to download tla2tools.jar. +""" +import argparse +import hashlib +import os +import re +import shutil +import subprocess +import sys +import tempfile +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +SPEC = "ReschedulingTask.tla" +CFG = "ReschedulingTask.cfg" +JAVA_FILE = "src/main/java/org/morphix/lang/thread/ReschedulingTask.java" + +TLA_VERSION = "v1.7.4" +TLA_URL = "https://github.com/tlaplus/tlaplus/releases/download/%s/tla2tools.jar" % TLA_VERSION +TLA_SHA256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" + +PROPERTIES = [ + "NoFutureLeftAfterDisable", + "AtMostOneFutureWhileEnabled", + "NextExecutionTrackedWhileEnabled", +] + +# Broken variants of the model. Each one is the model of the Java code with one safeguard removed. +# name: (what was removed from the Java code, [(model text, broken model text)], property that must fail) +MUTANTS = { + "no-recheck-after-publish": ( + "scheduleNext() without the second `if (isDisabled())` block that cancels an orphaned task", + [('THEN /\\ GoTo(t, "next.take")', 'THEN /\\ GoTo(t, "idle")')], + "NoFutureLeftAfterDisable", + ), + "no-cancel-when-disabled-before-publish": ( + "scheduleNext() without `cancel(newTask)` in the branch where the task got disabled before publishing", + [('/\\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing")\n /\\ CancelFuture(newTask[t])', + '/\\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing")\n /\\ fut\' = fut')], + "NoFutureLeftAfterDisable", + ), + "disable-does-not-cancel": ( + "cancelScheduledTask() without `cancel(taskToCancel)`", + [('/\\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)")\n /\\ CancelFuture(victim[c])', + '/\\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)")\n /\\ fut\' = fut')], + "NoFutureLeftAfterDisable", + ), + "no-reconcile-after-publish": ( + "scheduleNext() without `reconcileSchedule`", + [('ELSE IF scheduledTask \\in Pending\n THEN /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>\n ELSE /\\ lifecycle\' = "disabled"\n /\\ scheduledTask\' = NONE\n /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>', + 'ELSE /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>')], + "NextExecutionTrackedWhileEnabled", + ), +} + + +def read_sync_commit(): + with open(os.path.join(HERE, "SKILL.md")) as f: + m = re.search(r"^Sync commit: ([0-9a-f]{7,40})", f.read(), re.M) + return m.group(1) if m else None + + +def repo_root(): + return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], cwd=HERE, text=True).strip() + + +def drift(): + sync = read_sync_commit() + if not sync: + print("No `Sync commit:` line in SKILL.md.") + return 2 + root = repo_root() + diff = subprocess.run(["git", "diff", "--stat", sync, "--", JAVA_FILE], cwd=root, text=True, capture_output=True) + if diff.returncode != 0: + print("git diff failed: " + diff.stderr.strip()) + return 2 + if diff.stdout.strip(): + print("DRIFT: %s changed since the sync commit %s:" % (JAVA_FILE, sync)) + print(diff.stdout.rstrip()) + print("Compare the changed methods with the model (see SKILL.md, section Coverage) before trusting a pass.") + return 3 + print("No drift: %s is unchanged since the sync commit %s." % (JAVA_FILE, sync)) + return 0 + + +def tla_jar(): + override = os.environ.get("TLA2TOOLS_JAR") + if override: + return override + cache = os.path.join(os.path.expanduser("~"), ".cache", "morphix", "tla2tools-%s.jar" % TLA_VERSION) + if not os.path.exists(cache): + os.makedirs(os.path.dirname(cache), exist_ok=True) + print("Downloading %s ..." % TLA_URL) + tmp = cache + ".part" + urllib.request.urlretrieve(TLA_URL, tmp) + with open(tmp, "rb") as f: + digest = hashlib.sha256(f.read()).hexdigest() + if digest != TLA_SHA256: + os.remove(tmp) + raise SystemExit("tla2tools.jar checksum mismatch: " + digest) + os.replace(tmp, cache) + return cache + + +def make_cfg(prop, max_ops, target): + with open(os.path.join(HERE, CFG)) as f: + cfg = f.read() + cfg = re.sub(r"INVARIANTS\n(?: \w+\n)+", "INVARIANTS\n TypeOK\n %s\n" % prop, cfg) + if max_ops is not None: + cfg = re.sub(r"MaxOps = \d+", "MaxOps = %d" % max_ops, cfg) + with open(target, "w") as f: + f.write(cfg) + + +def run_tlc(jar, spec_dir, prop, max_ops): + work = tempfile.mkdtemp(prefix="tlc-") + try: + shutil.copy(os.path.join(spec_dir, SPEC), os.path.join(work, SPEC)) + cfg = os.path.join(work, "run.cfg") + make_cfg(prop, max_ops, cfg) + out = subprocess.run( + ["java", "-XX:+UseParallelGC", "-cp", jar, "tlc2.TLC", "-workers", "auto", + "-metadir", os.path.join(work, "states"), "-config", "run.cfg", SPEC], + cwd=work, text=True, capture_output=True) + return out.stdout + out.stderr + finally: + shutil.rmtree(work, ignore_errors=True) + + +def summary(output): + m = re.search(r"(\d+) states generated, (\d+) distinct states found", output) + return "%s distinct states" % m.group(2) if m else "no state count" + + +def violated(output, prop): + return "Invariant %s is violated" % prop in output + + +def trace(output): + """Condensed counterexample: one line per step, then the final state.""" + blocks = re.split(r"^State \d+: ", output, flags=re.M)[1:] + lines = [] + last_block = "" + for i, block in enumerate(blocks, 1): + last_block = block + m = re.search(r'last = \[thread\s*\|->\s*"?([\w-]+)"?,\s*step\s*\|->\s*"([^"]*)"\]', block, re.S) + if m and m.group(1) != "-": + lines.append(" %2d. %-3s %s" % (i, m.group(1), m.group(2))) + enabled = re.search(r"enabled = (TRUE|FALSE)", last_block) + sched = re.search(r"scheduledTask = (\d+)", last_block) + fut = re.search(r"fut = <<([^>]*)>>", last_block) + if enabled and sched and fut: + states = [s.strip().strip('"') for s in fut.group(1).split(",")] + shown = ", ".join("future %d %s" % (i, s) for i, s in enumerate(states, 1) if s != "unused") + lines.append(" end state: enabled=%s, scheduledTask=%s, %s" % ( + enabled.group(1), "null" if sched.group(1) == "0" else "future " + sched.group(1), shown)) + return "\n".join(lines) + + +def known_findings(): + path = os.path.join(HERE, "known-findings.txt") + if not os.path.exists(path): + return set() + with open(path) as f: + return {l.split("#")[0].strip() for l in f if l.split("#")[0].strip()} + + +def check_properties(jar, max_ops): + known = known_findings() + bad = False + for prop in PROPERTIES: + out = run_tlc(jar, HERE, prop, max_ops) + if violated(out, prop): + tag = "KNOWN FINDING" if prop in known else "VIOLATED" + print("%s %s (%s)" % (tag, prop, summary(out))) + print(trace(out)) + bad = bad or prop not in known + elif "Model checking completed. No error has been found." in out: + note = " <-- listed in known-findings.txt but now holds: remove it from the list" if prop in known else "" + print("PASS %s (%s)%s" % (prop, summary(out), note)) + else: + print("ERROR %s: TLC did not finish. Last output:" % prop) + print("\n".join(out.splitlines()[-15:])) + return 2 + return 1 if bad else 0 + + +def check_mutants(jar, max_ops): + bad = False + with open(os.path.join(HERE, SPEC)) as f: + spec = f.read() + for name, (what, edits, prop) in MUTANTS.items(): + broken = spec + for old, new in edits: + if old not in broken: + print("ERROR mutant %s: the model text to break was not found (model changed?)" % name) + return 2 + broken = broken.replace(old, new, 1) + work = tempfile.mkdtemp(prefix="mutant-") + try: + with open(os.path.join(work, SPEC), "w") as f: + f.write(broken) + shutil.copy(os.path.join(HERE, CFG), work) + # reuse make_cfg/run_tlc against the broken copy + out = run_tlc_in(jar, work, prop, max_ops) + finally: + shutil.rmtree(work, ignore_errors=True) + if violated(out, prop): + print("CAUGHT %s: %s -> %s violated" % (name, what, prop)) + else: + print("MISSED %s: %s -> %s still holds" % (name, what, prop)) + bad = True + return 1 if bad else 0 + + +def run_tlc_in(jar, spec_dir, prop, max_ops): + return run_tlc(jar, spec_dir, prop, max_ops) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--mutants", action="store_true") + ap.add_argument("--drift", action="store_true") + ap.add_argument("--max-ops", type=int) + args = ap.parse_args() + + if args.drift: + return drift() + if shutil.which("java") is None: + print("java not found on PATH") + return 2 + jar = tla_jar() + code = drift() + code = 0 if code == 3 else code # drift is a warning here, the run still happens + result = check_properties(jar, args.max_ops) + if args.mutants: + result = max(result, check_mutants(jar, args.max_ops)) + return max(code, result) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/CHANGELOG.md b/CHANGELOG.md index 84ad589c..24df05ab 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ - Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling. - Fixed `ReschedulingTask.enable()` to throw `IllegalStateException` after the task has been closed. - Changed `ReschedulingTask.close()` to mark the task permanently closed before cleaning up resources. +- Changed `ReschedulingTask` to reconcile enabled state with the pending scheduled future after cancel or publish. --- diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index bdb2fe97..a9500115 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -286,10 +286,12 @@ private void closeRefreshScheduler(final boolean cancelled) throws InterruptedEx */ private boolean cancelScheduledTask() { ScheduledFuture taskToCancel = scheduledTask.getAndSet(null); + boolean cancelled = true; if (null != taskToCancel) { - return cancel(taskToCancel); + cancelled = cancel(taskToCancel); } - return true; + reconcileSchedule(); + return cancelled; } /** @@ -326,10 +328,31 @@ private void execute() { } catch (Exception e) { logger.error("[{}] Error during task execution.", name, e); } finally { + ScheduledFuture tracked = scheduledTask.get(); + if (isDone(tracked)) { + scheduledTask.compareAndSet(tracked, null); + } scheduleNext(); } } + /** + * If the task is enabled but has no pending {@link #scheduledTask}, transitions to {@link State#DISABLED}. + */ + private void reconcileSchedule() { + if (!isEnabled()) { + return; + } + ScheduledFuture tracked = scheduledTask.get(); + if (isDone(tracked)) { + scheduledTask.compareAndSet(tracked, null); + } + if (!isScheduled()) { + logger.debug("[{}] Enabled with no pending schedule; disabling.", name); + state.compareAndSet(State.ENABLED, State.DISABLED); + } + } + /** * Schedules the next execution based on the delay provided by the {@link #nextDelaySupplier}. */ @@ -359,6 +382,7 @@ private void scheduleNext() { logger.debug("[{}] New task was already scheduled, cancelling not needed.", name); } } + reconcileSchedule(); } else { logger.debug("[{}] Task was disabled during scheduling. Cancelling immediate orphan.", name); cancel(newTask); From c2adf61b4f7f4e025ae676da9a6b98c080bb96f6 Mon Sep 17 00:00:00 2001 From: raduking Date: Sun, 29 Nov 2026 03:41:22 +0200 Subject: [PATCH 09/13] Add `isNotScheduled`. --- CHANGELOG.md | 1 + .../morphix/lang/thread/ReschedulingTask.java | 17 +++++++++---- .../lang/thread/ReschedulingTaskTest.java | 25 +++++++++++++++++++ 3 files changed, 38 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 24df05ab..bb456391 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Fixed `ReschedulingTask.enable()` to throw `IllegalStateException` after the task has been closed. - Changed `ReschedulingTask.close()` to mark the task permanently closed before cleaning up resources. - Changed `ReschedulingTask` to reconcile enabled state with the pending scheduled future after cancel or publish. +- Added `ReschedulingTask.isNotScheduled()` to report whether there is no pending scheduled execution. --- diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index a9500115..0146dd2b 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -45,10 +45,7 @@ * any future executions and cancel any currently scheduled task. The task also provides a close method to clean up * resources when it is no longer needed. *

    - * Useful for token refreshers, cache refreshers, heartbeat mechanisms, etc. - *

      - *
    • TODO: add tests for the exact logging messages
    • - *
    + * Useful for token refreshers, cache refreshers, heart-beat mechanisms, etc. * * @author Radu Sebastian LAZIN */ @@ -347,7 +344,7 @@ private void reconcileSchedule() { if (isDone(tracked)) { scheduledTask.compareAndSet(tracked, null); } - if (!isScheduled()) { + if (isNotScheduled()) { logger.debug("[{}] Enabled with no pending schedule; disabling.", name); state.compareAndSet(State.ENABLED, State.DISABLED); } @@ -463,6 +460,16 @@ public boolean isScheduled() { return isNotDone(scheduledTask.get()); } + /** + * Returns true if there is no pending scheduled execution ({@link #scheduledTask} is null or already done). + * + * @return true if not scheduled, false if a future is still pending + * @see #isScheduled() + */ + public boolean isNotScheduled() { + return !isScheduled(); + } + /** * Returns true if the given task is currently scheduled (not null and not done), false otherwise. * diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index ea2d982a..3495a306 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -1623,6 +1623,30 @@ void shouldLogErrorWhenTaskExecutionFails() { verify(logger).error("[{}] Error during task execution.", TASK_NAME, exception); } + @Test + @SuppressWarnings("resource") + void shouldLogWhenReconcileDisablesBecauseNoPendingSchedule() throws Exception { + ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); + doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + doReturn(true).when(scheduledFuture).cancel(anyBoolean()); + LoggerAdapter logger = mock(LoggerAdapter.class); + + ReschedulingTask task = ReschedulingTask.builder() + .name(TASK_NAME) + .scheduler(ScopedResource.unmanaged(scheduledExecutor)) + .task(Runnables.doNothing()) + .nextDelay(() -> DELAY) + .logger(logger) + .build(); + task.enable(); + + Method cancelScheduledTaskMethod = Methods.getOneDeclared("cancelScheduledTask", ReschedulingTask.class); + Methods.IgnoreAccess.invoke(cancelScheduledTaskMethod, task); + + verify(logger).debug("[{}] Enabled with no pending schedule; disabling.", TASK_NAME); + } + } @Nested @@ -1746,6 +1770,7 @@ class CancellationOutcomeTests { private final ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); private final ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + @SuppressWarnings("resource") private ReschedulingTask managedTask(final LoggerAdapter logger) { doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); return ReschedulingTask.builder() From dc1185afa22ef688c6fc0c79f74e206e8d25e6cc Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Sun, 29 Nov 2026 03:45:22 +0200 Subject: [PATCH 10/13] Remove unneeded TLA files. --- .../ReschedulingTask.cfg | 15 - .../ReschedulingTask.tla | 340 ------------------ .../skills/verify-rescheduling-task/check.py | 256 ------------- 3 files changed, 611 deletions(-) delete mode 100644 .cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg delete mode 100644 .cursor/skills/verify-rescheduling-task/ReschedulingTask.tla delete mode 100755 .cursor/skills/verify-rescheduling-task/check.py diff --git a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg deleted file mode 100644 index a13e10f3..00000000 --- a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.cfg +++ /dev/null @@ -1,15 +0,0 @@ -SPECIFICATION Spec - -CONSTANTS - Clients = {c1, c2} - Workers = {w1, w2} - MaxOps = 2 - MaxFutures = 5 - -INVARIANTS - TypeOK - NoFutureLeftAfterDisable - AtMostOneFutureWhileEnabled - NextExecutionTrackedWhileEnabled - -CHECK_DEADLOCK FALSE diff --git a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla b/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla deleted file mode 100644 index 47d1e2f5..00000000 --- a/.cursor/skills/verify-rescheduling-task/ReschedulingTask.tla +++ /dev/null @@ -1,340 +0,0 @@ ----------------------------- MODULE ReschedulingTask ---------------------------- -(***************************************************************************) -(* Model of the enable / disable / close / reschedule protocol of *) -(* src/main/java/org/morphix/lang/thread/ReschedulingTask.java *) -(* *) -(* One step of this model is one atomic operation of the Java code: one *) -(* AtomicReference state transition, one read of isEnabled() or *) -(* isDisabled(), one ScheduledExecutorService.schedule(...) call, or one *) -(* Future.cancel(...) call (with the isDone check in front of it). The *) -(* label of each step names the Java method and statement it models. *) -(* *) -(* The scheduled futures are the ones the scheduler holds. A future that *) -(* is "pending" will run execute() on a scheduler thread when it fires. *) -(***************************************************************************) -EXTENDS Naturals, FiniteSets - -CONSTANTS - Clients, \* threads that call enable(), disable() and close() - Workers, \* scheduler threads that run execute() when a future fires - MaxOps, \* how many calls each client thread makes - MaxFutures \* how many scheduled futures the run may create - -NONE == 0 \* no future (a null scheduledTask) - -Threads == Clients \union Workers -FutureIds == 1..MaxFutures -LifecycleStates == {"disabled", "enabled", "closed"} - -VARIABLES - lifecycle, \* ReschedulingTask.State (DISABLED / ENABLED / CLOSED) - scheduledTask, \* ReschedulingTask.scheduledTask (NONE = null) - fut, \* state of every future the scheduler created - nextId, \* id of the next future schedule(...) creates - pc, \* where each thread is in the Java code - newTask, \* scheduleNext(): local variable newTask of each thread - victim, \* cancelScheduledTask(): local variable taskToCancel of each thread - opsLeft, \* calls each client thread may still make - last \* thread and Java statement of the latest step (trace readability only) - -vars == <> - -Pending == {f \in FutureIds : fut[f] = "pending"} - -IsEnabled == lifecycle = "enabled" - -\* No thread is inside enable(), disable(), close(), execute() or scheduleNext(). -Quiescent == \A t \in Threads : pc[t] = "idle" - -Init == - /\ lifecycle = "disabled" - /\ scheduledTask = NONE - /\ fut = [f \in FutureIds |-> "unused"] - /\ nextId = 1 - /\ pc = [t \in Threads |-> "idle"] - /\ newTask = [t \in Threads |-> NONE] - /\ victim = [t \in Threads |-> NONE] - /\ opsLeft = [c \in Clients |-> MaxOps] - /\ last = [thread |-> "-", step |-> "initial state"] - -\* Future.cancel: only a future that has not fired yet is stopped. -CancelFuture(f) == - fut' = IF f \in Pending THEN [fut EXCEPT ![f] = "cancelled"] ELSE fut - -GoTo(t, label) == pc' = [pc EXCEPT ![t] = label] - -Mark(t, what) == last' = [thread |-> t, step |-> what] - -(***************************************************************************) -(* Client calls *) -(***************************************************************************) - -CallEnable(c) == - /\ pc[c] = "idle" /\ opsLeft[c] > 0 - /\ Mark(c, "enable() is called") - /\ GoTo(c, "enable.cas") - /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] - /\ UNCHANGED <> - -CallDisable(c) == - /\ pc[c] = "idle" /\ opsLeft[c] > 0 - /\ Mark(c, "disable() is called") - /\ GoTo(c, "disable.cas") - /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] - /\ UNCHANGED <> - -CallClose(c) == - /\ pc[c] = "idle" /\ opsLeft[c] > 0 - /\ Mark(c, "close() is called") - /\ GoTo(c, "close.set") - /\ opsLeft' = [opsLeft EXCEPT ![c] = @ - 1] - /\ UNCHANGED <> - -(***************************************************************************) -(* enable(): state.compareAndExchange(DISABLED, ENABLED), then execute() *) -(***************************************************************************) - -EnableCas(c) == - /\ pc[c] = "enable.cas" - /\ Mark(c, "enable(): state.compareAndExchange(DISABLED, ENABLED)") - /\ IF lifecycle = "disabled" - THEN /\ lifecycle' = "enabled" - /\ GoTo(c, "execute.check") - ELSE /\ lifecycle' = lifecycle - /\ GoTo(c, "idle") - /\ UNCHANGED <> - -(***************************************************************************) -(* disable(): state.compareAndSet(ENABLED, DISABLED), cancelScheduledTask()*) -(* close(): state.set(CLOSED), then cancelScheduledTask() *) -(***************************************************************************) - -DisableCas(c) == - /\ pc[c] = "disable.cas" - /\ Mark(c, "disable(): state.compareAndSet(ENABLED, DISABLED)") - /\ IF lifecycle = "enabled" - THEN /\ lifecycle' = "disabled" - /\ GoTo(c, "cancelScheduled.take") - ELSE /\ lifecycle' = lifecycle - /\ GoTo(c, "idle") - /\ UNCHANGED <> - -CloseSet(c) == - /\ pc[c] = "close.set" - /\ Mark(c, "close(): state.set(CLOSED)") - /\ lifecycle' = "closed" - /\ GoTo(c, "cancelScheduled.take") - /\ UNCHANGED <> - -\* cancelScheduledTask(): scheduledTask.getAndSet(null) -CancelScheduledTake(c) == - /\ pc[c] = "cancelScheduled.take" - /\ Mark(c, "cancelScheduledTask(): scheduledTask.getAndSet(null)") - /\ victim' = [victim EXCEPT ![c] = scheduledTask] - /\ scheduledTask' = NONE - /\ GoTo(c, IF scheduledTask = NONE THEN "cancelScheduled.ensure" ELSE "cancelScheduled.cancel") - /\ UNCHANGED <> - -\* cancelScheduledTask(): cancel(taskToCancel) -CancelScheduledCancel(c) == - /\ pc[c] = "cancelScheduled.cancel" - /\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)") - /\ CancelFuture(victim[c]) - /\ GoTo(c, "cancelScheduled.ensure") - /\ UNCHANGED <> - -CancelScheduledEnsure(c) == - /\ pc[c] = "cancelScheduled.ensure" - /\ Mark(c, "cancelScheduledTask(): reconcileSchedule()") - /\ IF /\ IsEnabled - /\ ~(scheduledTask \in Pending) - THEN /\ lifecycle' = "disabled" - ELSE /\ lifecycle' = lifecycle - /\ GoTo(c, "idle") - /\ UNCHANGED <> - -(***************************************************************************) -(* Scheduler: a pending future fires and its execute() runs on a worker *) -(***************************************************************************) - -Fire(w, f) == - /\ pc[w] = "idle" /\ f \in Pending - /\ Mark(w, "the scheduler fires a pending future: execute() starts on a worker") - /\ fut' = [fut EXCEPT ![f] = "fired"] - /\ scheduledTask' = IF scheduledTask = f THEN NONE ELSE scheduledTask - /\ GoTo(w, "execute.check") - /\ UNCHANGED <> - -(***************************************************************************) -(* execute() *) -(***************************************************************************) - -\* if (isDisabled()) { return; } -ExecuteCheck(t) == - /\ pc[t] = "execute.check" - /\ Mark(t, "execute(): if (isDisabled())") - /\ GoTo(t, IF IsEnabled THEN "execute.run" ELSE "idle") - /\ UNCHANGED <> - -\* try { refreshTask } catch (...) { } finally { scheduleNext(); } -ExecuteRun(t) == - /\ pc[t] = "execute.run" - /\ Mark(t, "execute(): refreshTask runs") - /\ GoTo(t, "execute.dropDone") - /\ UNCHANGED <> - -ExecuteDropDone(t) == - /\ pc[t] = "execute.dropDone" - /\ Mark(t, "execute(): clear done scheduledTask before scheduleNext") - /\ scheduledTask' = IF /\ scheduledTask # NONE - /\ fut[scheduledTask] = "fired" - THEN NONE - ELSE scheduledTask - /\ GoTo(t, "next.check") - /\ UNCHANGED <> - -(***************************************************************************) -(* scheduleNext() *) -(***************************************************************************) - -\* if (isDisabled()) { return; } -NextCheck(t) == - /\ pc[t] = "next.check" - /\ Mark(t, "scheduleNext(): if (isDisabled())") - /\ GoTo(t, IF IsEnabled THEN "next.schedule" ELSE "idle") - /\ UNCHANGED <> - -\* ScheduledFuture newTask = executor.schedule(this::execute, ...); -NextSchedule(t) == - /\ pc[t] = "next.schedule" - /\ Mark(t, "scheduleNext(): executor.schedule(this::execute, ...)") - /\ nextId <= MaxFutures - /\ fut' = [fut EXCEPT ![nextId] = "pending"] - /\ newTask' = [newTask EXCEPT ![t] = nextId] - /\ nextId' = nextId + 1 - /\ GoTo(t, "next.checkEnabled") - /\ UNCHANGED <> - -\* if (isEnabled()) { ... } else { cancel(newTask); } -NextCheckEnabled(t) == - /\ pc[t] = "next.checkEnabled" - /\ Mark(t, "scheduleNext(): if (isEnabled())") - /\ GoTo(t, IF IsEnabled THEN "next.publish" ELSE "next.cancelImmediate") - /\ UNCHANGED <> - -\* scheduledTask.getAndSet(newTask); -NextPublish(t) == - /\ pc[t] = "next.publish" - /\ Mark(t, "scheduleNext(): scheduledTask.getAndSet(newTask)") - /\ LET prev == scheduledTask IN - /\ scheduledTask' = newTask[t] - /\ fut' = IF prev # NONE /\ prev # newTask[t] /\ prev \in Pending - THEN [fut EXCEPT ![prev] = "cancelled"] - ELSE fut - /\ GoTo(t, "next.recheck") - /\ UNCHANGED <> - -\* if (isDisabled()) { ... } -NextRecheck(t) == - /\ pc[t] = "next.recheck" - /\ Mark(t, "scheduleNext(): reconcileSchedule()") - /\ IF ~IsEnabled - THEN /\ GoTo(t, "next.take") - /\ UNCHANGED <> - ELSE IF scheduledTask \in Pending - THEN /\ GoTo(t, "idle") - /\ UNCHANGED <> - ELSE /\ lifecycle' = "disabled" - /\ scheduledTask' = NONE - /\ GoTo(t, "idle") - /\ UNCHANGED <> - -\* if (scheduledTask.compareAndSet(newTask, null)) { cancel(newTask); } -NextTake(t) == - /\ pc[t] = "next.take" - /\ Mark(t, "scheduleNext(): scheduledTask.compareAndSet(newTask, null)") - /\ IF scheduledTask = newTask[t] - THEN /\ scheduledTask' = NONE - /\ GoTo(t, "next.cancelOrphan") - ELSE /\ scheduledTask' = scheduledTask - /\ GoTo(t, "idle") - /\ UNCHANGED <> - -NextCancelOrphan(t) == - /\ pc[t] = "next.cancelOrphan" - /\ Mark(t, "scheduleNext(): cancel(newTask) for the orphan") - /\ CancelFuture(newTask[t]) - /\ GoTo(t, "idle") - /\ UNCHANGED <> - -NextCancelImmediate(t) == - /\ pc[t] = "next.cancelImmediate" - /\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing") - /\ CancelFuture(newTask[t]) - /\ GoTo(t, "idle") - /\ UNCHANGED <> - -\* Nothing is left to do (also used when MaxFutures is exhausted). -Done == - /\ \A c \in Clients : opsLeft[c] = 0 \/ pc[c] /= "idle" - /\ UNCHANGED vars - -Next == - \/ \E c \in Clients : CallEnable(c) - \/ \E c \in Clients : CallDisable(c) - \/ \E c \in Clients : CallClose(c) - \/ \E c \in Clients : EnableCas(c) - \/ \E c \in Clients : DisableCas(c) - \/ \E c \in Clients : CloseSet(c) - \/ \E c \in Clients : CancelScheduledTake(c) - \/ \E c \in Clients : CancelScheduledCancel(c) - \/ \E c \in Clients : CancelScheduledEnsure(c) - \/ \E w \in Workers, f \in FutureIds : Fire(w, f) - \/ \E t \in Threads : ExecuteCheck(t) - \/ \E t \in Threads : ExecuteRun(t) - \/ \E t \in Threads : ExecuteDropDone(t) - \/ \E t \in Threads : NextCheck(t) - \/ \E t \in Threads : NextSchedule(t) - \/ \E t \in Threads : NextCheckEnabled(t) - \/ \E t \in Threads : NextPublish(t) - \/ \E t \in Threads : NextRecheck(t) - \/ \E t \in Threads : NextTake(t) - \/ \E t \in Threads : NextCancelOrphan(t) - \/ \E t \in Threads : NextCancelImmediate(t) - -Spec == Init /\ [][Next]_vars - -(***************************************************************************) -(* Properties. Each one is checked only when no thread is inside one of *) -(* the methods above, because while a method runs the state is allowed to *) -(* be in between. *) -(***************************************************************************) - -TypeOK == - /\ lifecycle \in LifecycleStates - /\ scheduledTask \in {NONE} \union FutureIds - /\ fut \in [FutureIds -> {"unused", "pending", "cancelled", "fired"}] - /\ nextId \in 1..(MaxFutures + 1) - /\ pc \in [Threads -> {"idle", "enable.cas", "disable.cas", "close.set", - "cancelScheduled.take", "cancelScheduled.cancel", "cancelScheduled.ensure", - "execute.check", "execute.run", "execute.dropDone", "next.check", - "next.schedule", "next.checkEnabled", "next.publish", - "next.recheck", "next.take", "next.cancelOrphan", - "next.cancelImmediate"}] - -\* Once disable() or close() has returned and nothing else is running, no -\* future of this task is still waiting to fire. -NoFutureLeftAfterDisable == - (Quiescent /\ ~IsEnabled) => Pending = {} - -\* While the task is enabled and nothing else is running, at most one future -\* is waiting to fire: the task never runs two chains of executions. -AtMostOneFutureWhileEnabled == - (Quiescent /\ IsEnabled) => Cardinality(Pending) <= 1 - -\* While the task is enabled and nothing else is running, its next execution -\* is scheduled and scheduledTask points to it, so disable() can cancel it. -NextExecutionTrackedWhileEnabled == - (Quiescent /\ IsEnabled) => (scheduledTask \in Pending /\ Pending = {scheduledTask}) - -============================================================================= \ No newline at end of file diff --git a/.cursor/skills/verify-rescheduling-task/check.py b/.cursor/skills/verify-rescheduling-task/check.py deleted file mode 100755 index 16d96f30..00000000 --- a/.cursor/skills/verify-rescheduling-task/check.py +++ /dev/null @@ -1,256 +0,0 @@ -#!/usr/bin/env python3 -"""Runs the TLC model checker on ReschedulingTask.tla, one property at a time. - -Usage: - ./check.py check every property, report each one - ./check.py --mutants also prove that each property can fail: apply each broken variant - of the model and require that its property is reported as violated - ./check.py --drift only report whether the Java file changed since the sync commit - ./check.py --max-ops N change MaxOps (calls per client thread), default from the .cfg - -Exit code: 0 when every property holds or only known findings (known-findings.txt) fail, -1 when a property that is not a known finding fails or a mutant is not caught, -2 on a setup problem, 3 when the Java file changed since the sync commit (--drift only). - -Needs Java (any recent JDK) and, on the first run, network access to download tla2tools.jar. -""" -import argparse -import hashlib -import os -import re -import shutil -import subprocess -import sys -import tempfile -import urllib.request - -HERE = os.path.dirname(os.path.abspath(__file__)) -SPEC = "ReschedulingTask.tla" -CFG = "ReschedulingTask.cfg" -JAVA_FILE = "src/main/java/org/morphix/lang/thread/ReschedulingTask.java" - -TLA_VERSION = "v1.7.4" -TLA_URL = "https://github.com/tlaplus/tlaplus/releases/download/%s/tla2tools.jar" % TLA_VERSION -TLA_SHA256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88" - -PROPERTIES = [ - "NoFutureLeftAfterDisable", - "AtMostOneFutureWhileEnabled", - "NextExecutionTrackedWhileEnabled", -] - -# Broken variants of the model. Each one is the model of the Java code with one safeguard removed. -# name: (what was removed from the Java code, [(model text, broken model text)], property that must fail) -MUTANTS = { - "no-recheck-after-publish": ( - "scheduleNext() without the second `if (isDisabled())` block that cancels an orphaned task", - [('THEN /\\ GoTo(t, "next.take")', 'THEN /\\ GoTo(t, "idle")')], - "NoFutureLeftAfterDisable", - ), - "no-cancel-when-disabled-before-publish": ( - "scheduleNext() without `cancel(newTask)` in the branch where the task got disabled before publishing", - [('/\\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing")\n /\\ CancelFuture(newTask[t])', - '/\\ Mark(t, "scheduleNext(): cancel(newTask) after it was disabled before publishing")\n /\\ fut\' = fut')], - "NoFutureLeftAfterDisable", - ), - "disable-does-not-cancel": ( - "cancelScheduledTask() without `cancel(taskToCancel)`", - [('/\\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)")\n /\\ CancelFuture(victim[c])', - '/\\ Mark(c, "cancelScheduledTask(): cancel(taskToCancel)")\n /\\ fut\' = fut')], - "NoFutureLeftAfterDisable", - ), - "no-reconcile-after-publish": ( - "scheduleNext() without `reconcileSchedule`", - [('ELSE IF scheduledTask \\in Pending\n THEN /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>\n ELSE /\\ lifecycle\' = "disabled"\n /\\ scheduledTask\' = NONE\n /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>', - 'ELSE /\\ GoTo(t, "idle")\n /\\ UNCHANGED <>')], - "NextExecutionTrackedWhileEnabled", - ), -} - - -def read_sync_commit(): - with open(os.path.join(HERE, "SKILL.md")) as f: - m = re.search(r"^Sync commit: ([0-9a-f]{7,40})", f.read(), re.M) - return m.group(1) if m else None - - -def repo_root(): - return subprocess.check_output(["git", "rev-parse", "--show-toplevel"], cwd=HERE, text=True).strip() - - -def drift(): - sync = read_sync_commit() - if not sync: - print("No `Sync commit:` line in SKILL.md.") - return 2 - root = repo_root() - diff = subprocess.run(["git", "diff", "--stat", sync, "--", JAVA_FILE], cwd=root, text=True, capture_output=True) - if diff.returncode != 0: - print("git diff failed: " + diff.stderr.strip()) - return 2 - if diff.stdout.strip(): - print("DRIFT: %s changed since the sync commit %s:" % (JAVA_FILE, sync)) - print(diff.stdout.rstrip()) - print("Compare the changed methods with the model (see SKILL.md, section Coverage) before trusting a pass.") - return 3 - print("No drift: %s is unchanged since the sync commit %s." % (JAVA_FILE, sync)) - return 0 - - -def tla_jar(): - override = os.environ.get("TLA2TOOLS_JAR") - if override: - return override - cache = os.path.join(os.path.expanduser("~"), ".cache", "morphix", "tla2tools-%s.jar" % TLA_VERSION) - if not os.path.exists(cache): - os.makedirs(os.path.dirname(cache), exist_ok=True) - print("Downloading %s ..." % TLA_URL) - tmp = cache + ".part" - urllib.request.urlretrieve(TLA_URL, tmp) - with open(tmp, "rb") as f: - digest = hashlib.sha256(f.read()).hexdigest() - if digest != TLA_SHA256: - os.remove(tmp) - raise SystemExit("tla2tools.jar checksum mismatch: " + digest) - os.replace(tmp, cache) - return cache - - -def make_cfg(prop, max_ops, target): - with open(os.path.join(HERE, CFG)) as f: - cfg = f.read() - cfg = re.sub(r"INVARIANTS\n(?: \w+\n)+", "INVARIANTS\n TypeOK\n %s\n" % prop, cfg) - if max_ops is not None: - cfg = re.sub(r"MaxOps = \d+", "MaxOps = %d" % max_ops, cfg) - with open(target, "w") as f: - f.write(cfg) - - -def run_tlc(jar, spec_dir, prop, max_ops): - work = tempfile.mkdtemp(prefix="tlc-") - try: - shutil.copy(os.path.join(spec_dir, SPEC), os.path.join(work, SPEC)) - cfg = os.path.join(work, "run.cfg") - make_cfg(prop, max_ops, cfg) - out = subprocess.run( - ["java", "-XX:+UseParallelGC", "-cp", jar, "tlc2.TLC", "-workers", "auto", - "-metadir", os.path.join(work, "states"), "-config", "run.cfg", SPEC], - cwd=work, text=True, capture_output=True) - return out.stdout + out.stderr - finally: - shutil.rmtree(work, ignore_errors=True) - - -def summary(output): - m = re.search(r"(\d+) states generated, (\d+) distinct states found", output) - return "%s distinct states" % m.group(2) if m else "no state count" - - -def violated(output, prop): - return "Invariant %s is violated" % prop in output - - -def trace(output): - """Condensed counterexample: one line per step, then the final state.""" - blocks = re.split(r"^State \d+: ", output, flags=re.M)[1:] - lines = [] - last_block = "" - for i, block in enumerate(blocks, 1): - last_block = block - m = re.search(r'last = \[thread\s*\|->\s*"?([\w-]+)"?,\s*step\s*\|->\s*"([^"]*)"\]', block, re.S) - if m and m.group(1) != "-": - lines.append(" %2d. %-3s %s" % (i, m.group(1), m.group(2))) - enabled = re.search(r"enabled = (TRUE|FALSE)", last_block) - sched = re.search(r"scheduledTask = (\d+)", last_block) - fut = re.search(r"fut = <<([^>]*)>>", last_block) - if enabled and sched and fut: - states = [s.strip().strip('"') for s in fut.group(1).split(",")] - shown = ", ".join("future %d %s" % (i, s) for i, s in enumerate(states, 1) if s != "unused") - lines.append(" end state: enabled=%s, scheduledTask=%s, %s" % ( - enabled.group(1), "null" if sched.group(1) == "0" else "future " + sched.group(1), shown)) - return "\n".join(lines) - - -def known_findings(): - path = os.path.join(HERE, "known-findings.txt") - if not os.path.exists(path): - return set() - with open(path) as f: - return {l.split("#")[0].strip() for l in f if l.split("#")[0].strip()} - - -def check_properties(jar, max_ops): - known = known_findings() - bad = False - for prop in PROPERTIES: - out = run_tlc(jar, HERE, prop, max_ops) - if violated(out, prop): - tag = "KNOWN FINDING" if prop in known else "VIOLATED" - print("%s %s (%s)" % (tag, prop, summary(out))) - print(trace(out)) - bad = bad or prop not in known - elif "Model checking completed. No error has been found." in out: - note = " <-- listed in known-findings.txt but now holds: remove it from the list" if prop in known else "" - print("PASS %s (%s)%s" % (prop, summary(out), note)) - else: - print("ERROR %s: TLC did not finish. Last output:" % prop) - print("\n".join(out.splitlines()[-15:])) - return 2 - return 1 if bad else 0 - - -def check_mutants(jar, max_ops): - bad = False - with open(os.path.join(HERE, SPEC)) as f: - spec = f.read() - for name, (what, edits, prop) in MUTANTS.items(): - broken = spec - for old, new in edits: - if old not in broken: - print("ERROR mutant %s: the model text to break was not found (model changed?)" % name) - return 2 - broken = broken.replace(old, new, 1) - work = tempfile.mkdtemp(prefix="mutant-") - try: - with open(os.path.join(work, SPEC), "w") as f: - f.write(broken) - shutil.copy(os.path.join(HERE, CFG), work) - # reuse make_cfg/run_tlc against the broken copy - out = run_tlc_in(jar, work, prop, max_ops) - finally: - shutil.rmtree(work, ignore_errors=True) - if violated(out, prop): - print("CAUGHT %s: %s -> %s violated" % (name, what, prop)) - else: - print("MISSED %s: %s -> %s still holds" % (name, what, prop)) - bad = True - return 1 if bad else 0 - - -def run_tlc_in(jar, spec_dir, prop, max_ops): - return run_tlc(jar, spec_dir, prop, max_ops) - - -def main(): - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument("--mutants", action="store_true") - ap.add_argument("--drift", action="store_true") - ap.add_argument("--max-ops", type=int) - args = ap.parse_args() - - if args.drift: - return drift() - if shutil.which("java") is None: - print("java not found on PATH") - return 2 - jar = tla_jar() - code = drift() - code = 0 if code == 3 else code # drift is a warning here, the run still happens - result = check_properties(jar, args.max_ops) - if args.mutants: - result = max(result, check_mutants(jar, args.max_ops)) - return max(code, result) - - -if __name__ == "__main__": - sys.exit(main()) From e31fe71f6f76fa9b7394fe81ffe059d50f749342 Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Sun, 29 Nov 2026 03:55:41 +0200 Subject: [PATCH 11/13] Remove `reconcileSchedule`. --- CHANGELOG.md | 2 +- .../morphix/lang/thread/ReschedulingTask.java | 24 +----- .../lang/thread/ReschedulingTaskTest.java | 76 ++++++++++++++----- 3 files changed, 59 insertions(+), 43 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bb456391..a9d9ed98 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ - Added `Threads.safeJoin(Thread, Duration)` to join a thread with a timeout, with `InterruptedException` handling. - Fixed `ReschedulingTask.enable()` to throw `IllegalStateException` after the task has been closed. - Changed `ReschedulingTask.close()` to mark the task permanently closed before cleaning up resources. -- Changed `ReschedulingTask` to reconcile enabled state with the pending scheduled future after cancel or publish. +- Fixed `ReschedulingTask.disable()` to preserve a concurrent enable while cancellation finishes. - Added `ReschedulingTask.isNotScheduled()` to report whether there is no pending scheduled execution. --- diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index 0146dd2b..f0147395 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -283,12 +283,10 @@ private void closeRefreshScheduler(final boolean cancelled) throws InterruptedEx */ private boolean cancelScheduledTask() { ScheduledFuture taskToCancel = scheduledTask.getAndSet(null); - boolean cancelled = true; if (null != taskToCancel) { - cancelled = cancel(taskToCancel); + return cancel(taskToCancel); } - reconcileSchedule(); - return cancelled; + return true; } /** @@ -333,23 +331,6 @@ private void execute() { } } - /** - * If the task is enabled but has no pending {@link #scheduledTask}, transitions to {@link State#DISABLED}. - */ - private void reconcileSchedule() { - if (!isEnabled()) { - return; - } - ScheduledFuture tracked = scheduledTask.get(); - if (isDone(tracked)) { - scheduledTask.compareAndSet(tracked, null); - } - if (isNotScheduled()) { - logger.debug("[{}] Enabled with no pending schedule; disabling.", name); - state.compareAndSet(State.ENABLED, State.DISABLED); - } - } - /** * Schedules the next execution based on the delay provided by the {@link #nextDelaySupplier}. */ @@ -379,7 +360,6 @@ private void scheduleNext() { logger.debug("[{}] New task was already scheduled, cancelling not needed.", name); } } - reconcileSchedule(); } else { logger.debug("[{}] Task was disabled during scheduling. Cancelling immediate orphan.", name); cancel(newTask); diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index 3495a306..bf29536d 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -598,10 +598,12 @@ void shouldReportScheduledState() throws InterruptedException { .build(); assertThat(task.isScheduled(), is(false)); + assertThat(task.isNotScheduled(), is(true)); task.enable(); assertThat(task.isScheduled(), is(true)); + assertThat(task.isNotScheduled(), is(false)); latch.await(1, TimeUnit.SECONDS); @@ -610,6 +612,7 @@ void shouldReportScheduledState() throws InterruptedException { task.disable(); assertThat(task.isScheduled(), is(false)); + assertThat(task.isNotScheduled(), is(true)); } @Test @@ -1623,35 +1626,68 @@ void shouldLogErrorWhenTaskExecutionFails() { verify(logger).error("[{}] Error during task execution.", TASK_NAME, exception); } + } + + @Nested + class ConcurrentSchedulingTests { + @Test @SuppressWarnings("resource") - void shouldLogWhenReconcileDisablesBecauseNoPendingSchedule() throws Exception { - ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); + void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws Exception { + CountDownLatch cancellationStarted = new CountDownLatch(1); + CountDownLatch finishCancellation = new CountDownLatch(1); + CountDownLatch refreshStarted = new CountDownLatch(1); + CountDownLatch finishRefresh = new CountDownLatch(1); ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); - doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); - doReturn(true).when(scheduledFuture).cancel(anyBoolean()); - LoggerAdapter logger = mock(LoggerAdapter.class); - + ScheduledFuture firstFuture = mock(ScheduledFuture.class); + ScheduledFuture nextFuture = mock(ScheduledFuture.class); + doReturn(firstFuture).doReturn(nextFuture).when(scheduledExecutor) + .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + doAnswer(invocation -> { + cancellationStarted.countDown(); + assertThat(finishCancellation.await(5, TimeUnit.SECONDS), is(true)); + return true; + }).when(firstFuture).cancel(anyBoolean()); + AtomicInteger executions = new AtomicInteger(); + Runnable refresh = mock(Runnable.class); + doAnswer(invocation -> { + if (executions.incrementAndGet() == 2) { + refreshStarted.countDown(); + assertThat(finishRefresh.await(5, TimeUnit.SECONDS), is(true)); + } + return null; + }).when(refresh).run(); ReschedulingTask task = ReschedulingTask.builder() - .name(TASK_NAME) .scheduler(ScopedResource.unmanaged(scheduledExecutor)) - .task(Runnables.doNothing()) - .nextDelay(() -> DELAY) - .logger(logger) + .task(refresh) + .nextDelay(Duration.ofHours(1)) .build(); - task.enable(); - - Method cancelScheduledTaskMethod = Methods.getOneDeclared("cancelScheduledTask", ReschedulingTask.class); - Methods.IgnoreAccess.invoke(cancelScheduledTaskMethod, task); - verify(logger).debug("[{}] Enabled with no pending schedule; disabling.", TASK_NAME); + try (task; var workers = Executors.newVirtualThreadPerTaskExecutor()) { + try { + task.enable(); + Future disabling = workers.submit(task::disable); + assertThat(cancellationStarted.await(5, TimeUnit.SECONDS), is(true)); + Future enabling = workers.submit(task::enable); + assertThat(refreshStarted.await(5, TimeUnit.SECONDS), is(true)); + + // Finish the earlier disable while the new enable is still executing its initial refresh. + finishCancellation.countDown(); + assertThat(disabling.get(5, TimeUnit.SECONDS), is(true)); + finishRefresh.countDown(); + assertThat(enabling.get(5, TimeUnit.SECONDS), is(true)); + + assertThat(task.isEnabled(), is(true)); + assertThat(task.isScheduled(), is(true)); + verify(scheduledExecutor, times(2)).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + verify(nextFuture, never()).cancel(anyBoolean()); + } finally { + finishCancellation.countDown(); + finishRefresh.countDown(); + } + } } - } - - @Nested - class ConcurrentSchedulingTests { - @Test @SuppressWarnings("resource") void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending() throws Exception { From 075b2e9127fff79823f4fb32faecfba89891e94d Mon Sep 17 00:00:00 2001 From: raduking Date: Sun, 29 Nov 2026 04:09:45 +0200 Subject: [PATCH 12/13] Updated JavaDoc. --- src/main/java/org/morphix/lang/thread/ReschedulingTask.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java index f0147395..a540dcdf 100644 --- a/src/main/java/org/morphix/lang/thread/ReschedulingTask.java +++ b/src/main/java/org/morphix/lang/thread/ReschedulingTask.java @@ -45,6 +45,10 @@ * any future executions and cancel any currently scheduled task. The task also provides a close method to clean up * resources when it is no longer needed. *

    + * Whether the task is enabled and whether a scheduler future is still pending are separate concerns. The task may be + * enabled with no pending future while the initial refresh runs on the thread that called {@link #enable()}, or after a + * scheduled run has finished and the tracked future reference has been cleared. + *

    * Useful for token refreshers, cache refreshers, heart-beat mechanisms, etc. * * @author Radu Sebastian LAZIN @@ -62,7 +66,7 @@ private enum State { DISABLED, /** - * The task is active and can execute and reschedule itself. + * The task is active and can execute and reschedule itself. Does not imply a pending scheduled future. */ ENABLED, From 109c2aca7bbb8fcab88f8fad2d44041df9a2051d Mon Sep 17 00:00:00 2001 From: Radu Sebastian LAZIN Date: Sun, 29 Nov 2026 04:13:07 +0200 Subject: [PATCH 13/13] Concurrent scheduling tests. --- .../morphix/lang/thread/ReschedulingTaskTest.java | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java index bf29536d..0c91a1f6 100644 --- a/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java +++ b/src/test/java/org/morphix/lang/thread/ReschedulingTaskTest.java @@ -1433,7 +1433,7 @@ void shouldLogWhenCancellingScheduledTask() { @Test @SuppressWarnings("resource") - void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() throws Exception { + void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() { ScheduledFuture scheduledFuture = mock(ScheduledFuture.class); ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); doReturn(scheduledFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); @@ -1455,7 +1455,7 @@ void shouldLogScheduledNewTaskWhenNextExecutionIsScheduled() throws Exception { @Test @SuppressWarnings("resource") - void shouldLogWhenReplacingPreviouslyScheduledTaskWithNewOne() throws Exception { + void shouldLogWhenReplacingPreviouslyScheduledTaskWithNewOne() { ScheduledFuture future1 = mock(ScheduledFuture.class); ScheduledFuture future2 = mock(ScheduledFuture.class); doReturn(true).when(future1).cancel(anyBoolean()); @@ -1638,11 +1638,11 @@ void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws CountDownLatch finishCancellation = new CountDownLatch(1); CountDownLatch refreshStarted = new CountDownLatch(1); CountDownLatch finishRefresh = new CountDownLatch(1); + ScheduledExecutorService scheduledExecutor = mock(ScheduledExecutorService.class); ScheduledFuture firstFuture = mock(ScheduledFuture.class); ScheduledFuture nextFuture = mock(ScheduledFuture.class); - doReturn(firstFuture).doReturn(nextFuture).when(scheduledExecutor) - .schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); + doReturn(firstFuture).doReturn(nextFuture).when(scheduledExecutor).schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)); doAnswer(invocation -> { cancellationStarted.countDown(); assertThat(finishCancellation.await(5, TimeUnit.SECONDS), is(true)); @@ -1657,6 +1657,7 @@ void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws } return null; }).when(refresh).run(); + ReschedulingTask task = ReschedulingTask.builder() .scheduler(ScopedResource.unmanaged(scheduledExecutor)) .task(refresh) @@ -1671,7 +1672,7 @@ void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws Future enabling = workers.submit(task::enable); assertThat(refreshStarted.await(5, TimeUnit.SECONDS), is(true)); - // Finish the earlier disable while the new enable is still executing its initial refresh. + // finish the earlier disable while the new enable is still executing its initial refresh finishCancellation.countDown(); assertThat(disabling.get(5, TimeUnit.SECONDS), is(true)); finishRefresh.countDown(); @@ -1690,7 +1691,7 @@ void shouldKeepConcurrentEnableWhenPreviousDisableFinishesCancellation() throws @Test @SuppressWarnings("resource") - void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending() throws Exception { + void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending() { ScheduledFuture future1 = mock(ScheduledFuture.class); ScheduledFuture future2 = mock(ScheduledFuture.class); doReturn(true).when(future1).cancel(anyBoolean()); @@ -1717,7 +1718,7 @@ void shouldCancelPreviouslyPublishedFutureWhenReschedulingWhileAnotherIsPending( @Test @SuppressWarnings("resource") - void shouldNotCancelScheduledTaskWhenReplacingWithTheSameFutureReference() throws Exception { + void shouldNotCancelScheduledTaskWhenReplacingWithTheSameFutureReference() { ScheduledFuture future = mock(ScheduledFuture.class); ScheduledExecutorService mockExecutor = mock(ScheduledExecutorService.class); doReturn(future).when(mockExecutor).schedule(any(Runnable.class), anyLong(), any());