-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
feat(webapp): query boundary pinned end-to-end and a capped query retry #4549
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kathiekiwi
wants to merge
20
commits into
fix/watch-mode-keepalive-tri-13065
Choose a base branch
from
feat/query-safety-tri-11165
base: fix/watch-mode-keepalive-tri-13065
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
20 commits
Select commit
Hold shift + click to select a range
0edbb22
feat(webapp): pin the query boundary end-to-end and cap the query retry
kathiekiwi 3fa21ef
Merge remote-tracking branch 'origin/fix/watch-mode-keepalive-tri-130…
kathiekiwi acd54e0
Merge remote-tracking branch 'origin/fix/watch-mode-keepalive-tri-130…
kathiekiwi 25fe809
merge: propagate review fixes from fix/watch-mode-keepalive-tri-13065
kathiekiwi 2361556
merge: propagate wave-2 review fixes from fix/watch-mode-keepalive-tr…
kathiekiwi 4ed6b99
merge: propagate org-purge best-effort from fix/watch-mode-keepalive-…
kathiekiwi 614a7a9
fix(dashboard-agent): only count SQL errors toward the query-failure cap
kathiekiwi 24444be
merge: query-failure cap SQL errors only review-comment fixes
kathiekiwi 9a78579
merge: propagate review-comment fixes from fix/watch-mode-keepalive-t…
kathiekiwi 50df6c3
merge: propagate second-pass fixes from fix/watch-mode-keepalive-tri-…
kathiekiwi 2026a4e
merge: propagate server-changes consolidation from fix/watch-mode-kee…
kathiekiwi ed2c5c2
merge: propagate changeset consolidation and note restoration from fi…
kathiekiwi dbd216b
merge: propagate base UI relocation + drizzle attribution
kathiekiwi cf7fa9a
merge: propagate the tsql linter test fix from fix/watch-mode-keepali…
kathiekiwi dca2118
merge: propagate card-test relocation
kathiekiwi bf6a051
chore: merge fix/watch-mode-keepalive-tri-13065 (main sync)
kathiekiwi dd22919
chore: merge fix/watch-mode-keepalive-tri-13065 (review fixes)
kathiekiwi 76560bb
chore: merge fix/watch-mode-keepalive-tri-13065 (review fixes round 2)
kathiekiwi 14ea61c
chore: merge fix/watch-mode-keepalive-tri-13065 (review fixes round 3)
kathiekiwi 66b6dfa
chore: merge fix/watch-mode-keepalive-tri-13065 (review fixes round 3)
kathiekiwi File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| --- | ||
| area: webapp | ||
| type: improvement | ||
| --- | ||
|
|
||
| Queries stay read-only, and the agent now stops after a few failed queries in a row and answers with what it found instead of spending the whole reply retrying. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,168 @@ | ||
| import { generateJWT } from "@trigger.dev/core/v3/jwt"; | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
|
|
||
| /** | ||
| * The query API is read-only, and the grammar is what enforces it. A parser test alone would | ||
| * stay green if the route ever compiled agent SQL somewhere else, so these drive the real route | ||
| * with a real signed environment JWT and stub only the ClickHouse client. A write must be | ||
| * refused before anything reaches ClickHouse. | ||
| */ | ||
|
|
||
| const ENVIRONMENT_ID = "env_1234"; | ||
| const API_KEY = "tr_dev_abcdefghijklmnop"; | ||
|
|
||
| const environment = { | ||
| id: ENVIRONMENT_ID, | ||
| type: "DEVELOPMENT", | ||
| slug: "dev", | ||
| branchName: null, | ||
| apiKey: API_KEY, | ||
| organizationId: "org_1", | ||
| projectId: "proj_1", | ||
| archivedAt: null, | ||
| concurrencyLimitBurstFactor: { toNumber: () => 1 }, | ||
| maximumConcurrencyLimit: 10, | ||
| project: { id: "proj_1", externalRef: "proj_ref", deletedAt: null }, | ||
| organization: { id: "org_1" }, | ||
| orgMember: null, | ||
| parentEnvironment: null, | ||
| }; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| runtimeEnvironmentFindFirst: vi.fn(), | ||
| queryWithStats: vi.fn(), | ||
| customerQueryCreate: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock("~/db.server", () => { | ||
| const client = { | ||
| runtimeEnvironment: { | ||
| findFirst: mocks.runtimeEnvironmentFindFirst, | ||
| findMany: async () => [], | ||
| }, | ||
| revokedApiKey: { findMany: async () => [], findFirst: async () => null }, | ||
| project: { findMany: async () => [] }, | ||
| customerQuery: { findFirst: async () => null, create: mocks.customerQueryCreate }, | ||
| }; | ||
| return { prisma: client, $replica: client }; | ||
| }); | ||
|
kathiekiwi marked this conversation as resolved.
|
||
| vi.mock("~/env.server", () => ({ | ||
| env: { | ||
| SESSION_SECRET: "test-session-secret", | ||
| QUERY_CLICKHOUSE_MAX_EXECUTION_TIME: "30", | ||
| QUERY_CLICKHOUSE_MAX_MEMORY_USAGE: 1000000, | ||
| QUERY_CLICKHOUSE_MAX_AST_ELEMENTS: 50000, | ||
| QUERY_CLICKHOUSE_MAX_EXPANDED_AST_ELEMENTS: 500000, | ||
| QUERY_CLICKHOUSE_MAX_BYTES_BEFORE_EXTERNAL_GROUP_BY: 1000000, | ||
| QUERY_CLICKHOUSE_MAX_RETURNED_ROWS: 1000, | ||
| }, | ||
| })); | ||
| vi.mock("~/services/clickhouse/clickhouseFactoryInstance.server", () => ({ | ||
| clickhouseFactory: { | ||
| getClickhouseForOrganization: async () => ({ | ||
| reader: { queryWithStats: mocks.queryWithStats }, | ||
| }), | ||
| }, | ||
| })); | ||
| vi.mock("~/services/platform.v3.server", () => ({ getLimit: async () => 30 })); | ||
| vi.mock("~/services/queryConcurrencyLimiter.server", () => ({ | ||
| queryConcurrencyLimiter: { | ||
| acquire: async () => ({ success: true }), | ||
| release: async () => {}, | ||
| }, | ||
| DEFAULT_ORG_CONCURRENCY_LIMIT: 10, | ||
| GLOBAL_CONCURRENCY_LIMIT: 100, | ||
| })); | ||
| vi.mock("~/services/logger.server", () => ({ | ||
| logger: { debug: vi.fn(), error: vi.fn(), warn: vi.fn(), info: vi.fn() }, | ||
| })); | ||
| vi.mock("~/v3/services/worker/workerGroupTokenService.server", () => ({ | ||
| WorkerGroupTokenService: class {}, | ||
| })); | ||
| vi.mock("~/v3/services/common.server", () => ({ ServiceValidationError: class extends Error {} })); | ||
| vi.mock("@internal/run-engine", () => ({ EngineServiceValidationError: class extends Error {} })); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
|
|
||
| import { action } from "~/routes/api.v1.query"; | ||
| import { executeQuery } from "~/services/queryService.server"; | ||
|
|
||
| /** The claims the env-JWT exchange mints (api.v1.projects.$projectRef.$env.jwt.ts). */ | ||
| function mintEnvJwt(scopes: string[]) { | ||
| return generateJWT({ | ||
| secretKey: API_KEY, | ||
| payload: { | ||
| sub: ENVIRONMENT_ID, | ||
| pub: true, | ||
| scopes, | ||
| act: { sub: "usr_1", client: "dashboard-agent" }, | ||
| }, | ||
| expirationTime: "1h", | ||
| }); | ||
| } | ||
|
|
||
| async function runQuery(query: string): Promise<{ status: number; body: any }> { | ||
| const jwt = await mintEnvJwt(["read:query"]); | ||
| const response = await action({ | ||
| request: new Request("https://api.trigger.dev/api/v1/query", { | ||
| method: "POST", | ||
| headers: { Authorization: `Bearer ${jwt}`, "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ query }), | ||
| }), | ||
| params: {}, | ||
| context: {}, | ||
| } as any); | ||
| return { status: response.status, body: await response.json() }; | ||
| } | ||
|
|
||
| describe("the query API route", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mocks.runtimeEnvironmentFindFirst.mockResolvedValue(environment); | ||
| mocks.customerQueryCreate.mockResolvedValue({ id: "cq_1" }); | ||
| mocks.queryWithStats.mockReturnValue(async () => [null, { rows: [], stats: {} }]); | ||
| }); | ||
|
|
||
| // Pins the seam the two refusals assert against: a read really does reach ClickHouse here, | ||
| // so `not.toHaveBeenCalled()` below means refused, not unreachable. | ||
| it("runs a read against ClickHouse", async () => { | ||
| const result = await runQuery("SELECT count() FROM runs"); | ||
|
|
||
| expect(result.status).toBe(200); | ||
| expect(mocks.queryWithStats).toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("refuses a write smuggled in as a second statement", async () => { | ||
| const result = await runQuery("SELECT 1 FROM runs; DROP TABLE runs"); | ||
|
|
||
| expect(result.status).toBe(400); | ||
| expect(mocks.queryWithStats).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("refuses a mutating statement", async () => { | ||
| const result = await runQuery("INSERT INTO runs (task_identifier) VALUES ('x')"); | ||
|
|
||
| expect(result.status).toBe(400); | ||
| expect(mocks.queryWithStats).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| describe("the query service", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| mocks.queryWithStats.mockReturnValue(async () => [null, { rows: [], stats: {} }]); | ||
| }); | ||
|
|
||
| it("keeps ClickHouse read-only when a caller overrides the settings", async () => { | ||
| await executeQuery({ | ||
| name: "test-query", | ||
| query: "SELECT count() FROM runs", | ||
| scope: "environment", | ||
| organizationId: "org_1", | ||
| projectId: "proj_1", | ||
| environmentId: ENVIRONMENT_ID, | ||
| clickhouseSettings: { readonly: "0" }, | ||
| } as any); | ||
|
|
||
| expect(mocks.queryWithStats).toHaveBeenCalled(); | ||
| expect(mocks.queryWithStats.mock.calls[0][0].settings.readonly).toBe("1"); | ||
| }); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
90 changes: 90 additions & 0 deletions
90
internal-packages/dashboard-agent/src/tool-query-retry-cap.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,90 @@ | ||
| import { describe, expect, it, vi } from "vitest"; | ||
| import { buildApiTools, MAX_CONSECUTIVE_QUERY_FAILURES } from "./tool-api"; | ||
| import type { DashboardAgentApiClient } from "./tool-api-client"; | ||
|
|
||
| /** | ||
| * A failed query hands the model the database error to fix. Without a cap, the only other | ||
| * limit is the turn's step budget, so a model that keeps rewriting the same broken query | ||
| * burns the whole turn and the user gets no answer. After three failures in a row the tool | ||
| * tells it to stop and answer. | ||
| */ | ||
|
|
||
| function queryTool(postQuery: DashboardAgentApiClient["postQuery"]) { | ||
| const client = { | ||
| origin: "https://api.example.com", | ||
| hasAuth: true, | ||
| envApiGet: async () => ({ ok: false as const, status: 500 }), | ||
| postQuery, | ||
| validateChartQuery: async () => null, | ||
| } as unknown as DashboardAgentApiClient; | ||
| const tools = buildApiTools({ | ||
| ctx: { userActorToken: "uat", apiOrigin: client.origin }, | ||
| client, | ||
| renderInvestigations: (() => []) as any, | ||
| }); | ||
| return (query: string) => (tools.run_query as any).execute({ query }, {} as any); | ||
| } | ||
|
|
||
| const failure = { | ||
| ok: false as const, | ||
| kind: "query" as const, | ||
| error: "Unknown expression identifier 'createdAt'.", | ||
| }; | ||
| const transportFailure = { | ||
| ok: false as const, | ||
| kind: "transport" as const, | ||
| error: "The environment is temporarily unavailable.", | ||
| }; | ||
| const success = { ok: true as const, rows: [{ n: 1 }] }; | ||
|
|
||
| describe("run_query's consecutive-failure cap", () => { | ||
| it("keeps handing back the plain error until the cap", async () => { | ||
| const run = queryTool(async () => failure); | ||
|
|
||
| for (let attempt = 1; attempt < MAX_CONSECUTIVE_QUERY_FAILURES; attempt++) { | ||
| const result = await run("SELECT createdAt FROM runs"); | ||
| expect(result.error).toBe(failure.error); | ||
| } | ||
| }); | ||
|
|
||
| it("tells the model to stop and answer at the cap", async () => { | ||
| const run = queryTool(async () => failure); | ||
|
|
||
| let result: { error: string } = { error: "" }; | ||
| for (let attempt = 0; attempt < MAX_CONSECUTIVE_QUERY_FAILURES; attempt++) { | ||
| result = await run("SELECT createdAt FROM runs"); | ||
| } | ||
|
|
||
| expect(result.error).toContain(failure.error); | ||
| expect(result.error).toContain("answer the user with what you already have"); | ||
| }); | ||
|
|
||
| it("counts consecutive failures only, so a good query clears the count", async () => { | ||
| const postQuery = vi | ||
| .fn() | ||
| .mockResolvedValueOnce(failure) | ||
| .mockResolvedValueOnce(failure) | ||
| .mockResolvedValueOnce(success) | ||
| .mockResolvedValue(failure); | ||
| const run = queryTool(postQuery as any); | ||
|
|
||
| await run("bad"); | ||
| await run("bad"); | ||
| await run("good"); | ||
| const result = await run("bad"); | ||
|
|
||
| expect(result.error).toBe(failure.error); | ||
| }); | ||
|
|
||
| it("does not count transport errors toward the cap", async () => { | ||
| const run = queryTool(async () => transportFailure); | ||
|
|
||
| let result: { error: string } = { error: "" }; | ||
| for (let attempt = 0; attempt < MAX_CONSECUTIVE_QUERY_FAILURES + 2; attempt++) { | ||
| result = await run("SELECT createdAt FROM runs"); | ||
| } | ||
|
|
||
| expect(result.error).toBe(transportFailure.error); | ||
| expect(result.error).not.toContain("answer the user with what you already have"); | ||
| }); | ||
| }); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.