πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(monitors): Service & Schema (#13725)
Mark Salpeterc9274a20b7bd
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 60c7f657ea..e3390c958b 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -221,6 +221,43 @@ jobs:- name: run eslint-plugin testsrun: pnpm --filter @repo/eslint-plugin run test+ tests-shared:+ timeout-minutes: 15+ runs-on: blacksmith-4vcpu-ubuntu-2404+ needs:+ - pre-job+ if: needs.pre-job.outputs.should_skip != 'true'+ steps:+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ with:+ persist-credentials: false+ - uses: pnpm/action-setup@739bfe42ca9233c5e6aca07c1a25a9d34aca49b0 # v6.0.7+ with:+ version: 11.1.3+ - name: Use Node.js ${{ env.NODE_VERSION }} without cache+ if: env.CI_CACHE_ALLOWED != 'true'+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0+ with:+ node-version: ${{ env.NODE_VERSION }}+ package-manager-cache: false+ - name: Use Node.js ${{ env.NODE_VERSION }} with pnpm cache+ if: env.CI_CACHE_ALLOWED == 'true'+ uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # zizmor: ignore[cache-poisoning] shared test dependency cache only; no published artifacts are built from this cached state+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: "pnpm"+ cache-dependency-path: "pnpm-lock.yaml"+ - name: install dependencies+ run: |+ pnpm install+ - name: Load default env (for prisma generate)+ run: |+ cp .env.dev.example .env+ - name: generate prisma client+ run: pnpm --filter=shared run db:generate+ - name: run shared tests+ run: pnpm --filter @langfuse/shared run test+test-docker-build:timeout-minutes: 20runs-on: blacksmith-4vcpu-ubuntu-2404@@ -769,6 +806,7 @@ jobs:lint,prettier-check,tests-eslint-plugin,+ tests-shared,tests-web,tests-worker,test-worker-llm-connections,diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex d7f48d33d0..26b9e8b9b6 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -63,6 +63,7 @@"dev": "tsc --watch","lint": "eslint . --cache --cache-location dist/.eslintcache --max-warnings 0","lint:fix": "eslint . --cache --cache-location dist/.eslintcache --fix",+ "test": "vitest run","db:migrate": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma migrate dev","db:push": "DISABLE_ERD=false dotenv -e ../../.env -- npx prisma db push","db:reset": "dotenv -e ../../.env npx -- prisma migrate reset",@@ -145,7 +146,8 @@"prisma": "^6.19.3","ts-node": "^10.9.2","tsc-watch": "^6.2.0",- "typescript": "^5.7.2"+ "typescript": "^5.7.2",+ "vitest": "^4.1.4"},"peerDependencies": {"@types/react": "~19.2.14",diff --git a/packages/shared/prisma/migrations/20260521000000_monitor_severity_status_reorder_drop_message/migration.sql b/packages/shared/prisma/migrations/20260521000000_monitor_severity_status_reorder_drop_message/migration.sqlnew file mode 100644index 0000000000..db43f6f61e--- /dev/null+++ b/packages/shared/prisma/migrations/20260521000000_monitor_severity_status_reorder_drop_message/migration.sql@@ -0,0 +1,26 @@+-- AlterEnum: reorder MonitorSeverity so DESC sorts most-critical first+-- (ALERT, WARNING, OK, NO_DATA, UNKNOWN).+BEGIN;+CREATE TYPE "MonitorSeverity_new" AS ENUM ('UNKNOWN', 'NO_DATA', 'OK', 'WARNING', 'ALERT');+ALTER TABLE "monitors" ALTER COLUMN "severity" DROP DEFAULT;+ALTER TABLE "monitors" ALTER COLUMN "severity" TYPE "MonitorSeverity_new" USING ("severity"::text::"MonitorSeverity_new");+ALTER TYPE "MonitorSeverity" RENAME TO "MonitorSeverity_old";+ALTER TYPE "MonitorSeverity_new" RENAME TO "MonitorSeverity";+DROP TYPE "MonitorSeverity_old";+ALTER TABLE "monitors" ALTER COLUMN "severity" SET DEFAULT 'UNKNOWN';+COMMIT;++-- AlterEnum: reorder MonitorStatus so DESC sorts in attention-priority order+-- (ERROR_BAD_QUERY, ACTIVE, PAUSED).+BEGIN;+CREATE TYPE "MonitorStatus_new" AS ENUM ('PAUSED', 'ACTIVE', 'ERROR_BAD_QUERY');+ALTER TABLE "monitors" ALTER COLUMN "status" DROP DEFAULT;+ALTER TABLE "monitors" ALTER COLUMN "status" TYPE "MonitorStatus_new" USING ("status"::text::"MonitorStatus_new");+ALTER TYPE "MonitorStatus" RENAME TO "MonitorStatus_old";+ALTER TYPE "MonitorStatus_new" RENAME TO "MonitorStatus";+DROP TYPE "MonitorStatus_old";+ALTER TABLE "monitors" ALTER COLUMN "status" SET DEFAULT 'ACTIVE';+COMMIT;++-- AlterTable: drop the unused message column (templating removed for v1).+ALTER TABLE "monitors" DROP COLUMN "message";diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex 6e8d16a8d7..c67f638070 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -1597,16 +1597,16 @@ enum MonitorView {enum MonitorSeverity {UNKNOWN+ NO_DATAOKWARNINGALERT- NO_DATA}// Scheduler evaluates only ACTIVE; any other state is skipped.enum MonitorStatus {- ACTIVEPAUSED+ ACTIVEERROR_BAD_QUERY}@@ -1650,7 +1650,6 @@ model Monitor {// === Alerts ===name String- message String @default("")tags String[] @default([])alertedAt DateTime? @map("alerted_at")diff --git a/packages/shared/src/features/monitors/helpers.ts b/packages/shared/src/features/monitors/helpers.tsnew file mode 100644index 0000000000..fa979ccc9a--- /dev/null+++ b/packages/shared/src/features/monitors/helpers.ts@@ -0,0 +1,27 @@+/** helpers.ts contains small monitor-feature utilities that are intentionally+ * not re-exported from the package barrel. */++/**+ * SECOND is one second in milliseconds.+ */+export const SECOND = 1000n;++/**+ * MINUTE is one minute in milliseconds.+ */+export const MINUTE = 60n * SECOND;++/**+ * HOUR is one hour in milliseconds.+ */+export const HOUR = 60n * MINUTE;++/**+ * DAY is one day in milliseconds.+ */+export const DAY = 24n * HOUR;++/**+ * WEEK is one week in milliseconds.+ */+export const WEEK = 7n * DAY;diff --git a/packages/shared/src/features/monitors/index.ts b/packages/shared/src/features/monitors/index.tsnew file mode 100644index 0000000000..1dd7d465ab--- /dev/null+++ b/packages/shared/src/features/monitors/index.ts@@ -0,0 +1,6 @@+/** index.ts is the client-safe barrel for the monitors feature β domain+ * schemas, types, refinements, and standalone predicates. Server-only code+ * (the service, scheduler DTOs) is re-exported from `./server` instead. */+export * from "./types";+export * from "./isValidQuery";+export * from "./isValidThresholdOrder";diff --git a/packages/shared/src/features/monitors/isValidQuery.test.ts b/packages/shared/src/features/monitors/isValidQuery.test.tsnew file mode 100644index 0000000000..5549ffc34c--- /dev/null+++ b/packages/shared/src/features/monitors/isValidQuery.test.ts@@ -0,0 +1,234 @@+import { describe, it, expect } from "vitest";++import { isValidQuery } from "./isValidQuery";++describe("isValidQuery", () => {+ it("accepts a valid (view, measure, aggregation) tuple", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [],+ });+ expect(result.valid).toBe(true);+ });++ it("rejects an unknown measure for the view", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "bogus_measure", aggregation: "count" },+ filters: [],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("Invalid measure");+ expect(result.reason).toContain("bogus_measure");+ }+ });++ it("accepts a `metadata` filter column without checking the view's dimensions", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "stringObject",+ column: "metadata",+ key: "tenant",+ operator: "=",+ value: "acme",+ },+ ],+ });+ expect(result.valid).toBe(true);+ });++ it("rejects a filter column that isn't a dimension on the view", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "string",+ column: "not_a_dimension",+ operator: "=",+ value: "x",+ },+ ],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("Invalid filter column");+ expect(result.reason).toContain("not_a_dimension");+ }+ });++ it("rejects when the view itself is unknown", () => {+ // `getViewDeclaration` throws InvalidRequestError on an unknown view name.+ expect(() =>+ isValidQuery({+ view: "bogus" as never,+ metric: { measure: "count", aggregation: "count" },+ filters: [],+ }),+ ).toThrow(/View 'bogus' is not supported/);+ });++ it.each(["constructor", "toString", "hasOwnProperty", "__proto__"])(+ "rejects %s as a measure (does not walk the prototype chain)",+ (measure) => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure, aggregation: "count" },+ filters: [],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("Invalid measure");+ }+ },+ );++ it.each(["constructor", "toString", "hasOwnProperty", "__proto__"])(+ "rejects %s as a filter column (does not walk the prototype chain)",+ (column) => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [{ type: "string", column, operator: "=", value: "x" }],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("Invalid filter column");+ }+ },+ );++ it("rejects histogram aggregation (bucket array is not comparable to a scalar threshold)", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "histogram" },+ filters: [],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("histogram");+ expect(result.reason).toContain("not supported for monitors");+ }+ });++ it.each([+ {+ type: "stringOptions" as const,+ column: "environment",+ operator: "any of" as const,+ value: ["prod", "prod", "staging"],+ },+ {+ type: "arrayOptions" as const,+ column: "tags",+ operator: "all of" as const,+ value: ["a", "a"],+ },+ ])("rejects a $type filter with duplicate value entries", (filter) => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [filter],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("unique");+ expect(result.reason).toContain(filter.type);+ }+ });++ it("rejects a string filter on an array-typed dimension (tags is string[])", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ { type: "string", column: "tags", operator: "=", value: "foo" },+ ],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("tags");+ expect(result.reason).toContain("arrayOptions");+ }+ });++ it("rejects a stringOptions filter on an array-typed dimension (tags is string[])", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "stringOptions",+ column: "tags",+ operator: "any of",+ value: ["foo"],+ },+ ],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("tags");+ expect(result.reason).toContain("arrayOptions");+ }+ });++ it("accepts a stringOptions filter on a scalar string dimension", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "stringOptions",+ column: "environment",+ operator: "any of",+ value: ["production", "staging"],+ },+ ],+ });+ expect(result.valid).toBe(true);+ });++ it("accepts an arrayOptions filter on a string[] dimension", () => {+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "arrayOptions",+ column: "tags",+ operator: "all of",+ value: ["alpha", "beta"],+ },+ ],+ });+ expect(result.valid).toBe(true);+ });++ it("rejects a non-stringObject filter on the metadata column", () => {+ // queryBuilder requires metadata filters to be `type: "stringObject"`.+ // Without this, a `{type: "string", column: "metadata"}` filter would+ // parse cleanly here but fail at every scheduler tick downstream.+ const result = isValidQuery({+ view: "observations",+ metric: { measure: "count", aggregation: "count" },+ filters: [+ {+ type: "string",+ column: "metadata",+ operator: "=",+ value: "acme",+ },+ ],+ });+ expect(result.valid).toBe(false);+ if (!result.valid) {+ expect(result.reason).toContain("metadata");+ expect(result.reason).toContain("stringObject");+ }+ });+});diff --git a/packages/shared/src/features/monitors/isValidQuery.ts b/packages/shared/src/features/monitors/isValidQuery.tsnew file mode 100644index 0000000000..39bc3b1439--- /dev/null+++ b/packages/shared/src/features/monitors/isValidQuery.ts@@ -0,0 +1,113 @@+/** isValidQuery.ts checks that a Monitor's (view, metric, filters) tuple+ * resolves against the v2 view declaration in the query package. Consumed as+ * a zod `superRefine` from the Monitor input schemas in `./types`. */+import { type z } from "zod";++import { type singleFilter } from "../../interfaces/filters";+import { getViewDeclaration } from "../query/dataModel";+import {+ getValidAggregationsForMeasureType,+ type metric,+ type viewsV2,+} from "../query/types";++/**+ * isValidQuery ensures:+ * - The measure exists on the view's v2 declaration.+ * - The aggregation is compatible with the measure's declared type.+ * - Each filter column is either a declared dimension or the `metadata`+ * escape hatch.+ */+export function isValidQuery(input: {+ view: z.infer<typeof viewsV2>;+ metric: z.infer<typeof metric>;+ filters: z.infer<typeof singleFilter>[];+}): { valid: true } | { valid: false; reason: string } {+ const declaration = getViewDeclaration(input.view, "v2");++ if (!Object.hasOwn(declaration.measures, input.metric.measure)) {+ return {+ valid: false,+ reason:+ `Invalid measure "${input.metric.measure}" for view "${input.view}". ` ++ `Must be one of: ${Object.keys(declaration.measures).join(", ")}`,+ };+ }+ const measureDef = declaration.measures[input.metric.measure];++ const validAggs = getValidAggregationsForMeasureType(measureDef.type);+ if (!validAggs.some((a) => a === input.metric.aggregation)) {+ return {+ valid: false,+ reason:+ `Aggregation "${input.metric.aggregation}" is not valid for measure ` ++ `"${input.metric.measure}" (type: ${measureDef.type}). Valid: ${validAggs.join(", ")}`,+ };+ }++ // `histogram` returns a bucket-array (Array(Tuple(...))) at the ClickHouse+ // layer; monitor thresholds are scalars (`z.number()`) compared with+ // `gt`/`gte`/`lt`/`lte`/`eq`/`neq`. No defined comparison semantics β+ // reject at the input boundary rather than failing in the worker.+ if (input.metric.aggregation === "histogram") {+ return {+ valid: false,+ reason:+ `Aggregation "histogram" is not supported for monitors β it produces ` ++ `a bucket array, not a scalar value comparable to the threshold.`,+ };+ }++ for (const filter of input.filters) {+ if (filter.column === "metadata") {+ if (filter.type !== "stringObject") {+ return {+ valid: false,+ reason:+ `Filter on "metadata" must be type "stringObject" with a "key" property ` ++ `(got "${filter.type}"). queryBuilder rejects other metadata filter types.`,+ };+ }+ continue;+ }+ if (!Object.hasOwn(declaration.dimensions, filter.column)) {+ return {+ valid: false,+ reason:+ `Invalid filter column "${filter.column}" for view "${input.view}". ` ++ `Must be a dimension on the view or the special "metadata" column.`,+ };+ }+ // Array-typed dimensions (e.g. `tags`) require the `arrayOptions` filter+ // variant; queryBuilder rejects scalar filters on them. Fail fast at the+ // input boundary instead of letting the scheduler tick fail.+ const dimension = declaration.dimensions[filter.column];+ if (dimension.type === "string[]" && filter.type !== "arrayOptions") {+ return {+ valid: false,+ reason:+ `Filter on "${filter.column}" must be type "arrayOptions" β the dimension is an array ` ++ `(got "${filter.type}"). queryBuilder requires scalar dimensions for non-array filter types.`,+ };+ }+ // Set-semantics value arrays must not contain duplicates β `any of` /+ // `none of` / `all of` are set operators, so duplicate elements produce+ // a logically identical filter that would fragment schedulerBatchId.+ if (+ filter.type === "stringOptions" ||+ filter.type === "categoryOptions" ||+ filter.type === "arrayOptions"+ ) {+ if (new Set(filter.value).size !== filter.value.length) {+ return {+ valid: false,+ reason:+ `Filter on "${filter.column}" (type "${filter.type}") must have unique values; ` ++ `duplicates are not allowed for set-semantics operators.`,+ };+ }+ }+ }++ return { valid: true };+}diff --git a/packages/shared/src/features/monitors/isValidThresholdOrder.test.ts b/packages/shared/src/features/monitors/isValidThresholdOrder.test.tsnew file mode 100644index 0000000000..811f8a0c90--- /dev/null+++ b/packages/shared/src/features/monitors/isValidThresholdOrder.test.ts@@ -0,0 +1,84 @@+import { describe, it, expect } from "vitest";++import { isValidThresholdOrder } from "./isValidThresholdOrder";++describe("isValidThresholdOrder", () => {+ it.each(["gt", "gte"] as const)(+ "%s requires warningThreshold < alertThreshold",+ (op) => {+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 50,+ }),+ ).toBe(true);+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100, // equal β invalid+ }),+ ).toBe(false);+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 200, // warning > alert β invalid for gt+ }),+ ).toBe(false);+ },+ );++ it.each(["lt", "lte"] as const)(+ "%s requires warningThreshold > alertThreshold",+ (op) => {+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 200,+ }),+ ).toBe(true);+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100,+ }),+ ).toBe(false);+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 50,+ }),+ ).toBe(false);+ },+ );++ it.each(["eq", "neq"] as const)("%s passes regardless of ordering", (op) => {+ for (const warning of [50, 100, 200]) {+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: warning,+ }),+ ).toBe(true);+ }+ });++ it.each(["gt", "gte", "lt", "lte", "eq", "neq"] as const)(+ "%s passes when warningThreshold is null",+ (op) => {+ expect(+ isValidThresholdOrder({+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: null,+ }),+ ).toBe(true);+ },+ );+});diff --git a/packages/shared/src/features/monitors/isValidThresholdOrder.ts b/packages/shared/src/features/monitors/isValidThresholdOrder.tsnew file mode 100644index 0000000000..5ae2463234--- /dev/null+++ b/packages/shared/src/features/monitors/isValidThresholdOrder.ts@@ -0,0 +1,28 @@+/** isValidThresholdOrder.ts contains the warning-vs-alert threshold ordering+ * predicate. Consumed as a zod `superRefine` from the Monitor input schemas+ * via `validateThresholdOrder` in `./types`. */+import { type MonitorThresholdOperator } from "./types";++/**+ * isValidThresholdOrder returns true when the warning and alert thresholds+ * are ordered correctly for the given operator. Null `warningThreshold` and+ * the unordered `eq`/`neq` operators always pass.+ */+export const isValidThresholdOrder = (monitor: {+ thresholdOperator: MonitorThresholdOperator;+ alertThreshold: number;+ warningThreshold: number | null;+}): boolean => {+ if (monitor.warningThreshold == null) return true;+ switch (monitor.thresholdOperator) {+ case "gt":+ case "gte":+ return monitor.warningThreshold < monitor.alertThreshold;+ case "lt":+ case "lte":+ return monitor.warningThreshold > monitor.alertThreshold;+ case "eq":+ case "neq":+ return true;+ }+};diff --git a/packages/shared/src/features/monitors/scheduler/types.test.ts b/packages/shared/src/features/monitors/scheduler/types.test.tsnew file mode 100644index 0000000000..9fed80c593--- /dev/null+++ b/packages/shared/src/features/monitors/scheduler/types.test.ts@@ -0,0 +1,185 @@+import { describe, it, expect } from "vitest";++import {+ MonitorQueueEventSchema,+ MonitorWebhookQueueEventSchema,+} from "./types";++describe("MonitorQueueEventSchema", () => {+ const validQueueEvent = {+ projectId: "proj_01",+ schedulerBatchId: 42n,+ scheduledAt: new Date("2026-05-18T12:00:00.000Z"),+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ metrics: [{ measure: "count", aggregation: "count" as const }],+ monitors: [{ monitorId: "mon_01", metricName: "count_count" }],+ };++ it("parses a representative queue event", () => {+ const result = MonitorQueueEventSchema.safeParse(validQueueEvent);+ expect(result.success).toBe(true);+ });++ it("coerces a string scheduledAt to a Date", () => {+ const result = MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ scheduledAt: "2026-05-18T12:00:00.000Z",+ });+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.scheduledAt).toBeInstanceOf(Date);+ });++ it("coerces a string schedulerBatchId to a bigint", () => {+ const result = MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ schedulerBatchId: "42",+ });+ expect(result.success).toBe(true);+ if (result.success)+ expect(typeof result.data.schedulerBatchId).toBe("bigint");+ });++ it("rejects a window outside the MonitorWindow tier set", () => {+ expect(+ MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ window: "bogus",+ }).success,+ ).toBe(false);+ });++ it("rejects a negative schedulerBatchId", () => {+ // `calculateSchedulerBatchId` masks the sha256 high 8 bytes with+ // `& (2^63 - 1)`, so the producer can never emit a negative value. Guard+ // the wire boundary so anything else looks like an obvious validator+ // failure rather than corrupted data.+ expect(+ MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ schedulerBatchId: -1n,+ }).success,+ ).toBe(false);+ });++ it("accepts zero as a schedulerBatchId", () => {+ // Cryptographically improbable but mathematically possible; the+ // refinement is `.nonnegative()`, not `.positive()`, to match the+ // producer's contract.+ expect(+ MonitorQueueEventSchema.safeParse({+ ...validQueueEvent,+ schedulerBatchId: 0n,+ }).success,+ ).toBe(true);+ });++ it("accepts an empty monitors array", () => {+ // Scheduler may publish with zero monitors if everything in the batch was+ // filtered out β schema should not block; downstream worker handles it.+ expect(+ MonitorQueueEventSchema.safeParse({ ...validQueueEvent, monitors: [] })+ .success,+ ).toBe(true);+ });+});++describe("MonitorWebhookQueueEventSchema", () => {+ const validEnvelope = {+ type: "monitor-alert" as const,+ version: "v1" as const,+ payload: {+ monitorId: "mon_01",+ projectId: "proj_01",+ severity: "alert" as const,+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ },+ };++ it("parses a valid envelope", () => {+ expect(+ MonitorWebhookQueueEventSchema.safeParse(validEnvelope).success,+ ).toBe(true);+ });++ it("rejects a wrong type discriminator", () => {+ expect(+ MonitorWebhookQueueEventSchema.safeParse({+ ...validEnvelope,+ type: "prompt-version",+ }).success,+ ).toBe(false);+ });++ it("rejects a wrong version literal", () => {+ expect(+ MonitorWebhookQueueEventSchema.safeParse({+ ...validEnvelope,+ version: "v2",+ }).success,+ ).toBe(false);+ });+});++describe("scheduler DTO JSON round-trip (wire contract)", () => {+ // BigInt and Date can't be JSON-stringified natively; the wire schemas use+ // `z.coerce.*` to recover them on the consumer side. These tests lock that+ // contract: produce β JSON.stringify β JSON.parse β schema.parse must+ // round-trip successfully.++ const stringifyWithBigInt = (value: unknown) =>+ JSON.stringify(value, (_key, v) =>+ typeof v === "bigint" ? v.toString() : v,+ );++ it("round-trips a MonitorQueueEvent through JSON", () => {+ const event = {+ projectId: "proj_01",+ schedulerBatchId: 42n,+ scheduledAt: new Date("2026-05-18T12:00:00.000Z"),+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ metrics: [{ measure: "count", aggregation: "count" as const }],+ monitors: [{ monitorId: "mon_01", metricName: "count_count" }],+ };+ const wire = JSON.parse(stringifyWithBigInt(event));+ const result = MonitorQueueEventSchema.safeParse(wire);+ expect(result.success).toBe(true);+ if (result.success) {+ expect(typeof result.data.schedulerBatchId).toBe("bigint");+ expect(result.data.scheduledAt).toBeInstanceOf(Date);+ expect(result.data.window).toBe("5m");+ }+ });++ it("round-trips a MonitorWebhookQueueEvent envelope through JSON", () => {+ const envelope = {+ type: "monitor-alert" as const,+ version: "v1" as const,+ payload: {+ monitorId: "mon_01",+ projectId: "proj_01",+ severity: "alert" as const,+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ },+ };+ const wire = JSON.parse(stringifyWithBigInt(envelope));+ const result = MonitorWebhookQueueEventSchema.safeParse(wire);+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.payload.timestamp).toBeInstanceOf(Date);+ }+ });+});diff --git a/packages/shared/src/features/monitors/scheduler/types.ts b/packages/shared/src/features/monitors/scheduler/types.tsnew file mode 100644index 0000000000..90ed8edcbe--- /dev/null+++ b/packages/shared/src/features/monitors/scheduler/types.ts@@ -0,0 +1,54 @@+/** scheduler/types.ts contains the transport DTOs the scheduler/worker+ * publish on BullMQ. These are wire-shaped (coerced primitives) and not+ * domain entities. */+import { z } from "zod";++import { metric as MetricSchema } from "../../query/types";++import {+ MonitorAlertSchema,+ MonitorFiltersSchema,+ MonitorViewSchema,+ MonitorWindowSchema,+} from "../types";++/**+ * MonitorQueueEventSchema represents a batch of monitors that can be+ * evaluated together using the same set of parameters.+ *+ * All monitors in `monitors[]` share `view` / `filters` / `window`, so the+ * worker runs one ClickHouse query for the whole batch.+ */+export const MonitorQueueEventSchema = z.object({+ projectId: z.string(),+ // Fingerprint of (projectId, view, filters, window)+ schedulerBatchId: z.coerce.bigint().nonnegative(),++ // Scheduler tick time+ scheduledAt: z.coerce.date(),++ // Shared query primitives β every monitor in this batch agrees on these.+ view: MonitorViewSchema,+ filters: MonitorFiltersSchema,+ window: MonitorWindowSchema,+ metrics: z.array(MetricSchema),++ // Monitors map to metricNames returned by the above query params+ monitors: z.array(+ z.object({ monitorId: z.string(), metricName: z.string() }),+ ),+});+export type MonitorQueueEvent = z.infer<typeof MonitorQueueEventSchema>;++/**+ * MonitorWebhookQueueEventSchema is the transport envelope wrapping+ * `MonitorAlertSchema` for the `WebhookQueue`.+ */+export const MonitorWebhookQueueEventSchema = z.object({+ type: z.literal("monitor-alert"),+ version: z.literal("v1"),+ payload: MonitorAlertSchema,+});+export type MonitorWebhookQueueEvent = z.infer<+ typeof MonitorWebhookQueueEventSchema+>;diff --git a/packages/shared/src/features/monitors/server.ts b/packages/shared/src/features/monitors/server.tsnew file mode 100644index 0000000000..db6f73c2ca--- /dev/null+++ b/packages/shared/src/features/monitors/server.ts@@ -0,0 +1,6 @@+/** server.ts is the server-only barrel for the monitors feature. It+ * re-exports everything client-safe from `./index` plus the service and+ * scheduler DTOs. */+export * from "./index";+export * from "./service";+export * from "./scheduler/types";diff --git a/packages/shared/src/features/monitors/service/helpers.test.ts b/packages/shared/src/features/monitors/service/helpers.test.tsnew file mode 100644index 0000000000..8988443056--- /dev/null+++ b/packages/shared/src/features/monitors/service/helpers.test.ts@@ -0,0 +1,563 @@+import {+ MonitorSeverity as PrismaMonitorSeverity,+ MonitorStatus as PrismaMonitorStatus,+ MonitorThresholdOperator as PrismaMonitorThresholdOperator,+ MonitorView as PrismaMonitorView,+ Prisma,+} from "@prisma/client";+import { describe, it, expect } from "vitest";+import { z } from "zod";++import { InvalidRequestError } from "../../../errors";+import { singleFilter } from "../../../interfaces/filters";+import {+ MonitorSeveritySchema,+ MonitorStatusSchema,+ MonitorThresholdOperatorSchema,+ MonitorViewSchema,+ MonitorWindowSchema,+} from "../types";+import { DAY, HOUR, MINUTE, WEEK } from "../helpers";+import {+ calculateCadence,+ calculateLastRunAt,+ calculateSchedulerBatchId,+ decimalToPrisma,+ errorFromPrisma,+ monitorFromPrisma,+ severityFromPrisma,+ sortFiltersCanonically,+ statusFromPrisma,+ statusToPrisma,+ thresholdOperatorFromPrisma,+ thresholdOperatorToPrisma,+ viewFromPrisma,+ viewToPrisma,+ windowFromMs,+ windowToMs,+} from "./helpers";++type Filter = z.infer<typeof singleFilter>;++const stringFilter = (column: string, value: string): Filter => ({+ column,+ operator: "=",+ value,+ type: "string",+});++const stringOptionsFilter = (column: string, value: string[]): Filter => ({+ column,+ operator: "any of",+ value,+ type: "stringOptions",+});++describe("sortFiltersCanonically", () => {+ it("returns a new array sorted by column", () => {+ const input: Filter[] = [+ stringFilter("env", "production"),+ stringFilter("app", "faq-bot"),+ ];+ const sorted = sortFiltersCanonically(input);++ expect(sorted.map((f) => f.column)).toEqual(["app", "env"]);+ // does not mutate the original+ expect(input.map((f) => f.column)).toEqual(["env", "app"]);+ });++ it("breaks column ties by operator", () => {+ const input: Filter[] = [+ { column: "env", operator: ">=", value: 10, type: "number" },+ { column: "env", operator: "=", value: 10, type: "number" },+ ];+ const sorted = sortFiltersCanonically(input);+ expect(sorted.map((f) => f.operator)).toEqual(["=", ">="]);+ });++ it("breaks column+operator ties by stringified value", () => {+ const input: Filter[] = [+ stringOptionsFilter("env", ["staging", "production"]),+ stringOptionsFilter("env", ["dev"]),+ ];+ const sorted = sortFiltersCanonically(input);+ // JSON.stringify(["dev"]) < JSON.stringify(["staging","production"])+ expect(sorted[0].value).toEqual(["dev"]);+ });++ it("sorts the value array for set-semantics operators", () => {+ // `stringOptions` / `categoryOptions` / `arrayOptions` all use the+ // `any of` / `none of` / `all of` operators over a `string[]` value, and+ // element order is semantically irrelevant β must canonicalize the array+ // so equivalent filters hash the same.+ const input: Filter[] = [+ stringOptionsFilter("env", ["staging", "production", "dev"]),+ ];+ const sorted = sortFiltersCanonically(input);+ expect(sorted[0].value as string[]).toEqual([+ "dev",+ "production",+ "staging",+ ]);+ });++ it("breaks column+operator ties by `key` for stringObject filters", () => {+ // Two metadata filters with the same operator and value but different+ // keys must canonicalize on `key` β otherwise filters that scope to+ // different metadata properties collide in the canonical sequence.+ const input: Filter[] = [+ {+ type: "stringObject",+ column: "metadata",+ key: "tenant",+ operator: "=",+ value: "acme",+ },+ {+ type: "stringObject",+ column: "metadata",+ key: "env",+ operator: "=",+ value: "acme",+ },+ ];+ const sorted = sortFiltersCanonically(input);+ expect((sorted[0] as { key: string }).key).toBe("env");+ expect((sorted[1] as { key: string }).key).toBe("tenant");+ });++ it("is idempotent", () => {+ const input: Filter[] = [+ stringFilter("env", "production"),+ stringFilter("app", "faq-bot"),+ ];+ const once = sortFiltersCanonically(input);+ const twice = sortFiltersCanonically(once);+ expect(twice).toEqual(once);+ });+});++describe("calculateCadence", () => {+ it("returns 1 minute for sub-day windows", () => {+ expect(calculateCadence(5n * 60_000n)).toBe(MINUTE);+ expect(calculateCadence(4n * 60n * 60_000n)).toBe(MINUTE);+ expect(calculateCadence(DAY - 1n)).toBe(MINUTE);+ });++ it("returns 30 minutes for day-to-week windows", () => {+ expect(calculateCadence(24n * 60n * 60_000n)).toBe(30n * MINUTE);+ expect(calculateCadence(DAY + 1n)).toBe(30n * MINUTE);+ expect(calculateCadence(2n * 24n * 60n * 60_000n)).toBe(30n * MINUTE);+ expect(calculateCadence(WEEK - 1n)).toBe(30n * MINUTE);+ });++ it("returns 48 hours for week-and-up windows", () => {+ expect(calculateCadence(7n * 24n * 60n * 60_000n)).toBe(48n * HOUR);+ expect(calculateCadence(WEEK + 1n)).toBe(48n * HOUR);+ });+});++describe("calculateSchedulerBatchId", () => {+ const base = {+ projectId: "proj_01",+ view: "observations" as const,+ filters: [+ stringFilter("env", "production"),+ stringFilter("app", "faq-bot"),+ ],+ windowMs: 5n * 60_000n,+ };++ it("is deterministic across calls", () => {+ expect(calculateSchedulerBatchId(base)).toBe(+ calculateSchedulerBatchId(base),+ );+ });++ it("is filter-order-insensitive", () => {+ const reordered = {+ ...base,+ filters: [...base.filters].reverse(),+ };+ expect(calculateSchedulerBatchId(reordered)).toBe(+ calculateSchedulerBatchId(base),+ );+ });++ it("is permutation-invariant for set-semantics value arrays", () => {+ // `stringOptions` (and its siblings) carry a set as `value` β element+ // order does not change which rows match, so two filters that pick the+ // same options in different orders MUST produce the same+ // schedulerBatchId. Otherwise the worker batching optimization+ // fragments on logically-identical multi-select filters.+ const a = calculateSchedulerBatchId({+ ...base,+ filters: [stringOptionsFilter("env", ["prod", "staging"])],+ });+ const b = calculateSchedulerBatchId({+ ...base,+ filters: [stringOptionsFilter("env", ["staging", "prod"])],+ });+ expect(a).toBe(b);+ });++ it("is permutation-invariant for filters that differ only in `key`", () => {+ // Two metadata.* filters with the same (column, operator, value) but+ // different keys MUST canonicalize to the same sequence regardless of+ // input order; otherwise the schedulerBatchId is not a stable+ // fingerprint of the query shape.+ const metaTenant: Filter = {+ type: "stringObject",+ column: "metadata",+ key: "tenant",+ operator: "=",+ value: "acme",+ };+ const metaEnv: Filter = {+ type: "stringObject",+ column: "metadata",+ key: "env",+ operator: "=",+ value: "acme",+ };+ const a = calculateSchedulerBatchId({+ ...base,+ filters: [metaTenant, metaEnv],+ });+ const b = calculateSchedulerBatchId({+ ...base,+ filters: [metaEnv, metaTenant],+ });+ expect(a).toBe(b);+ });++ it("hashes equally for a metadata filter parsed from inputs with different property orders", () => {+ // Zod `.parse` rebuilds the object in schema-declared property order, so+ // two raw inputs with the same content but different property orders+ // produce identical canonical filters and identical hashes.+ const canonical = singleFilter.parse({+ type: "stringObject",+ column: "metadata",+ key: "env",+ operator: "=",+ value: "prod",+ });+ const reordered = singleFilter.parse({+ value: "prod",+ operator: "=",+ key: "env",+ column: "metadata",+ type: "stringObject",+ });+ const a = calculateSchedulerBatchId({ ...base, filters: [canonical] });+ const b = calculateSchedulerBatchId({ ...base, filters: [reordered] });+ expect(a).toBe(b);+ });++ it("hashes equally for a set-semantics filter parsed from inputs with reordered value arrays", () => {+ // The set-semantics canonicalization in `sortFiltersCanonically` sorts+ // the value array, so a parsed filter with reordered `value` elements+ // hashes the same as its canonically-ordered counterpart.+ const canonical = singleFilter.parse({+ type: "stringOptions",+ column: "env",+ operator: "any of",+ value: ["prod", "staging"],+ });+ const reordered = singleFilter.parse({+ type: "stringOptions",+ column: "env",+ operator: "any of",+ value: ["staging", "prod"],+ });+ const a = calculateSchedulerBatchId({ ...base, filters: [canonical] });+ const b = calculateSchedulerBatchId({ ...base, filters: [reordered] });+ expect(a).toBe(b);+ });++ it("changes when projectId changes", () => {+ expect(+ calculateSchedulerBatchId({ ...base, projectId: "proj_02" }),+ ).not.toBe(calculateSchedulerBatchId(base));+ });++ it("changes when view changes", () => {+ expect(+ calculateSchedulerBatchId({ ...base, view: "scores-numeric" }),+ ).not.toBe(calculateSchedulerBatchId(base));+ });++ it("changes when window changes", () => {+ expect(+ calculateSchedulerBatchId({+ ...base,+ windowMs: 60n * 60_000n,+ }),+ ).not.toBe(calculateSchedulerBatchId(base));+ });++ it("changes when a filter value changes", () => {+ expect(+ calculateSchedulerBatchId({+ ...base,+ filters: [stringFilter("env", "staging"), ...base.filters.slice(1)],+ }),+ ).not.toBe(calculateSchedulerBatchId(base));+ });++ it("returns a nonneg i63 (fits Postgres BIGINT)", () => {+ for (const view of [+ "observations",+ "scores-numeric",+ "scores-categorical",+ ] as const) {+ const id = calculateSchedulerBatchId({ ...base, view });+ expect(id >= 0n).toBe(true);+ expect(id < 1n << 63n).toBe(true);+ }+ });+});++describe("calculateLastRunAt", () => {+ const ONE_MINUTE = 60n * 1000n;+ const THIRTY_MIN = 30n * ONE_MINUTE;+ const FORTY_EIGHT_HOURS = 48n * 60n * ONE_MINUTE;++ it("returns a Date strictly at or before now", () => {+ const now = new Date("2026-05-19T12:34:56.789Z");+ const result = calculateLastRunAt(now, ONE_MINUTE, 17n);+ expect(result.getTime()).toBeLessThanOrEqual(now.getTime());+ });++ it("places the result on the (boundary + offset) slot", () => {+ // schedulerBatchId % 60 = 17 β offset = 17_000ms+ const now = new Date("2026-05-19T12:34:56.789Z");+ const result = calculateLastRunAt(now, ONE_MINUTE, 17n);++ // result is exactly (boundary + 17s); the seconds-component is 17+ expect(result.getUTCSeconds()).toBe(17);+ expect(result.getUTCMilliseconds()).toBe(0);+ });++ it("is deterministic per (schedulerBatchId, cadence) inside one cadence", () => {+ const cadence = ONE_MINUTE;+ const batchId = 42n;++ // two `now`s within the same minute-after-offset window+ const a = calculateLastRunAt(+ new Date("2026-05-19T12:34:50.000Z"),+ cadence,+ batchId,+ );+ const b = calculateLastRunAt(+ new Date("2026-05-19T12:34:55.123Z"),+ cadence,+ batchId,+ );+ expect(a.getTime()).toBe(b.getTime());+ });++ it("computes a deterministic slot for the 30-minute cadence", () => {+ const result = calculateLastRunAt(+ new Date("2026-05-19T12:45:00.000Z"),+ THIRTY_MIN,+ 45n,+ );+ // most recent boundary <= 12:45:00 with offset=45s is 12:30:45+ expect(result.toISOString()).toBe("2026-05-19T12:30:45.000Z");+ });++ it("computes a deterministic slot for the 48-hour cadence", () => {+ // epoch 0 is a 48h boundary; 48h slots align at multiples of 172_800_000ms from epoch.+ const now = new Date("2026-05-19T12:00:00.000Z");+ const result = calculateLastRunAt(now, FORTY_EIGHT_HOURS, 7n);++ const cadenceMs = Number(FORTY_EIGHT_HOURS);+ const offsetMs = 7 * 1000;+ const expected =+ Math.floor((now.getTime() - offsetMs) / cadenceMs) * cadenceMs + offsetMs;+ expect(result.getTime()).toBe(expected);+ expect(result.getTime()).toBeLessThanOrEqual(now.getTime());+ });++ it("preserves the same in-cadence offset for the same batchId across different `now`s", () => {+ // Two monitors with the same schedulerBatchId created at different `now`s+ // produce different initial lastRunAt values (off by a cadence), but each+ // is on the same `(boundary + offset)` slot β the scheduler converges them+ // by advancing each by +cadence on every tick where due.+ const cadence = ONE_MINUTE;+ const batchId = 30n;++ const a = calculateLastRunAt(+ new Date("2026-05-19T12:00:10.000Z"),+ cadence,+ batchId,+ );+ const b = calculateLastRunAt(+ new Date("2026-05-19T12:00:40.000Z"),+ cadence,+ batchId,+ );++ const cadenceMs = Number(cadence);+ const offsetMs = Number(batchId % 60n) * 1000;+ expect(a.getTime() % cadenceMs).toBe(offsetMs);+ expect(b.getTime() % cadenceMs).toBe(offsetMs);+ });+});++describe("windowToMs / windowFromMs", () => {+ it.each(MonitorWindowSchema.options)("round-trips %s", (window) => {+ expect(windowFromMs(windowToMs(window))).toBe(window);+ });++ it("throws InvalidRequestError on a bigint that isn't a known tier", () => {+ expect(() => windowFromMs(123n)).toThrow(InvalidRequestError);+ });+});++describe("viewToPrisma / viewFromPrisma", () => {+ it.each(MonitorViewSchema.options)("round-trips %s", (view) => {+ expect(viewFromPrisma(viewToPrisma(view))).toBe(view);+ });++ it.each(Object.values(PrismaMonitorView))("round-trips Prisma %s", (view) => {+ expect(viewToPrisma(viewFromPrisma(view))).toBe(view);+ });+});++describe("statusToPrisma / statusFromPrisma", () => {+ it.each(MonitorStatusSchema.options)("round-trips %s", (status) => {+ expect(statusFromPrisma(statusToPrisma(status))).toBe(status);+ });++ it.each(Object.values(PrismaMonitorStatus))(+ "round-trips Prisma %s",+ (status) => {+ expect(statusToPrisma(statusFromPrisma(status))).toBe(status);+ },+ );+});++describe("severityFromPrisma", () => {+ // No `severityToPrisma`: severity is owned by the scheduler/worker, never by+ // a caller submitting an input. Only the reverse mapping is needed.+ it.each(Object.values(PrismaMonitorSeverity))(+ "maps Prisma %s to a valid MonitorSeverity",+ (severity) => {+ const mapped = severityFromPrisma(severity);+ expect(MonitorSeveritySchema.options).toContain(mapped);+ },+ );+});++describe("thresholdOperatorToPrisma / thresholdOperatorFromPrisma", () => {+ it.each(MonitorThresholdOperatorSchema.options)("round-trips %s", (op) => {+ expect(thresholdOperatorFromPrisma(thresholdOperatorToPrisma(op))).toBe(op);+ });++ it.each(Object.values(PrismaMonitorThresholdOperator))(+ "round-trips Prisma %s",+ (op) => {+ expect(thresholdOperatorToPrisma(thresholdOperatorFromPrisma(op))).toBe(+ op,+ );+ },+ );+});++describe("decimalToPrisma", () => {+ it("returns null for a null input", () => {+ expect(decimalToPrisma(null)).toBeNull();+ });++ it("wraps a finite number as Prisma.Decimal", () => {+ const out = decimalToPrisma(42);+ expect(out).toBeInstanceOf(Prisma.Decimal);+ expect((out as Prisma.Decimal).toNumber()).toBe(42);+ });+});++describe("errorFromPrisma", () => {+ it("maps P2025 (row not found) to InvalidRequestError", () => {+ const e = new Prisma.PrismaClientKnownRequestError("not found", {+ code: "P2025",+ clientVersion: "test",+ });+ const mapped = errorFromPrisma("mon_01", "proj_01", e);+ expect(mapped).toBeInstanceOf(InvalidRequestError);+ expect(mapped.message).toContain("mon_01");+ expect(mapped.message).toContain("proj_01");+ });++ it("passes through other Prisma errors unchanged", () => {+ const e = new Prisma.PrismaClientKnownRequestError("oops", {+ code: "P2002",+ clientVersion: "test",+ });+ expect(errorFromPrisma("mon_01", "proj_01", e)).toBe(e);+ });++ it("passes through non-Prisma errors unchanged", () => {+ const e = new Error("boom");+ expect(errorFromPrisma("mon_01", "proj_01", e)).toBe(e);+ });+});++describe("monitorFromPrisma", () => {+ // The shape of a Prisma `Monitor` row, post-fetch. The mapper translates+ // enums, unwraps Decimals, and re-emits the API-shaped `window` string.+ const prismaRow = {+ id: "mon_01",+ createdAt: new Date("2026-05-18T00:00:00.000Z"),+ updatedAt: new Date("2026-05-18T00:00:00.000Z"),+ createdBy: null,+ updatedBy: null,+ projectId: "proj_01",+ view: PrismaMonitorView.OBSERVATIONS,+ filters: [],+ metric: { measure: "count", aggregation: "count" },+ windowMs: 5n * 60_000n,+ cadenceMs: 60_000n,+ schedulerBatchId: 42n,+ thresholdOperator: PrismaMonitorThresholdOperator.GT,+ alertThreshold: new Prisma.Decimal(100),+ warningThreshold: null,+ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },+ severity: PrismaMonitorSeverity.UNKNOWN,+ severityChangedAt: null,+ alertedAt: null,+ status: PrismaMonitorStatus.ACTIVE,+ nextRunAt: new Date("2026-05-18T00:01:00.000Z"),+ lastPublishedRunAt: null,+ lastCompletedRunAt: null,+ name: "High error rate",+ tags: [] as string[],+ };++ it("translates a representative row to the domain shape", () => {+ const monitor = monitorFromPrisma(prismaRow);+ expect(monitor.view).toBe("observations");+ expect(monitor.status).toBe("active");+ expect(monitor.severity).toBe("unknown");+ expect(monitor.thresholdOperator).toBe("gt");+ expect(monitor.window).toBe("5m");+ expect(monitor.alertThreshold).toBe(100);+ expect(monitor.warningThreshold).toBeNull();+ });++ it("unwraps a Decimal warningThreshold", () => {+ const monitor = monitorFromPrisma({+ ...prismaRow,+ warningThreshold: new Prisma.Decimal(50),+ });+ expect(monitor.warningThreshold).toBe(50);+ });++ it("throws when windowMs doesn't match a tier", () => {+ expect(() =>+ monitorFromPrisma({ ...prismaRow, windowMs: 7n * 60_000n }),+ ).toThrow(InvalidRequestError);+ });+});diff --git a/packages/shared/src/features/monitors/service/helpers.ts b/packages/shared/src/features/monitors/service/helpers.tsnew file mode 100644index 0000000000..7d6794f2fe--- /dev/null+++ b/packages/shared/src/features/monitors/service/helpers.ts@@ -0,0 +1,327 @@+/** service/helpers.ts contains the mapping + calculate helpers consumed+ * by MonitorService. Exported so that colocated unit tests can exercise them,+ * but intentionally not re-exported from the service barrel β internal+ * implementation detail of the service. */+import { createHash } from "node:crypto";+import {+ type Monitor as PrismaMonitor,+ MonitorSeverity as PrismaMonitorSeverity,+ MonitorStatus as PrismaMonitorStatus,+ MonitorThresholdOperator as PrismaMonitorThresholdOperator,+ MonitorView as PrismaMonitorView,+ Prisma,+} from "@prisma/client";++import { InvalidRequestError } from "../../../errors";++import { DAY, HOUR, MINUTE, WEEK } from "../helpers";+import {+ type Monitor,+ type MonitorFilters,+ type MonitorSeverity,+ type MonitorStatus,+ type MonitorThresholdOperator,+ type MonitorView,+ type MonitorWindow,+ MonitorSchema,+} from "../types";++import { type MonitorListOrderBy } from "./types";++/** nullableOrderColumns is the list of sortable columns that are nullable. */+export const nullableOrderColumns: ReadonlySet<MonitorListOrderBy> = new Set([+ "severityChangedAt",+ "alertedAt",+]);++/**+ * canonicalizeFilter normalizes a single filter for canonical comparison.+ * For the set-semantics filter variants (`stringOptions` / `categoryOptions` /+ * `arrayOptions`, all of which use `any of` / `none of` / `all of` over a+ * `string[]` value) element order is semantically irrelevant, so the value+ * array is sorted. Otherwise the filter is returned unchanged.+ *+ * Without this, `["prod","staging"]` and `["staging","prod"]` would produce+ * different `schedulerBatchId` values for logically-identical filters,+ * fragmenting the worker batching optimization the helper exists to enable.+ */+const canonicalizeFilter = (+ f: MonitorFilters[number],+): MonitorFilters[number] => {+ if (+ f.type === "stringOptions" ||+ f.type === "categoryOptions" ||+ f.type === "arrayOptions"+ ) {+ return { ...f, value: [...f.value].sort() };+ }+ return f;+};++/**+ * sortFiltersCanonically returns a new array of filters in canonical order:+ * each filter's value is normalized first (set-semantics value arrays are+ * sorted), then filters are sorted by `column` β `operator` β `key` (when+ * present on `stringObject`/`numberObject`/`categoryOptions`/`positionInTrace`+ * variants) β `JSON.stringify(value)`. Same logical filter set β same+ * canonical sequence, regardless of input order.+ */+export const sortFiltersCanonically = (+ filters: MonitorFilters,+): MonitorFilters =>+ filters.map(canonicalizeFilter).sort((a, b) => {+ if (a.column !== b.column) return a.column < b.column ? -1 : 1;+ if (a.operator !== b.operator) return a.operator < b.operator ? -1 : 1;+ const aKey = "key" in a ? String(a.key) : "";+ const bKey = "key" in b ? String(b.key) : "";+ if (aKey !== bKey) return aKey < bKey ? -1 : 1;+ const av = JSON.stringify(a.value);+ const bv = JSON.stringify(b.value);+ if (av !== bv) return av < bv ? -1 : 1;+ return 0;+ });++/**+ * calculateCadence derives a Monitor's scheduler cadence from its evaluation+ * window.+ */+export const calculateCadence = (windowMillis: bigint): bigint => {+ if (windowMillis >= WEEK) return 48n * HOUR;+ if (windowMillis >= DAY) return 30n * MINUTE;+ return MINUTE; // default cadence+};++/**+ * calculateSchedulerBatchId fingerprints the query shape that the scheduler+ * groups by: (projectId, view, canonicalized filters, windowMs). Output fits+ * Postgres BIGINT (nonneg i63).+ */+export const calculateSchedulerBatchId = (params: {+ projectId: string;+ view: MonitorView;+ filters: MonitorFilters;+ windowMs: bigint;+}): bigint => {+ const canonical = sortFiltersCanonically(params.filters);+ const input = [+ params.projectId,+ params.view,+ JSON.stringify(canonical),+ params.windowMs.toString(),+ ].join("\x1f");+ const digest = createHash("sha256").update(input).digest();+ return digest.readBigUInt64BE(0) & ((1n << 63n) - 1n);+};++/**+ * calculateLastRunAt picks the most recent cadence boundary at or before+ * `now`, offset by `(schedulerBatchId % 60) * 1000` ms. Persisted as+ * `monitor.nextRunAt` on create/update so the scheduler picks the monitor up+ * on its very next tick and advances it onto the deterministic slot.+ */+export const calculateLastRunAt = (+ now: Date,+ cadenceMs: bigint,+ schedulerBatchId: bigint,+): Date => {+ const cadence = Number(cadenceMs);+ const offset = Number(schedulerBatchId % 60n) * 1000;+ const aligned =+ Math.floor((now.getTime() - offset) / cadence) * cadence + offset;+ return new Date(aligned);+};++/** viewToPrisma converts the MonitorView api enum to the Prisma MonitorView enum. */+export const viewToPrisma = (view: MonitorView): PrismaMonitorView => {+ switch (view) {+ case "observations":+ return PrismaMonitorView.OBSERVATIONS;+ case "scores-numeric":+ return PrismaMonitorView.SCORES_NUMERIC;+ case "scores-categorical":+ return PrismaMonitorView.SCORES_CATEGORICAL;+ }+};++/** viewFromPrisma converts the Prisma MonitorView enum to the MonitorView api enum. */+export const viewFromPrisma = (view: PrismaMonitorView): MonitorView => {+ switch (view) {+ case PrismaMonitorView.OBSERVATIONS:+ return "observations";+ case PrismaMonitorView.SCORES_NUMERIC:+ return "scores-numeric";+ case PrismaMonitorView.SCORES_CATEGORICAL:+ return "scores-categorical";+ }+};++/** severityFromPrisma converts the Prisma MonitorSeverity enum to the MonitorSeverity api enum. */+export const severityFromPrisma = (+ s: PrismaMonitorSeverity,+): MonitorSeverity => {+ switch (s) {+ case PrismaMonitorSeverity.UNKNOWN:+ return "unknown";+ case PrismaMonitorSeverity.NO_DATA:+ return "no-data";+ case PrismaMonitorSeverity.OK:+ return "ok";+ case PrismaMonitorSeverity.WARNING:+ return "warning";+ case PrismaMonitorSeverity.ALERT:+ return "alert";+ }+};++/** statusToPrisma converts the MonitorStatus api enum to the Prisma MonitorStatus enum. */+export const statusToPrisma = (s: MonitorStatus): PrismaMonitorStatus => {+ switch (s) {+ case "paused":+ return PrismaMonitorStatus.PAUSED;+ case "active":+ return PrismaMonitorStatus.ACTIVE;+ case "error-bad-query":+ return PrismaMonitorStatus.ERROR_BAD_QUERY;+ }+};++/** statusFromPrisma converts the Prisma MonitorStatus enum to the MonitorStatus api enum. */+export const statusFromPrisma = (s: PrismaMonitorStatus): MonitorStatus => {+ switch (s) {+ case PrismaMonitorStatus.PAUSED:+ return "paused";+ case PrismaMonitorStatus.ACTIVE:+ return "active";+ case PrismaMonitorStatus.ERROR_BAD_QUERY:+ return "error-bad-query";+ }+};++/** thresholdOperatorToPrisma converts the MonitorThresholdOperator api enum to the Prisma MonitorThresholdOperator enum. */+export const thresholdOperatorToPrisma = (+ o: MonitorThresholdOperator,+): PrismaMonitorThresholdOperator => {+ switch (o) {+ case "gt":+ return PrismaMonitorThresholdOperator.GT;+ case "gte":+ return PrismaMonitorThresholdOperator.GTE;+ case "lt":+ return PrismaMonitorThresholdOperator.LT;+ case "lte":+ return PrismaMonitorThresholdOperator.LTE;+ case "eq":+ return PrismaMonitorThresholdOperator.EQ;+ case "neq":+ return PrismaMonitorThresholdOperator.NEQ;+ }+};++/** thresholdOperatorFromPrisma converts the Prisma MonitorThresholdOperator enum to the MonitorThresholdOperator api enum. */+export const thresholdOperatorFromPrisma = (+ o: PrismaMonitorThresholdOperator,+): MonitorThresholdOperator => {+ switch (o) {+ case PrismaMonitorThresholdOperator.GT:+ return "gt";+ case PrismaMonitorThresholdOperator.GTE:+ return "gte";+ case PrismaMonitorThresholdOperator.LT:+ return "lt";+ case PrismaMonitorThresholdOperator.LTE:+ return "lte";+ case PrismaMonitorThresholdOperator.EQ:+ return "eq";+ case PrismaMonitorThresholdOperator.NEQ:+ return "neq";+ }+};++/** windowToMs converts the MonitorWindow api enum to a bigint of milliseconds. */+export const windowToMs = (w: MonitorWindow): bigint => {+ switch (w) {+ case "5m":+ return 5n * 60_000n;+ case "10m":+ return 10n * 60_000n;+ case "15m":+ return 15n * 60_000n;+ case "30m":+ return 30n * 60_000n;+ case "1h":+ return 60n * 60_000n;+ case "2h":+ return 2n * 60n * 60_000n;+ case "4h":+ return 4n * 60n * 60_000n;+ case "1d":+ return 24n * 60n * 60_000n;+ case "2d":+ return 2n * 24n * 60n * 60_000n;+ case "1w":+ return 7n * 24n * 60n * 60_000n;+ }+};++/** windowFromMs converts a bigint of milliseconds to the MonitorWindow api enum. */+export const windowFromMs = (ms: bigint): MonitorWindow => {+ switch (ms) {+ case 5n * 60_000n:+ return "5m";+ case 10n * 60_000n:+ return "10m";+ case 15n * 60_000n:+ return "15m";+ case 30n * 60_000n:+ return "30m";+ case 60n * 60_000n:+ return "1h";+ case 2n * 60n * 60_000n:+ return "2h";+ case 4n * 60n * 60_000n:+ return "4h";+ case 24n * 60n * 60_000n:+ return "1d";+ case 2n * 24n * 60n * 60_000n:+ return "2d";+ case 7n * 24n * 60n * 60_000n:+ return "1w";+ default:+ throw new InvalidRequestError(+ `windowMs ${ms.toString()} does not correspond to a known MonitorWindow tier`,+ );+ }+};++/** monitorFromPrisma converts a Prisma monitor row to the domain Monitor. */+export const monitorFromPrisma = (monitor: PrismaMonitor): Monitor =>+ MonitorSchema.parse({+ ...monitor,+ view: viewFromPrisma(monitor.view),+ severity: severityFromPrisma(monitor.severity),+ status: statusFromPrisma(monitor.status),+ thresholdOperator: thresholdOperatorFromPrisma(monitor.thresholdOperator),+ window: windowFromMs(monitor.windowMs),+ alertThreshold: monitor.alertThreshold.toNumber(),+ warningThreshold: monitor.warningThreshold?.toNumber() ?? null,+ });++/** decimalToPrisma converts a nullable JS number to a Prisma.Decimal, preserving null. */+export const decimalToPrisma = (n: number | null): Prisma.Decimal | null =>+ n == null ? null : new Prisma.Decimal(n);++/** errorFromPrisma maps a Prisma client error to a caller-facing Error:+ * P2025 (row not found) becomes `InvalidRequestError`; anything else passes+ * through unchanged. */+export const errorFromPrisma = (+ id: string,+ projectId: string,+ e: unknown,+): Error => {+ if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === "P2025") {+ return new InvalidRequestError(+ `Monitor ${id} not found in project ${projectId}`,+ );+ }+ return e as Error;+};diff --git a/packages/shared/src/features/monitors/service/index.ts b/packages/shared/src/features/monitors/service/index.tsnew file mode 100644index 0000000000..d9846cf88b--- /dev/null+++ b/packages/shared/src/features/monitors/service/index.ts@@ -0,0 +1,5 @@+/** service/index.ts is the MonitorService barrel β public DTOs and the+ * service class. Mapping/calculate helpers in `./helpers` are intentionally+ * not re-exported. */+export * from "./service";+export * from "./types";diff --git a/packages/shared/src/features/monitors/service/service.ts b/packages/shared/src/features/monitors/service/service.tsnew file mode 100644index 0000000000..4f81ffb3cb--- /dev/null+++ b/packages/shared/src/features/monitors/service/service.ts@@ -0,0 +1,173 @@+/** service.ts contains the MonitorService */+import { Prisma, prisma } from "../../../db";++import { type Monitor } from "../types";++import {+ calculateCadence,+ calculateLastRunAt,+ calculateSchedulerBatchId,+ decimalToPrisma,+ errorFromPrisma,+ monitorFromPrisma,+ nullableOrderColumns,+ sortFiltersCanonically,+ statusToPrisma,+ thresholdOperatorToPrisma,+ viewToPrisma,+ windowToMs,+} from "./helpers";+import {+ type CreateMonitorInput,+ type MonitorListInput,+ type UpdateMonitorInput,+} from "./types";++/**+ * MonitorService manages all of the Monitors that produce MonitorAlerts on+ * the system.+ *+ * It normalizes data, calculates derived properties, and persists data to+ * the Prisma repository.+ *+ * Validation is handled directly by the zod schema found in `service/types`.+ * Services assume the inputs have been parsed and validated by tRPC or other+ * API adapters.+ */+export class MonitorService {+ public static async create(input: CreateMonitorInput): Promise<Monitor> {+ const filters = sortFiltersCanonically(input.filters);+ const windowMs = windowToMs(input.window);+ const cadenceMs = calculateCadence(windowMs);+ const schedulerBatchId = calculateSchedulerBatchId({+ projectId: input.projectId,+ view: input.view,+ filters,+ windowMs,+ });+ const nextRunAt = calculateLastRunAt(+ new Date(),+ cadenceMs,+ schedulerBatchId,+ );++ const created = await prisma.monitor.create({+ data: {+ projectId: input.projectId,+ createdBy: input.createdBy,+ updatedBy: input.createdBy,+ view: viewToPrisma(input.view),+ filters,+ metric: input.metric,+ windowMs,+ cadenceMs,+ thresholdOperator: thresholdOperatorToPrisma(input.thresholdOperator),+ alertThreshold: new Prisma.Decimal(input.alertThreshold),+ warningThreshold: decimalToPrisma(input.warningThreshold),+ noData: input.noData,+ renotify: input.renotify,+ status: statusToPrisma(input.status),+ schedulerBatchId,+ nextRunAt,+ name: input.name,+ tags: input.tags,+ },+ });+ return monitorFromPrisma(created);+ }++ public static async update(input: UpdateMonitorInput): Promise<Monitor> {+ const filters = sortFiltersCanonically(input.filters);+ const windowMs = windowToMs(input.window);+ const cadenceMs = calculateCadence(windowMs);+ const schedulerBatchId = calculateSchedulerBatchId({+ projectId: input.projectId,+ view: input.view,+ filters,+ windowMs,+ });+ const nextRunAt = calculateLastRunAt(+ new Date(),+ cadenceMs,+ schedulerBatchId,+ );++ // Scheduler and QueueProcessor columns are intentionally not touched+ // (eg. severity, severityChangedAt, alertedAt, lastPublishedRunAt, lastCompletedRunAt).+ try {+ const updated = await prisma.monitor.update({+ where: { id: input.id, projectId: input.projectId },+ data: {+ updatedBy: input.updatedBy,+ view: viewToPrisma(input.view),+ filters,+ metric: input.metric,+ windowMs,+ cadenceMs,+ thresholdOperator: thresholdOperatorToPrisma(input.thresholdOperator),+ alertThreshold: new Prisma.Decimal(input.alertThreshold),+ warningThreshold: decimalToPrisma(input.warningThreshold),+ noData: input.noData,+ renotify: input.renotify,+ status: statusToPrisma(input.status),+ schedulerBatchId,+ nextRunAt,+ name: input.name,+ tags: input.tags,+ },+ });+ return monitorFromPrisma(updated);+ } catch (e) {+ throw errorFromPrisma(input.id, input.projectId, e);+ }+ }++ public static async getById(+ monitorId: string,+ projectId: string,+ ): Promise<Monitor | null> {+ const monitor = await prisma.monitor.findFirst({+ where: { id: monitorId, projectId },+ });+ return monitor ? monitorFromPrisma(monitor) : null;+ }++ public static async list(+ input: MonitorListInput,+ ): Promise<{ monitors: Monitor[]; totalCount: number }> {+ const skip =+ input.page && input.limit ? (input.page - 1) * input.limit : undefined;++ const sortOrder = input.orderBy?.order.toLowerCase();+ const orderByValue =+ input.orderBy && nullableOrderColumns.has(input.orderBy.column)+ ? { sort: sortOrder, nulls: "last" as const }+ : sortOrder;+ const [monitors, totalCount] = await Promise.all([+ prisma.monitor.findMany({+ where: { projectId: input.projectId },+ orderBy: input.orderBy+ ? [{ [input.orderBy.column]: orderByValue }, { id: "asc" }]+ : [{ severity: "desc" }, { id: "asc" }],+ skip,+ take: input.limit,+ }),+ prisma.monitor.count({ where: { projectId: input.projectId } }),+ ]);++ return { monitors: monitors.map(monitorFromPrisma), totalCount };+ }++ public static async delete(+ monitorId: string,+ projectId: string,+ ): Promise<void> {+ try {+ await prisma.monitor.delete({+ where: { id: monitorId, projectId },+ });+ } catch (e) {+ throw errorFromPrisma(monitorId, projectId, e);+ }+ }+}diff --git a/packages/shared/src/features/monitors/service/types.test.ts b/packages/shared/src/features/monitors/service/types.test.tsnew file mode 100644index 0000000000..76fef1e870--- /dev/null+++ b/packages/shared/src/features/monitors/service/types.test.ts@@ -0,0 +1,204 @@+import { describe, it, expect } from "vitest";++import {+ CreateMonitorInputSchema,+ MonitorListInputSchema,+ UpdateMonitorInputSchema,+} from "./types";++// Minimal valid `CreateMonitorInputSchema` payload. Tests override one field+// at a time to exercise the refinements wired onto the input schema.+const validCreateInput = {+ projectId: "proj_01",+ createdBy: null,++ view: "observations" as const,+ filters: [],+ metric: { measure: "count", aggregation: "count" as const },++ window: "5m" as const,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },+ status: "active" as const,++ name: "High error rate",+ tags: [],+};++const validUpdateInput = {+ ...validCreateInput,+ id: "mon_01",+ updatedBy: null,+};++describe("CreateMonitorInputSchema", () => {+ it("parses a minimal valid input", () => {+ expect(CreateMonitorInputSchema.safeParse(validCreateInput).success).toBe(+ true,+ );+ });++ it("rejects warning >= alert for gt (validateThresholdOrder is wired)", () => {+ const result = CreateMonitorInputSchema.safeParse({+ ...validCreateInput,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(result.success).toBe(false);+ });++ it.each(["gt", "gte"] as const)(+ "%s emits a `>` strict-ordering message (not the operator name)",+ (op) => {+ const result = CreateMonitorInputSchema.safeParse({+ ...validCreateInput,+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const message = result.error.issues[0].message;+ expect(message).toContain(">");+ // Must NOT interpolate the operator literal β `gte` would otherwise+ // produce the misleading "must be gte" (non-strict) phrasing.+ expect(message).not.toContain(op);+ }+ },+ );++ it.each(["lt", "lte"] as const)(+ "%s emits a `<` strict-ordering message (not the operator name)",+ (op) => {+ const result = CreateMonitorInputSchema.safeParse({+ ...validCreateInput,+ thresholdOperator: op,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ const message = result.error.issues[0].message;+ expect(message).toContain("<");+ expect(message).not.toContain(op);+ }+ },+ );++ it("rejects an unknown measure (validateQuery is wired)", () => {+ const result = CreateMonitorInputSchema.safeParse({+ ...validCreateInput,+ metric: { measure: "bogus_measure", aggregation: "count" as const },+ });+ expect(result.success).toBe(false);+ });++ it("rejects status `error-bad-query` on create (scheduler-owned)", () => {+ const result = CreateMonitorInputSchema.safeParse({+ ...validCreateInput,+ status: "error-bad-query",+ });+ expect(result.success).toBe(false);+ });+});++describe("UpdateMonitorInputSchema", () => {+ it("parses a minimal valid input", () => {+ expect(UpdateMonitorInputSchema.safeParse(validUpdateInput).success).toBe(+ true,+ );+ });++ it("rejects warning <= alert for lt (validateThresholdOrder is wired)", () => {+ const result = UpdateMonitorInputSchema.safeParse({+ ...validUpdateInput,+ thresholdOperator: "lt" as const,+ alertThreshold: 100,+ warningThreshold: 100,+ });+ expect(result.success).toBe(false);+ });++ it("rejects an unknown filter column (validateQuery is wired)", () => {+ const result = UpdateMonitorInputSchema.safeParse({+ ...validUpdateInput,+ filters: [+ {+ type: "string",+ column: "not_a_dimension",+ operator: "=",+ value: "x",+ },+ ],+ });+ expect(result.success).toBe(false);+ });++ it("rejects status `error-bad-query` on update (scheduler-owned)", () => {+ // `error-bad-query` is flipped by the scheduler when a monitor's query+ // fails to evaluate. Callers must not be able to set or clear it+ // directly β narrowing the input DTO to active/paused enforces that.+ const result = UpdateMonitorInputSchema.safeParse({+ ...validUpdateInput,+ status: "error-bad-query",+ });+ expect(result.success).toBe(false);+ });+});++describe("MonitorListInputSchema", () => {+ it("parses a minimal input with defaults filled in", () => {+ const result = MonitorListInputSchema.safeParse({+ projectId: "proj_01",+ orderBy: null,+ });+ expect(result.success).toBe(true);+ if (result.success) {+ expect(result.data.page).toBe(1);+ expect(result.data.limit).toBe(50);+ }+ });++ it("accepts an orderBy + explicit pagination", () => {+ const result = MonitorListInputSchema.safeParse({+ projectId: "proj_01",+ orderBy: { column: "name", order: "ASC" },+ page: 2,+ limit: 25,+ });+ expect(result.success).toBe(true);+ });++ it.each([+ "name",+ "status",+ "severity",+ "severityChangedAt",+ "alertedAt",+ "createdAt",+ "updatedAt",+ ] as const)("accepts %s as orderBy.column", (column) => {+ const result = MonitorListInputSchema.safeParse({+ projectId: "proj_01",+ orderBy: { column, order: "DESC" },+ });+ expect(result.success).toBe(true);+ });++ it("rejects an unknown orderBy.column (Prisma would otherwise raise a 500)", () => {+ const result = MonitorListInputSchema.safeParse({+ projectId: "proj_01",+ orderBy: { column: "bogus", order: "DESC" },+ });+ expect(result.success).toBe(false);+ });++ it("rejects a missing projectId", () => {+ const result = MonitorListInputSchema.safeParse({ orderBy: null });+ expect(result.success).toBe(false);+ });+});diff --git a/packages/shared/src/features/monitors/service/types.ts b/packages/shared/src/features/monitors/service/types.tsnew file mode 100644index 0000000000..2b8ced7feb--- /dev/null+++ b/packages/shared/src/features/monitors/service/types.ts@@ -0,0 +1,83 @@+/** service/types.ts contains the DTO schemas and types for the MonitorService+ * β the input contracts for `create`, `update`, and `list`. */+import { z } from "zod";++import { paginationZod } from "../../../utils/zod";++import {+ MonitorSchema,+ MonitorWriteStatusSchema,+ validateQuery,+ validateThresholdOrder,+} from "../types";++/**+ * omitOnWrite are the Monitor fields the service generates or owns. They are+ * omitted from every write DTO.+ */+const omitOnWrite = {+ createdAt: true,+ updatedAt: true,+ severity: true,+ severityChangedAt: true,+ alertedAt: true,+ nextRunAt: true,+ lastPublishedRunAt: true,+ lastCompletedRunAt: true,+} as const;++/**+ * CreateMonitorInputSchema is the input contract for `MonitorService.create`.+ * The caller supplies `createdBy`; the service mirrors it onto `updatedBy`.+ * `status` is narrowed to the caller-settable subset (`error-bad-query` is+ * scheduler-owned).+ */+export const CreateMonitorInputSchema = MonitorSchema.omit({+ ...omitOnWrite,+ id: true,+ updatedBy: true,+})+ .extend({ status: MonitorWriteStatusSchema.default("active") })+ .superRefine(validateQuery)+ .superRefine(validateThresholdOrder);+export type CreateMonitorInput = z.infer<typeof CreateMonitorInputSchema>;++/**+ * UpdateMonitorInputSchema is the input contract for `MonitorService.update`.+ * The caller supplies `id` (target row) and `updatedBy`; `createdBy` is+ * preserved from the existing row. `status` is narrowed to the+ * caller-settable subset.+ */+export const UpdateMonitorInputSchema = MonitorSchema.omit({+ ...omitOnWrite,+ createdBy: true,+})+ .extend({ status: MonitorWriteStatusSchema.default("active") })+ .superRefine(validateQuery)+ .superRefine(validateThresholdOrder);+export type UpdateMonitorInput = z.infer<typeof UpdateMonitorInputSchema>;++/** MonitorListOrderBySchema is the list of fields that we can sort the Monitor collection by. */+export const MonitorListOrderBySchema = z.enum([+ "name",+ "status",+ "severity",+ "severityChangedAt",+ "alertedAt",+ "createdAt",+ "updatedAt",+]);+export type MonitorListOrderBy = z.infer<typeof MonitorListOrderBySchema>;++/** MonitorListInputSchema is the input contract for `MonitorService.list`. */+export const MonitorListInputSchema = z.object({+ projectId: z.string(),+ orderBy: z+ .object({+ column: MonitorListOrderBySchema,+ order: z.enum(["ASC", "DESC"]),+ })+ .nullable(),+ ...paginationZod,+});+export type MonitorListInput = z.infer<typeof MonitorListInputSchema>;diff --git a/packages/shared/src/features/monitors/types.test.ts b/packages/shared/src/features/monitors/types.test.tsnew file mode 100644index 0000000000..ae6b507447--- /dev/null+++ b/packages/shared/src/features/monitors/types.test.ts@@ -0,0 +1,201 @@+import { describe, it, expect } from "vitest";++import {+ MonitorAlertSchema,+ MonitorNoDataSchema,+ MonitorRenotifySchema,+ MonitorSchema,+ MonitorWindowSchema,+} from "./types";++// Minimal valid domain object. Tests override one field at a time.+const validMonitorBase = {+ id: "mon_01",+ createdAt: new Date("2026-05-18T00:00:00.000Z"),+ updatedAt: new Date("2026-05-18T00:00:00.000Z"),+ createdBy: null,+ updatedBy: null,+ projectId: "proj_01",++ view: "observations" as const,+ filters: [],+ metric: { measure: "count", aggregation: "count" as const },++ window: "5m" as const,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: null,++ severity: "unknown" as const,+ severityChangedAt: null,++ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },++ status: "active" as const,+ nextRunAt: new Date("2026-05-18T00:01:00.000Z"),+ lastPublishedRunAt: null,+ lastCompletedRunAt: null,++ name: "High error rate",+ tags: [],+ alertedAt: null,+};++describe("MonitorWindowSchema", () => {+ it("accepts every MonitorWindow tier value", () => {+ for (const tier of MonitorWindowSchema.options) {+ expect(MonitorWindowSchema.safeParse(tier).success).toBe(true);+ }+ });++ it("rejects a value that isn't a known tier", () => {+ expect(MonitorWindowSchema.safeParse("bogus").success).toBe(false);+ });+});++describe("MonitorRenotifySchema", () => {+ it("accepts the OFF variant", () => {+ expect(MonitorRenotifySchema.safeParse({ mode: "OFF" }).success).toBe(true);+ });++ it("accepts the EVERY variant with a valid interval", () => {+ const result = MonitorRenotifySchema.safeParse({+ mode: "EVERY",+ intervalMinutes: 5,+ });+ expect(result.success).toBe(true);+ });++ it("rejects EVERY without intervalMinutes", () => {+ expect(MonitorRenotifySchema.safeParse({ mode: "EVERY" }).success).toBe(+ false,+ );+ });++ it("rejects intervalMinutes below 1", () => {+ expect(+ MonitorRenotifySchema.safeParse({ mode: "EVERY", intervalMinutes: 0 })+ .success,+ ).toBe(false);+ });++ it("rejects intervalMinutes above one week", () => {+ expect(+ MonitorRenotifySchema.safeParse({+ mode: "EVERY",+ intervalMinutes: 60 * 24 * 7 + 1,+ }).success,+ ).toBe(false);+ });++ it("rejects an unknown discriminator", () => {+ expect(+ MonitorRenotifySchema.safeParse({+ mode: "BOGUS",+ intervalMinutes: 5,+ }).success,+ ).toBe(false);+ });+});++describe("MonitorNoDataSchema", () => {+ it("accepts the SILENT variant", () => {+ expect(MonitorNoDataSchema.safeParse({ mode: "SILENT" }).success).toBe(+ true,+ );+ });++ it("accepts the NOTIFY variant with a valid interval", () => {+ const result = MonitorNoDataSchema.safeParse({+ mode: "NOTIFY",+ intervalMinutes: 5,+ });+ expect(result.success).toBe(true);+ });++ it("rejects NOTIFY without intervalMinutes", () => {+ expect(MonitorNoDataSchema.safeParse({ mode: "NOTIFY" }).success).toBe(+ false,+ );+ });++ it("rejects intervalMinutes below 1", () => {+ expect(+ MonitorNoDataSchema.safeParse({ mode: "NOTIFY", intervalMinutes: 0 })+ .success,+ ).toBe(false);+ });++ it("rejects intervalMinutes above one day", () => {+ expect(+ MonitorNoDataSchema.safeParse({+ mode: "NOTIFY",+ intervalMinutes: 60 * 24 + 1,+ }).success,+ ).toBe(false);+ });++ it("rejects an unknown discriminator", () => {+ expect(+ MonitorNoDataSchema.safeParse({+ mode: "BOGUS",+ intervalMinutes: 5,+ }).success,+ ).toBe(false);+ });+});++describe("MonitorSchema", () => {+ it("parses a minimally valid Monitor", () => {+ const result = MonitorSchema.safeParse(validMonitorBase);+ expect(result.success).toBe(true);+ });+});++describe("MonitorAlertSchema", () => {+ const validAlert = {+ monitorId: "mon_01",+ projectId: "proj_01",+ severity: "alert" as const,+ permalink: "https://cloud.langfuse.com/project/proj_01/monitors/mon_01",+ timestamp: new Date("2026-05-18T12:01:00.000Z"),+ message: { title: "High error rate", body: "errors > 100" },+ view: "observations" as const,+ filters: [],+ window: "5m" as const,+ };++ it("parses a representative alert", () => {+ expect(MonitorAlertSchema.safeParse(validAlert).success).toBe(true);+ });++ it("rejects a non-URL permalink", () => {+ expect(+ MonitorAlertSchema.safeParse({ ...validAlert, permalink: "not-a-url" })+ .success,+ ).toBe(false);+ });++ it("rejects an unknown severity", () => {+ expect(+ MonitorAlertSchema.safeParse({ ...validAlert, severity: "BOGUS" })+ .success,+ ).toBe(false);+ });++ it("rejects a window outside the MonitorWindow tier set", () => {+ expect(+ MonitorAlertSchema.safeParse({ ...validAlert, window: "bogus" }).success,+ ).toBe(false);+ });++ it("coerces a string timestamp to a Date", () => {+ const result = MonitorAlertSchema.safeParse({+ ...validAlert,+ timestamp: "2026-05-18T12:01:00.000Z",+ });+ expect(result.success).toBe(true);+ if (result.success) expect(result.data.timestamp).toBeInstanceOf(Date);+ });+});diff --git a/packages/shared/src/features/monitors/types.ts b/packages/shared/src/features/monitors/types.tsnew file mode 100644index 0000000000..ad499ba33b--- /dev/null+++ b/packages/shared/src/features/monitors/types.ts@@ -0,0 +1,241 @@+/** types.ts contains the monitor domain β schemas, types, and the+ * `validate*` refinements consumed by the input schemas. */+import { z } from "zod";++import { singleFilter } from "../../interfaces/filters";+import { metric as MetricSchema, viewsV2 } from "../query/types";++import { isValidQuery } from "./isValidQuery";+import { isValidThresholdOrder } from "./isValidThresholdOrder";++/**+ * MonitorFiltersSchema is the array of filters applied to a Monitor's+ * underlying query β a thin alias over `singleFilter[]` so all Monitor+ * schemas reference one source of truth.+ */+export const MonitorFiltersSchema = z.array(singleFilter);+export type MonitorFilters = z.infer<typeof MonitorFiltersSchema>;++/**+ * MonitorSeveritySchema is the kebab-case wire form of Prisma's+ * `MonitorSeverity` enum. The service translates between this and Prisma at+ * the persistence boundary.+ */+export const MonitorSeveritySchema = z.enum([+ "unknown",+ "no-data",+ "ok",+ "warning",+ "alert",+]);+export type MonitorSeverity = z.infer<typeof MonitorSeveritySchema>;++/**+ * MonitorStatusSchema is the kebab-case wire form of Prisma's `MonitorStatus`+ * enum.+ */+export const MonitorStatusSchema = z.enum([+ "paused",+ "active",+ "error-bad-query",+]);+export type MonitorStatus = z.infer<typeof MonitorStatusSchema>;++/**+ * MonitorWriteStatusSchema is the subset of `MonitorStatusSchema` callers may+ * submit on create/update. `error-bad-query` is owned by the scheduler/worker+ * (flipped when a monitor's query fails to evaluate); accepting it on inputs+ * would let callers forge a broken state or clear a legitimately broken+ * monitor without scheduler revalidation.+ */+export const MonitorWriteStatusSchema = z.enum(["active", "paused"]);+export type MonitorWriteStatus = z.infer<typeof MonitorWriteStatusSchema>;++/**+ * MonitorThresholdOperatorSchema is the kebab-case wire form of Prisma's+ * `MonitorThresholdOperator` enum.+ */+export const MonitorThresholdOperatorSchema = z.enum([+ "gt",+ "gte",+ "lt",+ "lte",+ "eq",+ "neq",+]);+export type MonitorThresholdOperator = z.infer<+ typeof MonitorThresholdOperatorSchema+>;++/**+ * MonitorWindowSchema is the kebab-case wire form of a Monitor evaluation+ * window. The service translates between this and a bigint of milliseconds+ * (the Prisma `windowMs` column) at the persistence boundary.+ */+export const MonitorWindowSchema = z.enum([+ "5m",+ "10m",+ "15m",+ "30m",+ "1h",+ "2h",+ "4h",+ "1d",+ "2d",+ "1w",+]);+export type MonitorWindow = z.infer<typeof MonitorWindowSchema>;++/**+ * MonitorViewSchema is an alias of the query `viewsV2` schema.+ */+export const MonitorViewSchema = viewsV2;+export type MonitorView = z.infer<typeof MonitorViewSchema>;++/**+ * MonitorRenotifySchema describes renotify behavior for a sustained severity.+ * `OFF` is edge-only; `EVERY` re-emits every `intervalMinutes` while the+ * severity persists.+ */+export const MonitorRenotifySchema = z.discriminatedUnion("mode", [+ z.object({ mode: z.literal("OFF") }),+ z.object({+ mode: z.literal("EVERY"),+ intervalMinutes: z+ .number()+ .int()+ .min(1)+ .max(60 * 24 * 7),+ }),+]);+export type MonitorRenotify = z.infer<typeof MonitorRenotifySchema>;++/**+ * MonitorNoDataSchema describes behavior when a Monitor query returns no rows.+ * `SILENT` only alerts on recovery; `NOTIFY` also alerts after+ * `intervalMinutes` of sustained NO_DATA.+ */+export const MonitorNoDataSchema = z.discriminatedUnion("mode", [+ z.object({ mode: z.literal("SILENT") }),+ z.object({+ mode: z.literal("NOTIFY"),+ intervalMinutes: z+ .number()+ .int()+ .min(1)+ .max(60 * 24),+ }),+]);+export type MonitorNoData = z.infer<typeof MonitorNoDataSchema>;++/**+ * validateThresholdOrder enforces correct warning/alert threshold ordering on+ * the Monitor input schemas.+ */+export const validateThresholdOrder = (+ input: {+ thresholdOperator: MonitorThresholdOperator;+ alertThreshold: number;+ warningThreshold: number | null;+ },+ ctx: z.RefinementCtx,+): void => {+ if (!isValidThresholdOrder(input)) {+ // For gt/gte the predicate requires `warning < alert` (strict);+ // for lt/lte it requires `warning > alert` (strict). Map to the actual+ // required relation symbol so the error message doesn't claim the+ // non-strict variant for `gte`/`lte`.+ const symbol = input.thresholdOperator.startsWith("g") ? ">" : "<";+ ctx.addIssue({+ code: "custom",+ message: `alertThreshold must be ${symbol} warningThreshold`,+ path: ["threshold"],+ });+ }+};++/**+ * validateQuery enforces a valid (view, metric, filters) shape on the Monitor+ * input schemas.+ */+export const validateQuery = (+ input: {+ view: z.infer<typeof viewsV2>;+ metric: z.infer<typeof MetricSchema>;+ filters: MonitorFilters;+ },+ ctx: z.RefinementCtx,+): void => {+ const result = isValidQuery({+ view: input.view,+ metric: input.metric,+ filters: input.filters,+ });+ if (!result.valid) {+ ctx.addIssue({+ code: "custom",+ message: result.reason,+ path: ["query"],+ });+ }+};++/**+ * MonitorSchema is the Monitor domain object. It mirrors the Prisma `Monitor`+ * row.+ */+export const MonitorSchema = z.object({+ id: z.string(),+ createdAt: z.date(),+ updatedAt: z.date(),+ createdBy: z.string().nullable(),+ updatedBy: z.string().nullable(),+ projectId: z.string(),++ // Query Config+ view: MonitorViewSchema,+ filters: MonitorFiltersSchema,+ metric: MetricSchema,++ // Monitor Config+ window: MonitorWindowSchema,+ thresholdOperator: MonitorThresholdOperatorSchema,+ alertThreshold: z.number(),+ warningThreshold: z.number().nullable(),+ noData: MonitorNoDataSchema.default({ mode: "SILENT" }),+ renotify: MonitorRenotifySchema.default({ mode: "OFF" }),++ // MonitorAlert Config+ name: z.string().min(1).max(200),+ tags: z.array(z.string().max(60)).max(20).default([]),++ // Monitor State+ severity: MonitorSeveritySchema.default("unknown"),+ severityChangedAt: z.date().nullable(),+ alertedAt: z.date().nullable(),++ // MonitorScheduler State+ status: MonitorStatusSchema.default("active"),+ nextRunAt: z.date(),+ lastPublishedRunAt: z.date().nullable(),+ lastCompletedRunAt: z.date().nullable(),+});+export type Monitor = z.infer<typeof MonitorSchema>;++/**+ * MonitorAlertSchema is emitted when a monitor alerts. It carries the query+ * shape (`view` / `filters` / `window`) alongside the rendered message so+ * that recipients can reconstruct the underlying observations / scores query.+ */+export const MonitorAlertSchema = z.object({+ monitorId: z.string(),+ projectId: z.string(),+ permalink: z.url(),+ message: z.object({ title: z.string(), body: z.string() }),+ severity: MonitorSeveritySchema,+ timestamp: z.coerce.date(),+ view: MonitorViewSchema,+ filters: MonitorFiltersSchema,+ window: MonitorWindowSchema,+});+export type MonitorAlert = z.infer<typeof MonitorAlertSchema>;diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 409b0d3f5e..87053886fe 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -113,6 +113,7 @@ export * from "./redis/llmAsJudgeExecutionQueue";export * from "./services/sessions-ui-table-service";export * from "./services/sessions-ui-table-events-service";export * from "./services/DashboardService";+export * from "../features/monitors/server";export * from "./services/TableViewService";export * from "./services/DefaultViewService";export * from "./services/DefaultEvaluationModelService";diff --git a/packages/shared/vitest.config.ts b/packages/shared/vitest.config.tsnew file mode 100644index 0000000000..6fd890bdb5--- /dev/null+++ b/packages/shared/vitest.config.ts@@ -0,0 +1,9 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ test: {+ dir: "./src",+ include: ["**/*.test.ts"],+ pool: "forks",+ },+});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex e291402f94..d4184f19ea 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -345,6 +345,9 @@ importers:typescript:specifier: ^5.7.2version: 5.9.2+ vitest:+ specifier: ^4.1.4+ version: 4.1.4(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))web:dependencies:diff --git a/web/src/__tests__/server/monitorService.servertest.ts b/web/src/__tests__/server/monitorService.servertest.tsnew file mode 100644index 0000000000..b913f98764--- /dev/null+++ b/web/src/__tests__/server/monitorService.servertest.ts@@ -0,0 +1,299 @@+import { v4 as uuidv4 } from "uuid";+import {+ createOrgProjectAndApiKey,+ MonitorService,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";+import { InvalidRequestError } from "@langfuse/shared";++const baseCreateInput = (+ projectId: string,+ createdBy: string | null = null,+) => ({+ projectId,+ createdBy,+ view: "observations" as const,+ filters: [],+ metric: { measure: "count", aggregation: "count" as const },+ window: "5m" as const,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },+ status: "active" as const,+ name: "High error rate",+ tags: [],+});++const baseUpdateInput = (+ projectId: string,+ updatedBy: string | null = null,+) => ({+ projectId,+ updatedBy,+ view: "observations" as const,+ filters: [],+ metric: { measure: "count", aggregation: "count" as const },+ window: "5m" as const,+ thresholdOperator: "gt" as const,+ alertThreshold: 100,+ warningThreshold: null,+ noData: { mode: "SILENT" as const },+ renotify: { mode: "OFF" as const },+ status: "active" as const,+ name: "High error rate",+ tags: [],+});++describe("MonitorService (integration)", () => {+ let projectId: string;+ let creatorUserId: string;+ let editorUserId: string;++ beforeAll(async () => {+ const org = await createOrgProjectAndApiKey();+ projectId = org.projectId;+ const creator = await prisma.user.create({+ data: {+ id: uuidv4(),+ email: `monitor-creator-${uuidv4().substring(0, 8)}@test.com`,+ name: "Creator",+ },+ });+ const editor = await prisma.user.create({+ data: {+ id: uuidv4(),+ email: `monitor-editor-${uuidv4().substring(0, 8)}@test.com`,+ name: "Editor",+ },+ });+ creatorUserId = creator.id;+ editorUserId = editor.id;+ });++ afterEach(async () => {+ await prisma.monitor.deleteMany({ where: { projectId } });+ });++ describe("create", () => {+ it("creates a monitor and persists derived fields", async () => {+ const created = await MonitorService.create(baseCreateInput(projectId));++ const row = await prisma.monitor.findUnique({+ where: { id: created.id },+ });+ expect(row).not.toBeNull();+ expect(row!.windowMs).toBe(5n * 60_000n);+ // "5m" is a sub-day window β 1-minute cadence.+ expect(row!.cadenceMs).toBe(60_000n);+ expect(row!.schedulerBatchId).toBeGreaterThan(0n);+ expect(row!.nextRunAt.getTime()).toBeLessThanOrEqual(Date.now());+ expect(row!.severity).toBe("UNKNOWN");+ });++ it("canonicalizes filter order so permutations share the same schedulerBatchId", async () => {+ const filterA = {+ column: "environment" as const,+ operator: "=" as const,+ value: "production",+ type: "string" as const,+ };+ const filterB = {+ column: "name" as const,+ operator: "=" as const,+ value: "faq-bot",+ type: "string" as const,+ };++ const first = await MonitorService.create({+ ...baseCreateInput(projectId),+ filters: [filterA, filterB],+ });+ const second = await MonitorService.create({+ ...baseCreateInput(projectId),+ filters: [filterB, filterA],+ });++ const rows = await prisma.monitor.findMany({+ where: { id: { in: [first.id, second.id] } },+ });+ expect(rows).toHaveLength(2);+ expect(rows[0].schedulerBatchId).toBe(rows[1].schedulerBatchId);+ });++ it("yields a different schedulerBatchId for different projects", async () => {+ const otherOrg = await createOrgProjectAndApiKey();+ const otherProject = otherOrg.projectId;++ const here = await MonitorService.create(baseCreateInput(projectId));+ const there = await MonitorService.create(baseCreateInput(otherProject));++ const rows = await prisma.monitor.findMany({+ where: { id: { in: [here.id, there.id] } },+ });+ const idHere = rows.find((r) => r.id === here.id)!.schedulerBatchId;+ const idThere = rows.find((r) => r.id === there.id)!.schedulerBatchId;+ expect(idHere).not.toBe(idThere);++ await prisma.monitor.deleteMany({ where: { projectId: otherProject } });+ });+ });++ describe("update", () => {+ it("updates user-editable fields and preserves worker-owned lifecycle state", async () => {+ const created = await MonitorService.create(+ baseCreateInput(projectId, creatorUserId),+ );++ // Simulate the worker writing lifecycle state between create and update.+ await prisma.monitor.update({+ where: { id: created.id },+ data: {+ severity: "ALERT",+ severityChangedAt: new Date(),+ alertedAt: new Date(),+ lastCompletedRunAt: new Date(),+ },+ });++ const updated = await MonitorService.update({+ ...baseUpdateInput(projectId, editorUserId),+ id: created.id,+ name: "Renamed",+ });++ expect(updated.name).toBe("Renamed");+ expect(updated.severity).toBe("alert");+ expect(updated.severityChangedAt).not.toBeNull();+ expect(updated.alertedAt).not.toBeNull();+ expect(updated.lastCompletedRunAt).not.toBeNull();++ const row = await prisma.monitor.findUnique({+ where: { id: created.id },+ });+ expect(row!.createdBy).toBe(creatorUserId);+ expect(row!.updatedBy).toBe(editorUserId);+ });++ it("throws InvalidRequestError when the monitor does not exist", async () => {+ await expect(+ MonitorService.update({+ ...baseUpdateInput(projectId),+ id: "mon_missing",+ }),+ ).rejects.toBeInstanceOf(InvalidRequestError);+ });+ });++ describe("getById / list / delete", () => {+ it("returns the monitor by id within the project", async () => {+ const created = await MonitorService.create(baseCreateInput(projectId));+ const fetched = await MonitorService.getById(created.id, projectId);+ expect(fetched?.id).toBe(created.id);+ });++ it("returns null when fetching from a different project", async () => {+ const created = await MonitorService.create(baseCreateInput(projectId));+ const fetched = await MonitorService.getById(created.id, "other_project");+ expect(fetched).toBeNull();+ });++ it("paginates list results", async () => {+ for (let i = 0; i < 3; i++) {+ await MonitorService.create({+ ...baseCreateInput(projectId),+ name: `M${i}`,+ });+ }+ const page = await MonitorService.list({+ projectId,+ orderBy: null,+ limit: 2,+ page: 1,+ });+ expect(page.totalCount).toBe(3);+ expect(page.monitors).toHaveLength(2);+ });++ it("deletes a monitor", async () => {+ const created = await MonitorService.create(baseCreateInput(projectId));+ await MonitorService.delete(created.id, projectId);+ const fetched = await MonitorService.getById(created.id, projectId);+ expect(fetched).toBeNull();+ });++ it.each(["name", "status", "severity", "createdAt", "updatedAt"] as const)(+ "lists by %s (non-nullable column) without a PrismaClientValidationError",+ async (column) => {+ // Verifies whether Prisma accepts `{ sort, nulls: "last" }` on+ // non-nullable columns. If it doesn't, this throws+ // PrismaClientValidationError at runtime and we need to gate `nulls`+ // on the nullable subset instead.+ await MonitorService.create(baseCreateInput(projectId));+ const result = await MonitorService.list({+ projectId,+ orderBy: { column, order: "ASC" },+ page: 1,+ limit: 10,+ });+ expect(result.monitors.length).toBeGreaterThan(0);+ },+ );++ it.each(["alertedAt", "severityChangedAt"] as const)(+ "sorts %s with NULLS LAST regardless of direction",+ async (column) => {+ const dbColumn =+ column === "alertedAt" ? "alertedAt" : "severityChangedAt";++ // Three monitors: one never-touched (NULL), one older, one newer.+ const neverTouched = await MonitorService.create({+ ...baseCreateInput(projectId),+ name: "never",+ });+ const older = await MonitorService.create({+ ...baseCreateInput(projectId),+ name: "older",+ });+ const newer = await MonitorService.create({+ ...baseCreateInput(projectId),+ name: "newer",+ });++ await prisma.monitor.update({+ where: { id: older.id },+ data: { [dbColumn]: new Date("2026-01-01T00:00:00.000Z") },+ });+ await prisma.monitor.update({+ where: { id: newer.id },+ data: { [dbColumn]: new Date("2026-06-01T00:00:00.000Z") },+ });++ const desc = await MonitorService.list({+ projectId,+ orderBy: { column, order: "DESC" },+ page: 1,+ limit: 10,+ });+ expect(desc.monitors.map((m) => m.id)).toEqual([+ newer.id,+ older.id,+ neverTouched.id,+ ]);++ const asc = await MonitorService.list({+ projectId,+ orderBy: { column, order: "ASC" },+ page: 1,+ limit: 10,+ });+ expect(asc.monitors.map((m) => m.id)).toEqual([+ older.id,+ newer.id,+ neverTouched.id,+ ]);+ },+ );+ });+});