Skip to content

Commit 6593991

Browse files
fix: keep monitor state from committing ahead of its task outcome (#30) (#41)
1 parent dafe23e commit 6593991

2 files changed

Lines changed: 720 additions & 18 deletions

File tree

‎apps/server/src/engine/service.ts‎

Lines changed: 107 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -271,7 +271,7 @@ export class AgentService {
271271
? "Paused. Resume when you're ready."
272272
: "",
273273
...(task.kind === "monitor" && action === "resume"
274-
? { state: { ...task.state, failures: 0, notice: null } }
274+
? { state: { ...task.state, failures: 0, notice: null, resumingMonitor: false } }
275275
: {}),
276276
},
277277
);
@@ -286,6 +286,8 @@ export class AgentService {
286286
{
287287
status: action === "cancel" ? "stopped" : action === "pause" ? "paused" : "active",
288288
nextCheckAt: date(),
289+
// Clearing the error fences out a failure reconcile that read the task before this.
290+
...(action === "resume" || action === "retry" ? { error: null } : {}),
289291
},
290292
);
291293
if (action === "cancel" && task.actionId) {
@@ -395,10 +397,26 @@ export class AgentService {
395397
return monitor;
396398
}
397399
private async activateMonitor(owner: string, monitor: Monitor) {
398-
if (monitor.status !== "active") return;
400+
if (monitor.status !== "active") return null;
399401
const task = await this.getTask(owner, monitor.taskId);
400-
if (task.status !== "paused" || !task.state.initializingMonitor) return;
401-
await this.db.compareAndSwap(
402+
if (task.status !== "paused") return null;
403+
if (task.state.resumingMonitor)
404+
return this.db.compareAndSwap(
405+
owner,
406+
"tasks",
407+
task.id,
408+
{ status: "paused", state: { resumingMonitor: true } },
409+
{
410+
status: "queued",
411+
nextRunAt: date(),
412+
leaseId: null,
413+
leaseUntil: null,
414+
error: null,
415+
state: { ...task.state, resumingMonitor: false, failures: 0, notice: null },
416+
},
417+
);
418+
if (!task.state.initializingMonitor) return null;
419+
return this.db.compareAndSwap(
402420
owner,
403421
"tasks",
404422
task.id,
@@ -414,18 +432,79 @@ export class AgentService {
414432
if (!monitor) throw new AppError("Monitor not found", 404);
415433
if (monitor.status === "stopped" && action !== "stop")
416434
throw new AppError("Create a new watch to restart this stopped monitor", 409);
417-
const status = action === "pause" ? "paused" : action === "stop" ? "stopped" : "active";
418-
const saved = await this.db.put(owner, "monitors", { ...monitor, status, nextCheckAt: date() });
419-
const task = await this.getTask(owner, monitor.taskId);
420-
if (action === "pause" || action === "stop")
435+
if (action === "pause" || action === "stop") {
436+
const status = action === "pause" ? "paused" : "stopped";
437+
const saved = await this.db.put(owner, "monitors", {
438+
...monitor,
439+
status,
440+
nextCheckAt: date(),
441+
});
442+
const task = await this.getTask(owner, monitor.taskId);
421443
await this.control(owner, task.id, action === "pause" ? "pause" : "cancel");
422-
else {
444+
return saved;
445+
}
446+
let monitorStatus = monitor.status;
447+
for (let attempt = 0; attempt < 2; attempt++) {
448+
const task = await this.getTask(owner, monitor.taskId);
449+
if (task.status === "cancelled") break;
450+
if (task.status === "paused") {
451+
// Mark the paused task before activating the monitor so no worker can claim it in between.
452+
const marked = await this.db.compareAndSwap(
453+
owner,
454+
"tasks",
455+
task.id,
456+
{ status: "paused", leaseId: task.leaseId ?? null },
457+
{ state: { ...task.state, resumingMonitor: true } },
458+
);
459+
if (!marked) break;
460+
const activated = await this.db.compareAndSwap<Monitor>(
461+
owner,
462+
"monitors",
463+
id,
464+
{ status: monitor.status },
465+
{ status: "active", nextCheckAt: date(), error: null },
466+
);
467+
const saved = activated ?? (await this.db.get<Monitor>(owner, "monitors", id));
468+
if (saved?.status === "active" && (await this.activateMonitor(owner, saved))) return saved;
469+
const unmarked = await this.db.compareAndSwap(
470+
owner,
471+
"tasks",
472+
task.id,
473+
{ status: "paused", state: { resumingMonitor: true } },
474+
{ state: { ...task.state, resumingMonitor: false } },
475+
);
476+
// Another request or maintenance may have finished this resume first.
477+
if (!unmarked && saved?.status === "active") {
478+
const latest = await this.getTask(owner, task.id);
479+
if (["queued", "running", "scheduled"].includes(latest.status)) return saved;
480+
}
481+
if (activated)
482+
await this.db.compareAndSwap(
483+
owner,
484+
"monitors",
485+
id,
486+
{ status: "active" },
487+
{ status: monitor.status, error: monitor.error ?? null },
488+
);
489+
break;
490+
}
491+
// Only activate the monitor we read, so a concurrent stop is never undone.
492+
const saved = await this.db.compareAndSwap<Monitor>(
493+
owner,
494+
"monitors",
495+
id,
496+
{ status: monitorStatus },
497+
{ status: "active", nextCheckAt: date() },
498+
);
499+
if (!saved) break;
500+
monitorStatus = "active";
423501
this.worker.abort(task.id);
424-
await this.db.compareAndSwap(
502+
const queued = await this.db.compareAndSwap(
425503
owner,
426504
"tasks",
427505
task.id,
428-
{ status: task.status, leaseId: task.leaseId ?? null },
506+
// updatedAt fences out a whole run finishing in between, which would move the baseline.
507+
{ status: task.status, leaseId: task.leaseId ?? null, updatedAt: task.updatedAt },
429508
{
430509
status: "queued",
431510
nextRunAt: date(),
@@ -435,8 +514,9 @@ export class AgentService {
435514
state: { ...task.state, failures: 0, notice: null },
436515
},
437516
);
517+
if (queued) return saved;
438518
}
439-
return saved;
519+
throw new AppError("The watch changed while updating. Try again.", 409);
440520
}
441521
async refreshIdeas(owner: string) {
442522
const w = await this.workspace.snapshot(owner);
@@ -683,11 +763,7 @@ export class AgentService {
683763
"monitors",
684764
String(task.input.monitorId),
685765
{ status: "active" },
686-
{
687-
error: detail,
688-
nextCheckAt,
689-
...(failures >= 5 ? { status: "paused" } : {}),
690-
},
766+
{ error: detail, nextCheckAt },
691767
);
692768
await context.event(
693769
"error",
@@ -701,6 +777,7 @@ export class AgentService {
701777
state: {
702778
...task.state,
703779
failures,
780+
resumingMonitor: false,
704781
notice: {
705782
title: "Watch needs attention",
706783
body: detail,
@@ -804,6 +881,15 @@ export class AgentService {
804881
.safeParse(task.state.notice);
805882
if ((task.status === "scheduled" || (task.status === "paused" && task.error)) && notice.success)
806883
await this.notify(owner, notice.data.title, notice.data.body, task.id, notice.data.key);
884+
// A watch pauses after repeated failures only once that task outcome has committed.
885+
if (task.kind === "monitor" && task.status === "paused" && task.error)
886+
await this.db.compareAndSwap(
887+
owner,
888+
"monitors",
889+
String(task.input.monitorId),
890+
{ status: "active", error: task.error },
891+
{ status: "paused" },
892+
);
807893
}
808894
private async document(
809895
owner: string,
@@ -925,7 +1011,8 @@ export class AgentService {
9251011
}
9261012
const text = observation.text.replace(/\s+/g, " ").trim();
9271013
const currentHash = hash(text);
928-
const previousHash = monitor.lastHash;
1014+
const previousHash =
1015+
typeof task.state.lastHash === "string" ? task.state.lastHash : monitor.lastHash;
9291016
const matched =
9301017
monitor.condition === "change"
9311018
? Boolean(previousHash && previousHash !== currentHash)
@@ -970,6 +1057,8 @@ export class AgentService {
9701057
state: {
9711058
...task.state,
9721059
sessionId: observation.sessionId,
1060+
lastHash: currentHash,
1061+
resumingMonitor: false,
9731062
matched,
9741063
failures: 0,
9751064
notice: shouldNotify

0 commit comments

Comments
 (0)