Skip to content

feat(webapp): query boundary pinned end-to-end and a capped query retry - #4549

Open
kathiekiwi wants to merge 21 commits into
fix/watch-mode-keepalive-tri-13065from
feat/query-safety-tri-11165
Open

feat(webapp): query boundary pinned end-to-end and a capped query retry#4549
kathiekiwi wants to merge 21 commits into
fix/watch-mode-keepalive-tri-13065from
feat/query-safety-tri-11165

Conversation

@kathiekiwi

@kathiekiwi kathiekiwi commented Aug 10, 2026

Copy link
Copy Markdown
Collaborator

What & why

The agent's query tool is read-only, but that was true by three separate facts and only one of them had a test. This proves the boundary holds by contract rather than by prompt, and stops a broken query from burning a whole agent turn.

Two small guards, the rest is tests. TRI-11165.

Stack

Stacked on #4548 (watch-mode keepalive). Merge that first.

What's inside

  • A route-level read-only test (apps/webapp/test/queryRouteReadOnly.test.ts) that drives api.v1.query with a real signed environment JWT: a multi-statement write and a mutating statement are both refused before anything reaches ClickHouse, and a plain read passes so the seam stays live.
  • readonly=1 made non-overridable in queryService.server.ts — caller clickhouseSettings were spread after the defaults and could clear it.
  • A per-turn query-retry cap in the agent's run_query tool (internal-packages/dashboard-agent/src/tool-api.ts): three consecutive failures returns a terminal "stop and answer with what you have".

Key decisions

  • The read-only guarantee is grammar-level, not filtered. TRQL has no write statements — they don't parse — ClickHouse runs with readonly=1, and the org/project/env scoping is injected server-side from the credential. The request body can't widen scope or turn a read into a write.
  • The deny test runs through the route, not the parser. A parser-only test would stay green if a refactor routed agent SQL around the compiler; driving the real route with a signed JWT pins the boundary end-to-end, and the deliberate positive read keeps the assertion honest.
  • The retry cap lives per turn, not in the prompt. A failed query hands the model the database error to fix, and usually it does — but the only other limit was the turn's 10 steps, so one query the model couldn't fix could eat the whole turn and leave the user with no answer. The tool set is built per turn, so the counter caps consecutive failures; a success resets it. The retry instruction rides the error text, so the prompt prefix is unchanged.

Testing

  • queryRouteReadOnly.test.ts — write statements → 400, ClickHouse never called; a read passes.
  • tool-query-retry-cap.test.ts — terminal at the third consecutive failure, counter resets on a success.
  • The load-bearing guards were control-broken first (readonly override re-enabled; cap removed) and the tests went red.

The read-only guard was enforced by the TRQL grammar and a parser test, but nothing
proved the route itself refuses a write; a route test now drives api.v1.query with a
signed environment JWT and asserts nothing reaches ClickHouse. readonly=1 is no longer
overridable by a caller's clickhouseSettings. run_query gives up after three consecutive
failures so a broken query can't burn a whole agent turn.

TRI-11165
@changeset-bot

changeset-bot Bot commented Aug 10, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: d329967

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4d979f72-38c4-42d3-a03f-515e71a9db0e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

The webapp now rejects mutating query statements and enforces readonly: "1" after merging caller settings. Integration tests cover authenticated reads, rejected writes, and setting overrides. The dashboard agent now tracks consecutive run_query failures per turn, stops after three failures, and resets the counter after a successful query. Tests cover the failure cap and reset behavior.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the two main changes: enforcing the query boundary and capping consecutive query retries.
Description check ✅ Passed The description explains the motivation, implementation, key decisions, testing, and linked issue, with only non-critical template sections omitted.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/query-safety-tri-11165

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot]

This comment was marked as resolved.

@pkg-pr-new

pkg-pr-new Bot commented Aug 10, 2026

Copy link
Copy Markdown

Open in StackBlitz

@trigger.dev/build

npm i https://pkg.pr.new/@trigger.dev/build@14ea61c

trigger.dev

npm i https://pkg.pr.new/trigger.dev@14ea61c

@trigger.dev/core

npm i https://pkg.pr.new/@trigger.dev/core@14ea61c

@trigger.dev/python

npm i https://pkg.pr.new/@trigger.dev/python@14ea61c

@trigger.dev/react-hooks

npm i https://pkg.pr.new/@trigger.dev/react-hooks@14ea61c

@trigger.dev/redis-worker

npm i https://pkg.pr.new/@trigger.dev/redis-worker@14ea61c

@trigger.dev/rsc

npm i https://pkg.pr.new/@trigger.dev/rsc@14ea61c

@trigger.dev/schema-to-json

npm i https://pkg.pr.new/@trigger.dev/schema-to-json@14ea61c

@trigger.dev/sdk

npm i https://pkg.pr.new/@trigger.dev/sdk@14ea61c

commit: 14ea61c

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 new potential issues.

Open in Devin Review

Comment on lines +37 to +83
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 };
});
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 {} }));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 New tests rely on mocking, which the repository's test guidance forbids

The new test suites stub out the database, environment config, ClickHouse factory, logger and concurrency limiter with mock objects (vi.mock("~/db.server", ...) at apps/webapp/test/queryRouteReadOnly.test.ts:37-83), whereas the repository's testing guidance requires real containers instead of mocks.
Impact: The tests can keep passing while the real database, environment and ClickHouse wiring drifts, so the read-only guarantee they claim to pin is only proven against stand-ins.

Which rule is violated and where

AGENTS.md ("Testing") states: "We use vitest exclusively. Never mock anything - use testcontainers instead." Both new files rely on mocking: apps/webapp/test/queryRouteReadOnly.test.ts:31-83 mocks ~/db.server, ~/env.server, the ClickHouse factory instance, the platform limits service, the concurrency limiter and the logger; internal-packages/dashboard-agent/src/tool-query-retry-cap.test.ts:12-26 hand-builds a fake DashboardAgentApiClient. The webapp suite has an existing test/ layout with container-based e2e configs (apps/webapp/test/README.md) that these route-level assertions could use instead.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +353 to +365
if (!result.ok) {
// Only SQL errors count toward the cap; transport errors are transient.
if (result.kind === "query") {
consecutiveQueryFailures++;
if (consecutiveQueryFailures >= MAX_CONSECUTIVE_QUERY_FAILURES) {
return {
error: `${result.error} That is ${consecutiveQueryFailures} queries in a row that failed. Stop querying and answer the user with what you already have.`,
};
}
}
return { error: result.error };
}
consecutiveQueryFailures = 0;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Chart-query validation failures bypass the retry cap

render_view validates chart queries through validateChartQuery, which also posts to the query endpoint (internal-packages/dashboard-agent/src/tool-api-client.ts), but a failure there returns an error prompting the model to "Fix the query ... and render the chart again" (internal-packages/dashboard-agent/src/tool-api.ts:407-412) without touching consecutiveQueryFailures. So the failure mode the cap is meant to prevent — a model burning the turn's step budget rewriting a query it can't fix — is still reachable via repeated render_view calls.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants