@langwatch/server 3.4.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,193 @@
1
+ /**
2
+ * @vitest-environment node
3
+ *
4
+ * HTTP-level integration test for POST /api/ops/clickhouse/explain.
5
+ *
6
+ * This is the test that should exist from day one — the previous round
7
+ * used `handler(req, res)` direct invocation which sailed past the fact
8
+ * that the route was never bound to a real HTTP path. We import the FULL
9
+ * api-router (not just the ops route module) and exercise it via
10
+ * `router.request()` so a missing `api.route("/", opsApp)` in
11
+ * api-router.ts would show up as a 404 here instead of a green CI and a
12
+ * 404 in production.
13
+ *
14
+ * ClickHouse comes from @testcontainers/clickhouse (same image and
15
+ * .withReuse() pattern as src/server/clickhouse/__tests__/
16
+ * clickhouseClient.integration.test.ts).
17
+ */
18
+ import {
19
+ ClickHouseContainer,
20
+ type StartedClickHouseContainer,
21
+ } from "@testcontainers/clickhouse";
22
+ import { afterAll, beforeAll, describe, expect, it } from "vitest";
23
+
24
+ import { _resetOpsClickHouseClientForTesting } from "~/server/ops/explain-core";
25
+ import { createApiRouter } from "~/server/api-router";
26
+
27
+ const API_KEY = "integration-test-key";
28
+ let container: StartedClickHouseContainer;
29
+ let router: ReturnType<typeof createApiRouter>;
30
+
31
+ async function post(path: string, body: unknown, headers: Record<string, string> = {}) {
32
+ return router.request(path, {
33
+ method: "POST",
34
+ headers: {
35
+ "content-type": "application/json",
36
+ authorization: `Bearer ${API_KEY}`,
37
+ ...headers,
38
+ },
39
+ body: JSON.stringify(body),
40
+ });
41
+ }
42
+
43
+ describe("POST /api/ops/clickhouse/explain (HTTP integration)", () => {
44
+ beforeAll(async () => {
45
+ container = await new ClickHouseContainer("clickhouse/clickhouse-server:25.10.2.65")
46
+ .withLabels({ "langwatch.test.ops-explain": "http" })
47
+ .withReuse()
48
+ .withStartupTimeout(120_000)
49
+ .start();
50
+ const url = container.getConnectionUrl();
51
+ const { createClient } = await import("@clickhouse/client");
52
+ const c = createClient({ url });
53
+ await c.command({ query: "CREATE DATABASE IF NOT EXISTS langwatch" });
54
+ await c.command({
55
+ query: `CREATE TABLE IF NOT EXISTS langwatch.stored_spans (
56
+ TenantId String,
57
+ SpanId String,
58
+ OccurredAt DateTime,
59
+ SpanAttributes Map(String, String)
60
+ ) ENGINE = MergeTree() ORDER BY (TenantId, OccurredAt)`,
61
+ });
62
+ await c.close();
63
+
64
+ process.env.LANGWATCH_OPS_API_KEY = API_KEY;
65
+ process.env.CLICKHOUSE_OPS_URL = url;
66
+ process.env.NODE_ENV = "test";
67
+ _resetOpsClickHouseClientForTesting();
68
+
69
+ // Built AFTER env is set so the route module reads the right values
70
+ // on first init.
71
+ router = createApiRouter();
72
+ }, 300_000);
73
+
74
+ afterAll(() => {
75
+ delete process.env.LANGWATCH_OPS_API_KEY;
76
+ delete process.env.CLICKHOUSE_OPS_URL;
77
+ _resetOpsClickHouseClientForTesting();
78
+ });
79
+
80
+ it("is mounted at /api/ops/clickhouse/explain and serves EXPLAIN PLAN rows", async () => {
81
+ const res = await post("/api/ops/clickhouse/explain", {
82
+ query: "SELECT count() FROM langwatch.stored_spans WHERE TenantId = 'p_test'",
83
+ type: "PLAN",
84
+ });
85
+ expect(res.status).toBe(200);
86
+ const body = (await res.json()) as any;
87
+ expect(body.type).toBe("PLAN");
88
+ expect(Array.isArray(body.rows)).toBe(true);
89
+ expect(body.rows.length).toBeGreaterThan(0);
90
+ });
91
+
92
+ it("accepts a cross-tenant query — operator endpoint by design", async () => {
93
+ const res = await post("/api/ops/clickhouse/explain", {
94
+ query: "SELECT count() FROM langwatch.stored_spans",
95
+ });
96
+ expect(res.status).toBe(200);
97
+ });
98
+
99
+ it("honours the EXPLAIN type (PIPELINE returns different rows than PLAN)", async () => {
100
+ const plan = await post("/api/ops/clickhouse/explain", {
101
+ query: "SELECT TenantId, count() FROM langwatch.stored_spans GROUP BY TenantId",
102
+ type: "PLAN",
103
+ });
104
+ const pipe = await post("/api/ops/clickhouse/explain", {
105
+ query: "SELECT TenantId, count() FROM langwatch.stored_spans GROUP BY TenantId",
106
+ type: "PIPELINE",
107
+ });
108
+ expect(plan.status).toBe(200);
109
+ expect(pipe.status).toBe(200);
110
+ const planBody = await plan.json();
111
+ const pipeBody = await pipe.json();
112
+ expect(JSON.stringify(pipeBody)).not.toBe(JSON.stringify(planBody));
113
+ });
114
+
115
+ it("rejects a multi-statement query at the input filter (never reaches CH)", async () => {
116
+ const res = await post("/api/ops/clickhouse/explain", {
117
+ query: "SELECT 1 FROM langwatch.stored_spans WHERE TenantId='x'; DROP TABLE langwatch.stored_spans",
118
+ });
119
+ expect(res.status).toBe(400);
120
+ expect((await res.json()).message).toMatch(/single statement/i);
121
+ });
122
+
123
+ it("rejects a table function (SSRF surface)", async () => {
124
+ const res = await post("/api/ops/clickhouse/explain", {
125
+ query: "SELECT * FROM url('http://evil.example/x', CSV, 'a String') WHERE TenantId = 'p_x'",
126
+ });
127
+ expect(res.status).toBe(400);
128
+ expect((await res.json()).message).toMatch(/table function/i);
129
+ });
130
+
131
+ it("rejects the string-vs-comment ordering bypass end-to-end", async () => {
132
+ const res = await post("/api/ops/clickhouse/explain", {
133
+ query: `SELECT * FROM langwatch.stored_spans WHERE '/*' = 'literal' OR SpanId IN (SELECT SpanId FROM url('http://127.0.0.1:9/', CSV)) /* trailing */`,
134
+ });
135
+ expect(res.status).toBe(400);
136
+ expect((await res.json()).message).toMatch(/table function/i);
137
+ });
138
+
139
+ it("rejects the system.* schema", async () => {
140
+ const res = await post("/api/ops/clickhouse/explain", { query: "SELECT * FROM system.parts" });
141
+ expect(res.status).toBe(400);
142
+ expect((await res.json()).message).toMatch(/system/i);
143
+ });
144
+
145
+ it("returns 401 without the API key", async () => {
146
+ const res = await router.request("/api/ops/clickhouse/explain", {
147
+ method: "POST",
148
+ headers: { "content-type": "application/json" },
149
+ body: JSON.stringify({ query: "SELECT 1 FROM langwatch.stored_spans WHERE TenantId='x'" }),
150
+ });
151
+ expect(res.status).toBe(401);
152
+ });
153
+
154
+ it("returns 401 with a wrong API key", async () => {
155
+ const res = await post(
156
+ "/api/ops/clickhouse/explain",
157
+ { query: "SELECT 1 FROM langwatch.stored_spans WHERE TenantId='x'" },
158
+ { authorization: "Bearer totally-wrong" },
159
+ );
160
+ expect(res.status).toBe(401);
161
+ });
162
+
163
+ it("returns 405 / does not POST-handle on GET", async () => {
164
+ const res = await router.request("/api/ops/clickhouse/explain", {
165
+ method: "GET",
166
+ headers: { authorization: `Bearer ${API_KEY}` },
167
+ });
168
+ // Hono returns 404 for an unmatched method on an existing path by default;
169
+ // either way the POST handler must NOT run.
170
+ expect([404, 405]).toContain(res.status);
171
+ });
172
+
173
+ it("returns 502 on a syntactically valid SELECT against a missing table", async () => {
174
+ const res = await post("/api/ops/clickhouse/explain", {
175
+ query: "SELECT 1 FROM langwatch.does_not_exist_table WHERE TenantId='x'",
176
+ });
177
+ expect(res.status).toBe(502);
178
+ expect((await res.json()).message).toMatch(/ClickHouse error/i);
179
+ });
180
+
181
+ it("realistic arrayJoin shape the optimizer agent actually runs", async () => {
182
+ const res = await post("/api/ops/clickhouse/explain", {
183
+ query: `SELECT arrayJoin(mapKeys(SpanAttributes)) AS key, count() AS n
184
+ FROM langwatch.stored_spans
185
+ WHERE OccurredAt > now() - INTERVAL 1 DAY
186
+ GROUP BY key ORDER BY n DESC LIMIT 50`,
187
+ type: "PLAN",
188
+ });
189
+ expect(res.status).toBe(200);
190
+ const body = (await res.json()) as any;
191
+ expect(body.rows.length).toBeGreaterThan(0);
192
+ });
193
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Hono route for the operator-only /api/ops/clickhouse/explain endpoint.
3
+ *
4
+ * Lets the clickhouse-optimizer agent run EXPLAIN against the live
5
+ * ClickHouse instance the app is connected to. Defenses, outermost to
6
+ * innermost:
7
+ *
8
+ * 1. API key auth (LANGWATCH_OPS_API_KEY), constant-time compared.
9
+ * 2. Query normalization (single CH-aware lexer) — bypasses like
10
+ * `url/**\/('http://x')` and `'/*' = 'x' OR ... url(...)` can't
11
+ * evade the regex pass.
12
+ * 3. Input regex filter on the normalized text — table-function
13
+ * deny-list, SYSTEM_SCHEMA guard, multi-statement guard,
14
+ * forbidden-keyword guard. Tenant scoping is NOT enforced here
15
+ * on purpose: the optimizer agent legitimately runs cross-tenant
16
+ * EXPLAINs across the fleet.
17
+ * 4. Server-side EXPLAIN wrapping — the caller's SQL never reaches
18
+ * CH unwrapped.
19
+ * 5. EXPLAIN type allowlist — ANALYZE is blocked (it would execute
20
+ * the inner query).
21
+ * 6. Dedicated langwatch_ops CH user (via CLICKHOUSE_OPS_URL) with
22
+ * only `GRANT SELECT ON langwatch.*` and no SOURCES grant. **In
23
+ * production we fail closed with 503 when this env var is unset**
24
+ * so the regex filter is never the only line of defense.
25
+ * 7. Per-query CH settings: readonly=1 + 10s exec cap + 10MB result
26
+ * cap + 1GB memory cap.
27
+ * 8. Audit log of every accepted request — redacted shape + sha256
28
+ * prefix, raw literals stripped so logs aren't a PII sink.
29
+ *
30
+ * History note: this used to live at src/pages/api/ops/clickhouse/explain.ts
31
+ * back when the app was Next.js. After the move to a Hono-based service,
32
+ * the file kept compiling but was never bound to an HTTP path, so the
33
+ * endpoint silently 404'd in production despite green unit + integration
34
+ * tests (the tests invoked the handler function directly instead of going
35
+ * through HTTP). This version is registered in api-router.ts and the
36
+ * integration test issues real HTTP requests.
37
+ */
38
+ import { timingSafeEqual } from "node:crypto";
39
+ import {
40
+ createServiceApp,
41
+ handlerManagedAuth,
42
+ } from "~/server/api/security";
43
+ import { getSharedClickHouseClient } from "~/server/clickhouse/clickhouseClient";
44
+ import { createLogger } from "~/utils/logger/server";
45
+ import {
46
+ buildExplainQuery,
47
+ CLICKHOUSE_GUARDRAILS,
48
+ consumeMissingOpsUrlWarning,
49
+ explainBodySchema,
50
+ getOpsClickHouseClient,
51
+ redactQueryForAudit,
52
+ } from "~/server/ops/explain-core";
53
+
54
+ const logger = createLogger("langwatch:ops:clickhouse:explain");
55
+
56
+ function bearerTokenMatches(headerValue: string | undefined, expected: string): boolean {
57
+ if (!headerValue) return false;
58
+ const m = /^Bearer\s+(.+)$/i.exec(headerValue.trim());
59
+ if (!m?.[1]) return false;
60
+ const presented = m[1].trim();
61
+ const a = Buffer.from(presented);
62
+ const b = Buffer.from(expected);
63
+ if (a.length !== b.length) return false;
64
+ return timingSafeEqual(a, b);
65
+ }
66
+
67
+ const secured = createServiceApp({ basePath: "/api" });
68
+
69
+ secured
70
+ .access(
71
+ handlerManagedAuth(
72
+ "Bearer LANGWATCH_OPS_API_KEY constant-time compared; missing or wrong key returns 401. Operator-only endpoint for the clickhouse-optimizer agent.",
73
+ ),
74
+ )
75
+ .post("/ops/clickhouse/explain", async (c) => {
76
+ const expected = process.env.LANGWATCH_OPS_API_KEY;
77
+ if (!expected) {
78
+ // Fail closed when not configured.
79
+ return c.json({ message: "Unauthorized" }, 401);
80
+ }
81
+ if (!bearerTokenMatches(c.req.header("authorization"), expected)) {
82
+ return c.json({ message: "Unauthorized" }, 401);
83
+ }
84
+
85
+ let body: unknown;
86
+ try {
87
+ body = await c.req.json();
88
+ } catch {
89
+ return c.json({ message: "request body must be JSON" }, 400);
90
+ }
91
+ const parsed = explainBodySchema.safeParse(body);
92
+ if (!parsed.success) {
93
+ const issue = parsed.error.issues[0];
94
+ const path = issue?.path?.length ? `${issue.path.join(".")}: ` : "";
95
+ return c.json({ message: `${path}${issue?.message ?? "invalid body"}` }, 400);
96
+ }
97
+
98
+ const built = buildExplainQuery(parsed.data.query, parsed.data.type);
99
+ if (!built.ok) {
100
+ return c.json({ message: built.reason }, 400);
101
+ }
102
+
103
+ // Prefer the dedicated langwatch_ops user (no SOURCES grant, so url/s3/
104
+ // remote/file/postgresql table functions are refused at the access-check
105
+ // layer). In PRODUCTION, fail closed when CLICKHOUSE_OPS_URL is unset.
106
+ let client = getOpsClickHouseClient();
107
+ let usingFallback = false;
108
+ if (!client) {
109
+ if (process.env.NODE_ENV === "production") {
110
+ logger.error(
111
+ "CLICKHOUSE_OPS_URL is not set in production — refusing to fall back to the default-user client. " +
112
+ "Provision the langwatch_ops user (see infrastructure/clickhouse-serverless/config/users.xml.template) " +
113
+ "and set CLICKHOUSE_OPS_URL.",
114
+ );
115
+ return c.json(
116
+ {
117
+ message:
118
+ "ClickHouse ops user is not configured on this instance (CLICKHOUSE_OPS_URL unset in production).",
119
+ },
120
+ 503,
121
+ );
122
+ }
123
+ if (consumeMissingOpsUrlWarning()) {
124
+ logger.warn(
125
+ "CLICKHOUSE_OPS_URL is not set — /ops/clickhouse/explain is falling back to the default-user client. " +
126
+ "Provision the langwatch_ops user (see infrastructure/clickhouse-serverless/config/users.xml.template) " +
127
+ "and set CLICKHOUSE_OPS_URL to remove this fallback.",
128
+ );
129
+ }
130
+ usingFallback = true;
131
+ client = getSharedClickHouseClient();
132
+ }
133
+ if (!client) {
134
+ return c.json({ message: "ClickHouse is not configured on this instance" }, 503);
135
+ }
136
+
137
+ logger.info(
138
+ { type: built.type, usingFallback, ...redactQueryForAudit(parsed.data.query) },
139
+ "ops explain",
140
+ );
141
+
142
+ try {
143
+ // Only send guardrails when we fell back to the default-user client.
144
+ // The langwatch_ops user runs under the `readonly_safe` profile
145
+ // (readonly=1), which forbids client-side setting modifications —
146
+ // sending guardrails here would 400 every request. The profile
147
+ // already enforces the same caps server-side.
148
+ const result = await client.query({
149
+ query: built.wrapped!,
150
+ format: "JSONEachRow",
151
+ ...(usingFallback ? { clickhouse_settings: CLICKHOUSE_GUARDRAILS } : {}),
152
+ });
153
+ const rows = await result.json();
154
+ return c.json({ type: built.type, rows });
155
+ } catch (err) {
156
+ const msg = err instanceof Error ? err.message : String(err);
157
+ logger.warn({ err: msg }, "ops explain failed");
158
+ return c.json({ message: `ClickHouse error: ${msg}` }, 502);
159
+ }
160
+ });
161
+
162
+ export const app = secured.hono;
@@ -12,6 +12,10 @@ import { getProjectModelProviders } from "../api/routers/modelProviders.utils";
12
12
  import { prisma } from "../db";
13
13
  import type { SingleEvaluationResult } from "../evaluations/evaluators.generated";
14
14
  import type { MaybeStoredModelProvider } from "../modelProviders/registry";
15
+ import { createLogger } from "../../utils/logger";
16
+ import { stripUnsupportedLLMParamsFromWorkflow } from "./stripUnsupportedLLMParams";
17
+
18
+ const logger = createLogger("langwatch:workflows:runWorkflow");
15
19
 
16
20
  const getWorkFlow = (state: Workflow) => {
17
21
  return {
@@ -233,6 +237,33 @@ export async function runWorkflow(
233
237
  },
234
238
  };
235
239
 
240
+ // Strip every sampling parameter from each LLM block that the resolved
241
+ // model does not list as supported. The Studio path (POST
242
+ // /api/workflows/post_event) already does this; this is the parallel
243
+ // chokepoint for every server-driven dispatch (online evaluators,
244
+ // evaluator-as-evaluator chains, scheduled runs). Without it, a
245
+ // published workflow that carries a stale top_p from before the
246
+ // operator disabled it on their custom-model config still ships the
247
+ // field to the gateway, and Bedrock newer-Claude rejects the combo
248
+ // with `temperature and top_p cannot both be specified`. Customer
249
+ // dogfood 2026-05-31 surfaced exactly this path on
250
+ // us.anthropic.claude-haiku-4-5-* as an online evaluator. Best-effort
251
+ // so a registry-lookup miss never blocks the run.
252
+ try {
253
+ await stripUnsupportedLLMParamsFromWorkflow({
254
+ prisma,
255
+ projectId,
256
+ workflow: messageWithoutEnvs.payload.workflow as Parameters<
257
+ typeof stripUnsupportedLLMParamsFromWorkflow
258
+ >[0]["workflow"],
259
+ });
260
+ } catch (filterError) {
261
+ logger.warn(
262
+ { err: filterError, projectId, workflowId },
263
+ "stripUnsupportedLLMParamsFromWorkflow failed; forwarding original payload",
264
+ );
265
+ }
266
+
236
267
  const event = await addEnvs(messageWithoutEnvs, projectId);
237
268
 
238
269
  const response = await nlpgoFetch<{
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@langwatch/server",
3
- "version": "3.4.0",
3
+ "version": "3.4.1",
4
4
  "description": "Run LangWatch locally with one command — `npx @langwatch/server`. Complete LangWatch stack: observability, evaluations, AI gateway, agent simulations.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://langwatch.ai",
@@ -27133,7 +27133,7 @@ var placeholderRuntime = {
27133
27133
  };
27134
27134
 
27135
27135
  // src/cli.ts
27136
- var VERSION = true ? "3.4.0" : "0.0.0-dev";
27136
+ var VERSION = true ? "3.4.1" : "0.0.0-dev";
27137
27137
  async function loadRuntime() {
27138
27138
  try {
27139
27139
  const real = await Promise.resolve().then(() => (init_runtime(), runtime_exports));