Skip to content

Commit 40c3f66

Browse files
feat(server): tasks wait while an update is ready to go in
With several tasks on a short timer no moment is left in which nothing works, so an update never gets its restart. A marker in the data directory now keeps tasks from starting by themselves until it ends, at most 20 minutes; due tasks run right after. Webhooks and run-now are not kept back. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent a6266d6 commit 40c3f66

3 files changed

Lines changed: 110 additions & 5 deletions

File tree

‎apps/server/src/scheduledTasks/ScheduledTaskService.ts‎

Lines changed: 27 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ import {
6060
supervisedSendsSinceUser,
6161
} from "./portfolioNudge.ts";
6262
import { recordDecision } from "../decisionLog.ts";
63+
import { currentUpdateHold } from "./updateHold.ts";
6364
import { isMissedFixedTimeRun, isSameSchedule, nextScheduledRunAt } from "./Schedule.ts";
6465
import {
6566
redactHeaders,
@@ -468,6 +469,29 @@ export const layer = Layer.effect(
468469
),
469470
Effect.orElseSucceed(() => false),
470471
);
472+
// While an update waits for a quiet moment no task starts by itself; due
473+
// times stay as they are, so the tasks run right after. Webhooks and
474+
// "run now" are not kept back.
475+
const updateHolding = yield* Ref.make(false);
476+
const isHeldForUpdate = Effect.gen(function* () {
477+
const endsAt = yield* currentUpdateHold;
478+
const holding = endsAt !== null;
479+
if ((yield* Ref.getAndSet(updateHolding, holding)) !== holding) {
480+
yield* recordDecision({
481+
kind: "update-hold",
482+
threadId: "-",
483+
outcome: holding ? "holding-tasks" : "released",
484+
...(endsAt === null
485+
? {}
486+
: { facts: { until: DateTime.formatIso(DateTime.makeUnsafe(endsAt)) } }),
487+
});
488+
}
489+
return holding;
490+
});
491+
const startsByItself = (taskId: string) =>
492+
Effect.gen(function* () {
493+
return !(yield* isHeldByPause(taskId)) && !(yield* isHeldForUpdate);
494+
});
471495
// Switching a held task on is the user resuming that one task. The pause
472496
// is over when the last task it still held has been switched on again,
473497
// or when the user resumes all at once.
@@ -1128,9 +1152,7 @@ export const layer = Layer.effect(
11281152
Effect.mapError((cause) => taskError("Could not list schedule tasks.", { cause })),
11291153
);
11301154
// A held task is left exactly as it is, due time and all, until it is resumed.
1131-
const free = yield* Effect.filter(tasks, (task) =>
1132-
isHeldByPause(task.id).pipe(Effect.map((held) => !held)),
1133-
);
1155+
const free = yield* Effect.filter(tasks, (task) => startsByItself(task.id));
11341156
const due = free.flatMap((task) =>
11351157
task.nextRunAt === null ? [] : [{ task, dueAt: DateTime.makeUnsafe(task.nextRunAt) }],
11361158
);
@@ -1290,7 +1312,7 @@ export const layer = Layer.effect(
12901312
Effect.gen(function* () {
12911313
const task = yield* decodeRow(row);
12921314
if (task.schedule.type !== "idle" || task.threadId === null) return;
1293-
if (yield* isHeldByPause(task.id)) return;
1315+
if (!(yield* startsByItself(task.id))) return;
12941316
// The thread whose silence starts the task: its own, or another
12951317
// one when the task chains this thread's work behind that one's.
12961318
const watchedThreadId = task.schedule.watchThreadId ?? ThreadId.make(task.threadId);
@@ -1381,7 +1403,7 @@ export const layer = Layer.effect(
13811403
Effect.gen(function* () {
13821404
const task = yield* decodeRow(row);
13831405
if (task.schedule.type !== "idle" || task.schedule.allOpenThreads !== true) return;
1384-
if (yield* isHeldByPause(task.id)) return;
1406+
if (!(yield* startsByItself(task.id))) return;
13851407
const schedule = task.schedule;
13861408
const now = yield* localNow;
13871409
const nowMs = DateTime.toEpochMillis(now);
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import { describe, expect, it } from "@effect/vitest";
2+
import * as DateTime from "effect/DateTime";
3+
4+
import { UPDATE_HOLD_MAX_MS, updateHoldEndsAt } from "./updateHold.ts";
5+
6+
const at = Date.parse("2026-10-12T10:00:00.000Z");
7+
const marker = (minutes: number) =>
8+
JSON.stringify({
9+
at: DateTime.formatIso(DateTime.makeUnsafe(at)),
10+
until: DateTime.formatIso(DateTime.makeUnsafe(at + minutes * 60_000)),
11+
});
12+
13+
describe("updateHoldEndsAt", () => {
14+
it("holds until the marker's own end", () => {
15+
expect(updateHoldEndsAt(marker(10), at + 60_000)).toBe(at + 10 * 60_000);
16+
expect(updateHoldEndsAt(marker(10), at + 10 * 60_000)).toBeNull();
17+
});
18+
19+
it("never holds longer than the cap, whatever the marker asks for", () => {
20+
expect(updateHoldEndsAt(marker(600), at + 60_000)).toBe(at + UPDATE_HOLD_MAX_MS);
21+
expect(updateHoldEndsAt(marker(600), at + UPDATE_HOLD_MAX_MS)).toBeNull();
22+
});
23+
24+
it("does not hold on a marker it cannot read or one from the future", () => {
25+
expect(updateHoldEndsAt("", at)).toBeNull();
26+
expect(updateHoldEndsAt("{", at)).toBeNull();
27+
expect(updateHoldEndsAt(JSON.stringify({ at: "soon", until: "later" }), at)).toBeNull();
28+
expect(updateHoldEndsAt(marker(10), at - 1)).toBeNull();
29+
});
30+
});
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/**
2+
* Lets an update in when tasks run on a timer around the clock.
3+
*
4+
* An update restarts the server only while no agent works. With several tasks
5+
* on a short timer there is no such moment. So whoever has an update ready
6+
* writes a marker into the data directory, and while it is valid no task
7+
* starts by itself: the turns under way finish, the server can be restarted,
8+
* and the tasks that were due run right after. The marker carries its own end
9+
* and is capped, so a forgotten one cannot keep tasks back.
10+
*
11+
* @module updateHold
12+
*/
13+
import * as Clock from "effect/Clock";
14+
import * as Effect from "effect/Effect";
15+
import * as FileSystem from "effect/FileSystem";
16+
import * as Option from "effect/Option";
17+
import * as Path from "effect/Path";
18+
import * as Schema from "effect/Schema";
19+
20+
import * as ServerConfig from "../config.ts";
21+
22+
export const UPDATE_HOLD_FILE_NAME = "update-pending.json";
23+
/** The longest a marker can keep tasks back, whatever it asks for. */
24+
export const UPDATE_HOLD_MAX_MS = 20 * 60_000;
25+
26+
const Marker = Schema.Struct({ at: Schema.String, until: Schema.String });
27+
const decodeMarker = Schema.decodeUnknownOption(Schema.fromJsonString(Marker));
28+
29+
/**
30+
* When the hold a marker asks for ends, in epoch milliseconds, or null when
31+
* it does not hold now: unreadable, over, or written in the future.
32+
*/
33+
export function updateHoldEndsAt(contents: string, nowMs: number): number | null {
34+
const marker = decodeMarker(contents);
35+
if (Option.isNone(marker)) return null;
36+
const at = Date.parse(marker.value.at);
37+
const until = Date.parse(marker.value.until);
38+
if (!Number.isFinite(at) || !Number.isFinite(until) || at > nowMs) return null;
39+
const endsAt = Math.min(until, at + UPDATE_HOLD_MAX_MS);
40+
return nowMs < endsAt ? endsAt : null;
41+
}
42+
43+
/** When the current update hold ends, or null without one. Missing services or file mean none. */
44+
export const currentUpdateHold = Effect.gen(function* () {
45+
const fileSystem = yield* Effect.serviceOption(FileSystem.FileSystem);
46+
const path = yield* Effect.serviceOption(Path.Path);
47+
const config = yield* Effect.serviceOption(ServerConfig.ServerConfig);
48+
if (Option.isNone(fileSystem) || Option.isNone(path) || Option.isNone(config)) return null;
49+
const contents = yield* fileSystem.value
50+
.readFileString(path.value.join(config.value.stateDir, UPDATE_HOLD_FILE_NAME))
51+
.pipe(Effect.orElseSucceed(() => ""));
52+
return contents === "" ? null : updateHoldEndsAt(contents, yield* Clock.currentTimeMillis);
53+
});

0 commit comments

Comments
 (0)