Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(monitors): pin claim/complete SQL to UTC session, unstick PENDING (#17433)

Mark Salpeter1e3f13a6ad46
diff --git a/packages/shared/src/features/monitors/processor/processor.ts b/packages/shared/src/features/monitors/processor/processor.ts
index 561e6811f2..d0e967ddc0 100644
--- a/packages/shared/src/features/monitors/processor/processor.ts
+++ b/packages/shared/src/features/monitors/processor/processor.ts
@@ -204,12 +204,16 @@ export class MonitorProcessor {
completions: MonitorCompletion[];
}): Promise<void> {
if (args.completions.length === 0) return;
- await this.db.$executeRaw(
- buildCompleteQuery({
- projectId: args.projectId,
- completions: args.completions,
- }),
- );
+ await this.db.$transaction([
+ // tz-naive columns are read back as UTC by Prisma; pin the session so raw casts store UTC wall-clock
+ this.db.$executeRawUnsafe(`SET LOCAL TIME ZONE 'UTC'`),
+ this.db.$executeRaw(
+ buildCompleteQuery({
+ projectId: args.projectId,
+ completions: args.completions,
+ }),
+ ),
+ ]);
}
}
diff --git a/packages/shared/src/features/monitors/scheduler/scheduler.ts b/packages/shared/src/features/monitors/scheduler/scheduler.ts
index 0622ed6145..7e075ad422 100644
--- a/packages/shared/src/features/monitors/scheduler/scheduler.ts
+++ b/packages/shared/src/features/monitors/scheduler/scheduler.ts
@@ -36,10 +36,12 @@ export class MonitorScheduler {
* advances the schedule to the next run.
*/
async schedule(scheduledAt: Date): Promise<number> {
- const [, results] = await this.db.$transaction([
+ const [, , results] = await this.db.$transaction([
this.db.$executeRawUnsafe(
`SET LOCAL statement_timeout = ${MonitorScheduler.claimTimeoutMs}`,
),
+ // tz-naive columns are read back as UTC by Prisma; pin the session so raw casts store UTC wall-clock
+ this.db.$executeRawUnsafe(`SET LOCAL TIME ZONE 'UTC'`),
this.db.$queryRaw<MonitorBatchResult[]>(
buildScheduleQuery({
tick: scheduledAt,
diff --git a/worker/src/__tests__/monitorProcessor.test.ts b/worker/src/__tests__/monitorProcessor.test.ts
index e2c9dead19..0b8878ae36 100644
--- a/worker/src/__tests__/monitorProcessor.test.ts
+++ b/worker/src/__tests__/monitorProcessor.test.ts
@@ -220,7 +220,7 @@ function makeEvent(
};
}
-/** wrapDbToThrow returns a Proxy over `db` that rejects at the DB seam matching `stage`: claim intercepts `monitor.updateManyAndReturn`, complete intercepts `$executeRaw`. Lets the table inject failures without per-method seams on the processor. */
+/** wrapDbToThrow returns a Proxy over `db` that rejects at the DB seam matching `stage`: claim intercepts `monitor.updateManyAndReturn`, complete intercepts `$transaction`. Lets the table inject failures without per-method seams on the processor. */
function wrapDbToThrow(
db: PrismaClient,
stage: "claim" | "complete",
@@ -229,7 +229,7 @@ function wrapDbToThrow(
if (stage === "complete") {
return new Proxy(db, {
get(target, prop, _receiver) {
- if (prop === "$executeRaw") {
+ if (prop === "$transaction") {
return () => Promise.reject(new Error(message));
}
return Reflect.get(target, prop, target);
@@ -254,7 +254,7 @@ function wrapDbToThrow(
}) as PrismaClient;
}
-/** wrapDbPreemptBeforeComplete simulates another worker re-claiming between this worker's claim and complete: the first `$executeRaw` (the complete) first bumps `lastClaimedAt` on the project's monitors so the complete-side CAS owner key no longer matches and the update no-ops. */
+/** wrapDbPreemptBeforeComplete simulates another worker re-claiming between this worker's claim and complete: the complete `$transaction` first bumps `lastClaimedAt` on the project's monitors so the complete-side CAS owner key no longer matches and the update no-ops. */
function wrapDbPreemptBeforeComplete(
db: PrismaClient,
projectId: string,
@@ -263,7 +263,7 @@ function wrapDbPreemptBeforeComplete(
let preempted = false;
return new Proxy(db, {
get(target, prop, _receiver) {
- if (prop === "$executeRaw") {
+ if (prop === "$transaction") {
return async (...args: unknown[]) => {
if (!preempted) {
preempted = true;
@@ -272,7 +272,7 @@ function wrapDbPreemptBeforeComplete(
data: { lastClaimedAt: newClaimedAt },
});
}
- return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);
+ return (target.$transaction as (...a: unknown[]) => unknown)(...args);
};
}
return Reflect.get(target, prop, target);
@@ -280,7 +280,7 @@ function wrapDbPreemptBeforeComplete(
}) as PrismaClient;
}
-/** wrapDbPauseBeforeComplete simulates a user pausing between this worker's claim and complete: the first `$executeRaw` (the complete) first flips the project's monitors to PAUSED without touching `lastClaimedAt`, so the complete-side CAS owner key still matches. */
+/** wrapDbPauseBeforeComplete simulates a user pausing between this worker's claim and complete: the complete `$transaction` first flips the project's monitors to PAUSED without touching `lastClaimedAt`, so the complete-side CAS owner key still matches. */
function wrapDbPauseBeforeComplete(
db: PrismaClient,
projectId: string,
@@ -289,7 +289,7 @@ function wrapDbPauseBeforeComplete(
let paused = false;
return new Proxy(db, {
get(target, prop, _receiver) {
- if (prop === "$executeRaw") {
+ if (prop === "$transaction") {
return async (...args: unknown[]) => {
if (!paused) {
paused = true;
@@ -302,7 +302,7 @@ function wrapDbPauseBeforeComplete(
},
});
}
- return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);
+ return (target.$transaction as (...a: unknown[]) => unknown)(...args);
};
}
return Reflect.get(target, prop, target);
@@ -310,7 +310,7 @@ function wrapDbPauseBeforeComplete(
}) as PrismaClient;
}
-/** wrapDbRescueBeforeComplete simulates the scheduler TTL-rescuing this worker's stale run between claim and complete: the first `$executeRaw` (the complete) first advances `lastPublishedAt` on the project's monitors — leaving `lastClaimedAt` and `lastCompletedAt` untouched, exactly as buildScheduleQuery does — so the complete-side CAS owner key still matches on `lastClaimedAt` but the new publish-identity clause no-ops. */
+/** wrapDbRescueBeforeComplete simulates the scheduler TTL-rescuing this worker's stale run between claim and complete: the complete `$transaction` first advances `lastPublishedAt` on the project's monitors — leaving `lastClaimedAt` and `lastCompletedAt` untouched, exactly as buildScheduleQuery does — so the complete-side CAS owner key still matches on `lastClaimedAt` but the new publish-identity clause no-ops. */
function wrapDbRescueBeforeComplete(
db: PrismaClient,
projectId: string,
@@ -319,7 +319,7 @@ function wrapDbRescueBeforeComplete(
let rescued = false;
return new Proxy(db, {
get(target, prop, _receiver) {
- if (prop === "$executeRaw") {
+ if (prop === "$transaction") {
return async (...args: unknown[]) => {
if (!rescued) {
rescued = true;
@@ -328,7 +328,7 @@ function wrapDbRescueBeforeComplete(
data: { lastPublishedAt: newPublishedAt },
});
}
- return (target.$executeRaw as (...a: unknown[]) => unknown)(...args);
+ return (target.$transaction as (...a: unknown[]) => unknown)(...args);
};
}
return Reflect.get(target, prop, target);
diff --git a/worker/src/__tests__/monitorWorkerIntegration.test.ts b/worker/src/__tests__/monitorWorkerIntegration.test.ts
index 746a4b7ba6..37a36df890 100644
--- a/worker/src/__tests__/monitorWorkerIntegration.test.ts
+++ b/worker/src/__tests__/monitorWorkerIntegration.test.ts
@@ -14,7 +14,7 @@ import {
import { v4 } from "uuid";
import { setupServer } from "msw/node";
import { http, HttpResponse } from "msw";
-import { Prisma } from "@prisma/client";
+import { Prisma, PrismaClient } from "@prisma/client";
import { JobConfigState } from "@langfuse/shared";
import {
@@ -273,6 +273,75 @@ describe("monitor-alert e2e (scheduler → processor → dispatcher → webhook
});
});
+describe("monitor claim/complete under a non-UTC Postgres session TimeZone", () => {
+ let projectId: string;
+ let tzDb: PrismaClient;
+
+ beforeAll(() => {
+ const url = process.env.DATABASE_URL!;
+ const sep = url.includes("?") ? "&" : "?";
+ tzDb = new PrismaClient({
+ datasources: {
+ db: { url: `${url}${sep}options=-c%20timezone%3DAsia%2FShanghai` },
+ },
+ });
+ });
+
+ afterAll(async () => {
+ await tzDb.$disconnect();
+ });
+
+ beforeEach(async () => {
+ ({ projectId } = await createOrgProjectAndApiKey());
+ });
+
+ afterEach(async () => {
+ await prisma.monitor.deleteMany({ where: { projectId } });
+ });
+
+ it("claims and completes a due monitor instead of staying PENDING/UNKNOWN", async () => {
+ const session =
+ await tzDb.$queryRawUnsafe<Array<Record<string, string>>>(
+ "SHOW TIME ZONE",
+ );
+ expect(Object.values(session[0])[0]).toBe("Asia/Shanghai");
+
+ const monitorId = await seedMonitor({ projectId, alertThreshold: 100 });
+ const now = new Date();
+
+ const monitorQueueEvents: MonitorQueueEvent[] = [];
+ const scheduler = new MonitorScheduler({
+ schedulerId: 0,
+ totalSchedulers: 1,
+ db: tzDb,
+ publish: async (event) => {
+ monitorQueueEvents.push(MonitorQueueEventSchema.parse(event));
+ },
+ });
+ await scheduler.schedule(now);
+ const projectEvents = monitorQueueEvents.filter(
+ (e) => e.projectId === projectId,
+ );
+ expect(projectEvents).toHaveLength(1);
+
+ const processor = new MonitorProcessor(
+ tzDb,
+ async () => {},
+ async () => [{ count_count: 150 }],
+ );
+ await Promise.all(
+ projectEvents.map((event) => processor.process(event, now)),
+ );
+
+ const row = await tzDb.monitor.findUniqueOrThrow({
+ where: { id: monitorId },
+ });
+ expect(row.lastClaimedAt).not.toBeNull();
+ expect(row.lastCompletedAt).not.toBeNull();
+ expect(row.severity).not.toBe(MonitorSeveritySchema.enum.UNKNOWN);
+ });
+});
+
/** WebhookTestServer records webhook POSTs via MSW so tests can assert on them. */
class WebhookTestServer {
private server;
diff --git a/worker/src/scripts/retryMonitorBadQueryErrors.ts b/worker/src/scripts/retryMonitorBadQueryErrors.ts
index b829407e0d..67957d0c5f 100644
--- a/worker/src/scripts/retryMonitorBadQueryErrors.ts
+++ b/worker/src/scripts/retryMonitorBadQueryErrors.ts
@@ -37,18 +37,22 @@ async function retryMonitorBadQueryErrors(args: {
return;
}
- const reactivated = await prisma.$executeRaw`
- UPDATE monitors
- SET status = 'ACTIVE',
- severity = 'UNKNOWN',
- severity_changed_at = now(),
- next_run_at = now() + random() * make_interval(mins => ${args.jitterMinutes}::int),
- last_published_at = NULL,
- last_completed_at = NULL,
- last_claimed_at = NULL,
- alerted_at = NULL
- WHERE status = 'ERROR_BAD_QUERY'
- `;
+ const [, reactivated] = await prisma.$transaction([
+ // tz-naive columns are read back as UTC by Prisma; pin the session so now() stores UTC wall-clock
+ prisma.$executeRawUnsafe(`SET LOCAL TIME ZONE 'UTC'`),
+ prisma.$executeRaw`
+ UPDATE monitors
+ SET status = 'ACTIVE',
+ severity = 'UNKNOWN',
+ severity_changed_at = now(),
+ next_run_at = now() + random() * make_interval(mins => ${args.jitterMinutes}::int),
+ last_published_at = NULL,
+ last_completed_at = NULL,
+ last_claimed_at = NULL,
+ alerted_at = NULL
+ WHERE status = 'ERROR_BAD_QUERY'
+ `,
+ ]);
logger.info(
`retryMonitorBadQueryErrors: reactivated ${reactivated} monitors`,
);