fix(scheduler): keep a schedule's last fire across a restart (#8928)

With persistence on, schedules survived a restart but the dispatcher's record of when each last fired lived in memory, so a one-time at() schedule fired again and every rate and cron schedule fired an immediate catch-up. The last fire is now stored with the schedule and never returned by the API. The dispatcher records it under the same lock as UpdateSchedule, DeleteSchedule and DeleteScheduleGroup, skipping a schedule deleted or recreated meanwhile, and UpdateSchedule keeps it. A one-time schedule fires once its time is due unless it has fired since, so an update to a later time re-arms it; rate and cron schedules count from the stored fire.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-11-18 21:25:47 -04:00
1 parent fa965882ca
commit 6ea09ee520
6 files changed
+220 -26

No files matched your search

@@ -135,6 +135,70 @@ class ScheduleDispatcherTest {
verify(invoker, times(1)).invoke(eq(s), any(), any(), anyInt());
}
// Catches: a restart firing a one-time schedule again, because whether it had fired lived only
// in the dispatcher's memory. A new dispatcher stands in for the restarted process.
@Test
void anAtScheduleStoredAsFiredDoesNotFireAgainAfterARestart() {
Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
s.setLastFiredAt(Instant.parse("2026-04-21T09:18:00Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T10:00:00Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
}
@Test
void anAtScheduleUpdatedToALaterTimeFiresAgainAtThatTime() {
Schedule s = newSchedule("at1", "at(2026-04-21T11:00:00)", "ENABLED");
s.setLastFiredAt(Instant.parse("2026-04-21T09:18:00Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T10:59:50Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
dispatcher.tick(Instant.parse("2026-04-21T11:00:00Z"));
verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T11:00:00Z")), any(), anyInt());
}
// Catches: every rate schedule firing an immediate catch-up after a restart, since its next fire
// fell back to its creation date when the last fire was forgotten.
@Test
void aRateScheduleResumesOneIntervalAfterItsStoredLastFire() {
Schedule s = newSchedule("r1", "rate(1 hour)", "ENABLED");
s.setLastFiredAt(Instant.parse("2026-04-21T12:00:00Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T12:30:00Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
dispatcher.tick(Instant.parse("2026-04-21T13:00:00Z"));
verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T13:00:00Z")), any(), anyInt());
}
@Test
void aCronScheduleResumesAtTheNextOccurrenceAfterItsStoredLastFire() {
Schedule s = newSchedule("c1", "cron(0 * * * ? *)", "ENABLED");
s.setLastFiredAt(Instant.parse("2026-04-21T12:00:05Z"));
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T12:30:00Z"));
verify(invoker, never()).invoke(any(), any(), any(), anyInt());
dispatcher.tick(Instant.parse("2026-04-21T13:00:00Z"));
verify(invoker, times(1)).invoke(eq(s), eq(Instant.parse("2026-04-21T13:00:00Z")), any(), anyInt());
}
@Test
void aFireIsRecordedInTheStoredSchedule() {
Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
when(schedulerService.listAllSchedules()).thenReturn(List.of(s));
dispatcher.tick(Instant.parse("2026-04-21T09:18:00Z"));
verify(schedulerService).recordFire(eq(s), any(), eq(Instant.parse("2026-04-21T09:18:00Z")));
}
@Test
void deletesAtScheduleWhenActionAfterCompletionIsDelete() {
Schedule s = newSchedule("at1", "at(2026-04-21T09:17:54)", "ENABLED");
@@ -1,10 +1,12 @@
package io.floci.aws.services.scheduler;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.PaginatedResult;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.PersistentStorage;
import io.floci.aws.services.scheduler.model.DeadLetterConfig;
import io.floci.aws.services.scheduler.model.FlexibleTimeWindow;
import io.floci.aws.services.scheduler.model.RetryPolicy;
@@ -14,10 +16,14 @@ import io.floci.aws.services.scheduler.model.ScheduleRequest;
import io.floci.aws.services.scheduler.model.Target;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.nio.file.Path;
import java.time.Instant;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static org.junit.jupiter.api.Assertions.*;
@@ -48,6 +54,107 @@ class SchedulerServiceTest {
}
private Schedule createRateSchedule(SchedulerService schedulers, String name) {
return schedulers.createSchedule(newRequest(name, null, "rate(1 hour)", new FlexibleTimeWindow("OFF", null),
new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
}
@Test
void aRecordedFireIsKeptByAnUpdate() {
Schedule created = createRateSchedule(service, "fired");
Instant firedAt = Instant.parse("2026-04-21T12:00:00Z");
service.recordFire(created, REGION, firedAt);
service.updateSchedule(newRequest("fired", null, "rate(2 hours)", new FlexibleTimeWindow("OFF", null),
new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
assertEquals(firedAt, service.getSchedule("fired", null, REGION).getLastFiredAt());
}
// Catches: the dispatcher's record of a fire bringing back a schedule deleted while it fired, or
// marking a new schedule created under the same name as already fired.
@Test
void aFireIsNotRecordedOnADeletedOrRecreatedSchedule() {
Schedule created = createRateSchedule(service, "gone");
service.deleteSchedule("gone", null, REGION);
service.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z"));
assertThrows(AwsException.class, () -> service.getSchedule("gone", null, REGION));
Schedule recreated = createRateSchedule(service, "gone");
created.setCreationDate(recreated.getCreationDate().minusSeconds(60));
service.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z"));
assertNull(service.getSchedule("gone", null, REGION).getLastFiredAt());
}
// Catches: a fire recorded while a group delete cascades through its schedules writing one back,
// so it lived on in a deleted group and kept firing. The delete holds the lock until it is done.
@Test
void aFireIsNotRecordedWhileItsGroupIsBeingDeleted() throws Exception {
CountDownLatch deleting = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
InMemoryStorage<String, Schedule> schedules = new InMemoryStorage<>() {
@Override
public void delete(String key) {
deleting.countDown();
try {
release.await(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
super.delete(key);
}
};
SchedulerService schedulers = new SchedulerService(new InMemoryStorage<>(), schedules,
new RegionResolver(REGION, "000000000000"));
schedulers.createScheduleGroup("team", Map.of(), REGION);
Schedule created = schedulers.createSchedule(newRequest("in-group", "team", "rate(1 hour)",
new FlexibleTimeWindow("OFF", null),
new Target("arn:t", "arn:aws:iam::000000000000:role/r", null, null)), REGION);
Thread groupDelete = Thread.ofPlatform().start(() -> schedulers.deleteScheduleGroup("team", REGION));
assertTrue(deleting.await(5, TimeUnit.SECONDS), "the cascade should reach the schedule");
Thread fire = Thread.ofPlatform().start(
() -> schedulers.recordFire(created, REGION, Instant.parse("2026-04-21T12:00:00Z")));
// Without the lock the fire runs to completion here instead of parking on the service's monitor.
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5);
while (fire.getState() != Thread.State.BLOCKED && fire.isAlive() && System.nanoTime() < deadline) {
Thread.sleep(5);
}
assertEquals(Thread.State.BLOCKED, fire.getState(), "recording a fire should wait for the delete");
release.countDown();
groupDelete.join();
fire.join();
assertTrue(schedules.scan(key -> true).isEmpty(), "the deleted group's schedule must stay deleted");
}
// Catches BL-385 across a real restart: the last fire written to disk is there when the stores are
// read back, so the dispatcher neither re-fires a one-time schedule nor catches a recurring one up.
@Test
void aRecordedFireSurvivesAReloadFromDisk(@TempDir Path dir) {
Path groups = dir.resolve("scheduler-groups.json");
Path schedules = dir.resolve("scheduler-schedules.json");
SchedulerService before = new SchedulerService(
new PersistentStorage<>(groups, new TypeReference<Map<String, ScheduleGroup>>() { }),
new PersistentStorage<>(schedules, new TypeReference<Map<String, Schedule>>() { }),
new RegionResolver(REGION, "000000000000"));
Schedule created = createRateSchedule(before, "durable");
Instant firedAt = Instant.parse("2026-04-21T12:00:00Z");
before.recordFire(created, REGION, firedAt);
PersistentStorage<String, ScheduleGroup> groupStore =
new PersistentStorage<>(groups, new TypeReference<Map<String, ScheduleGroup>>() { });
PersistentStorage<String, Schedule> scheduleStore =
new PersistentStorage<>(schedules, new TypeReference<Map<String, Schedule>>() { });
groupStore.load();
scheduleStore.load();
SchedulerService after = new SchedulerService(groupStore, scheduleStore,
new RegionResolver(REGION, "000000000000"));
assertEquals(firedAt, after.getSchedule("durable", null, REGION).getLastFiredAt());
}
/**
* Tagging and untagging put a new map in place of the group's, never changing the one a tag lookup may be
* copying, so a lookup during either reads one whole set.