@malloy-publisher/server 0.0.232 → 0.0.234
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.
- package/README.docker.md +1 -0
- package/dist/app/api-doc.yaml +269 -10
- package/dist/app/assets/{EnvironmentPage-DXEaZIPx.js → EnvironmentPage-DTZQ4Gxc.js} +1 -1
- package/dist/app/assets/{HomePage-kofsqpZt.js → HomePage-C5mlDPXK.js} +1 -1
- package/dist/app/assets/{LightMode-CNhIlIlJ.js → LightMode-DGNmhG0u.js} +1 -1
- package/dist/app/assets/{MainPage-Bgqo8jCy.js → MainPage-CVL_wmP4.js} +1 -1
- package/dist/app/assets/{MaterializationsPage-CgBlgGz2.js → MaterializationsPage-DmzMBCpy.js} +1 -1
- package/dist/app/assets/{ModelPage-B0TjoDtf.js → ModelPage-Dbvf4QbB.js} +1 -1
- package/dist/app/assets/{PackagePage-BL8vnFj1.js → PackagePage-DxdHc2Qs.js} +1 -1
- package/dist/app/assets/{RouteError-BzPby0X2.js → RouteError-OJdT4tCd.js} +1 -1
- package/dist/app/assets/{ThemeEditorPage-CTEP_9r3.js → ThemeEditorPage-Bk7s0KXY.js} +1 -1
- package/dist/app/assets/{WorkbookPage-BwM3BmKw.js → WorkbookPage-j_vCWdN3.js} +1 -1
- package/dist/app/assets/{core-CK68iv6w.es-CpRxXBt7.js → core-Rj_4rRnA.es-DoIfLxDJ.js} +1 -1
- package/dist/app/assets/{index-B33zGctF.js → index-B_jKMR35.js} +4 -4
- package/dist/app/assets/{index-CmkW1MiE.js → index-D-rDyK11.js} +1 -1
- package/dist/app/assets/{index-tXJXwdyj.js → index-DWIe_hK0.js} +1 -1
- package/dist/app/assets/{index-BkiWKaAF.js → index-hw-xn0X7.js} +1 -1
- package/dist/app/index.html +1 -1
- package/dist/package_load_worker.mjs +53 -3
- package/dist/server.mjs +20277 -925
- package/package.json +1 -1
- package/src/config.ts +35 -1
- package/src/controller/connection.controller.spec.ts +46 -0
- package/src/controller/connection.controller.ts +105 -2
- package/src/controller/materialization.controller.spec.ts +25 -0
- package/src/controller/materialization.controller.ts +60 -0
- package/src/controller/model.controller.ts +24 -0
- package/src/controller/query.controller.ts +83 -10
- package/src/json_utils.spec.ts +51 -0
- package/src/json_utils.ts +33 -0
- package/src/mcp/handler_utils.ts +10 -2
- package/src/mcp/query_envelope.spec.ts +229 -0
- package/src/mcp/query_envelope.ts +240 -0
- package/src/mcp/server.protocol.spec.ts +128 -16
- package/src/mcp/skills/build_skills_bundle.ts +94 -4
- package/src/mcp/skills/skills_bundle.json +1 -1
- package/src/mcp/skills/skills_bundle.spec.ts +113 -4
- package/src/mcp/tool_response.spec.ts +108 -0
- package/src/mcp/tool_response.ts +138 -0
- package/src/mcp/tools/compile_tool.spec.ts +112 -4
- package/src/mcp/tools/compile_tool.ts +61 -30
- package/src/mcp/tools/docs_search_tool.ts +6 -16
- package/src/mcp/tools/execute_query_tool.spec.ts +154 -3
- package/src/mcp/tools/execute_query_tool.ts +131 -155
- package/src/mcp/tools/get_context_tool.spec.ts +63 -3
- package/src/mcp/tools/get_context_tool.ts +43 -46
- package/src/mcp/tools/reload_package_tool.ts +3 -29
- package/src/mcp_config.spec.ts +919 -0
- package/src/mcp_config.ts +425 -0
- package/src/oom_guards.integration.spec.ts +11 -3
- package/src/package_load/package_load_pool.ts +2 -0
- package/src/package_load/package_load_worker.ts +17 -5
- package/src/package_load/protocol.ts +6 -0
- package/src/query_metadata_metrics.ts +49 -0
- package/src/server.ts +99 -3
- package/src/service/build_plan.spec.ts +125 -0
- package/src/service/build_plan.ts +108 -7
- package/src/service/compile_fragment_techniques.spec.ts +156 -0
- package/src/service/connection.spec.ts +371 -1
- package/src/service/connection.ts +77 -14
- package/src/service/connection_config.spec.ts +60 -0
- package/src/service/connection_config.ts +75 -0
- package/src/service/duckdb_instance_isolation.spec.ts +137 -0
- package/src/service/environment.ts +57 -3
- package/src/service/materialization_config_validation.spec.ts +99 -0
- package/src/service/materialization_config_validation.ts +120 -0
- package/src/service/materialization_schedule_surface.spec.ts +124 -0
- package/src/service/materialization_service.spec.ts +119 -0
- package/src/service/materialization_service.ts +186 -3
- package/src/service/materialization_test_fixtures.ts +86 -21
- package/src/service/model.spec.ts +45 -1
- package/src/service/model.ts +171 -23
- package/src/service/model_limits.spec.ts +28 -0
- package/src/service/model_limits.ts +21 -0
- package/src/service/package.ts +24 -1
- package/src/service/package_manifest.spec.ts +137 -4
- package/src/service/package_manifest.ts +140 -5
- package/src/service/persist_annotation_validation.spec.ts +12 -0
- package/src/service/persist_annotation_validation.ts +9 -4
- package/src/service/query_metadata.spec.ts +408 -0
- package/src/service/query_metadata.ts +492 -0
- package/src/service/query_metadata_identity.spec.ts +149 -0
- package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +37 -12
package/src/mcp/handler_utils.ts
CHANGED
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
type ErrorDetails,
|
|
20
20
|
} from "./error_messages";
|
|
21
21
|
import type { Model } from "../service/model";
|
|
22
|
+
import type { Environment } from "../service/environment";
|
|
22
23
|
import { logger } from "../logger";
|
|
23
24
|
|
|
24
25
|
/**
|
|
@@ -116,6 +117,11 @@ export function classifyToolError(
|
|
|
116
117
|
/**
|
|
117
118
|
* Fetches and validates the Package and Model instances needed for query execution.
|
|
118
119
|
* Handles errors related to package/model access and initial compilation.
|
|
120
|
+
*
|
|
121
|
+
* The resolved Environment comes back with the model because a query needs it for
|
|
122
|
+
* more than the lookup: it owns the connection configs the per-query metadata
|
|
123
|
+
* layers are read from.
|
|
124
|
+
*
|
|
119
125
|
* @returns An object containing the Model instance or a pre-formatted ErrorDetails object.
|
|
120
126
|
*/
|
|
121
127
|
export async function getModelForQuery(
|
|
@@ -123,7 +129,9 @@ export async function getModelForQuery(
|
|
|
123
129
|
environmentName: string,
|
|
124
130
|
packageName: string,
|
|
125
131
|
modelPath: string,
|
|
126
|
-
): Promise<
|
|
132
|
+
): Promise<
|
|
133
|
+
{ model: Model; environment: Environment } | { error: ErrorDetails }
|
|
134
|
+
> {
|
|
127
135
|
try {
|
|
128
136
|
const environment = await environmentStore.getEnvironment(
|
|
129
137
|
environmentName,
|
|
@@ -143,7 +151,7 @@ export async function getModelForQuery(
|
|
|
143
151
|
}
|
|
144
152
|
// Attempt to get the model definition early to catch initial compilation errors
|
|
145
153
|
await model.getModel(); // This might throw ModelCompilationError
|
|
146
|
-
return { model };
|
|
154
|
+
return { model, environment };
|
|
147
155
|
} catch (error) {
|
|
148
156
|
// Handle errors during package/model access or initial compilation
|
|
149
157
|
let errorDetails: ErrorDetails;
|
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { describe, expect, it } from "bun:test";
|
|
2
|
+
import type * as Malloy from "@malloydata/malloy-interfaces";
|
|
3
|
+
import {
|
|
4
|
+
buildQueryEnvelope,
|
|
5
|
+
serializeEnvelope,
|
|
6
|
+
MAX_RESULT_CHARS,
|
|
7
|
+
} from "./query_envelope";
|
|
8
|
+
|
|
9
|
+
const rows = (n: number) =>
|
|
10
|
+
Array.from({ length: n }, (_, i) => ({ id: i, name: `row ${i}` }));
|
|
11
|
+
|
|
12
|
+
/** A minimal Malloy.Result: only the metadata the envelope reads. */
|
|
13
|
+
const result = (extra: Partial<Malloy.Result> = {}): Malloy.Result =>
|
|
14
|
+
({
|
|
15
|
+
schema: { fields: [{ kind: "dimension", name: "id" }] },
|
|
16
|
+
connection_name: "duckdb",
|
|
17
|
+
...extra,
|
|
18
|
+
}) as Malloy.Result;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The field names here are Credible's, on purpose: a data app authored against
|
|
22
|
+
* Publisher is served through Credible, and an agent that sees one shape while
|
|
23
|
+
* developing and another in production has to learn both. These assertions are
|
|
24
|
+
* the contract that keeps them the same, so renaming a field should fail here.
|
|
25
|
+
*/
|
|
26
|
+
describe("buildQueryEnvelope", () => {
|
|
27
|
+
it("returns flat rows plus Credible's metadata block", () => {
|
|
28
|
+
const e = buildQueryEnvelope(rows(3), 1000, result());
|
|
29
|
+
expect(e.rows).toHaveLength(3);
|
|
30
|
+
expect(e._meta.connection_name).toBe("duckdb");
|
|
31
|
+
expect(e._meta.schema.fields).toHaveLength(1);
|
|
32
|
+
expect(e._meta.annotations).toEqual([]);
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
it("carries the Malloy metadata that flat rows drop", () => {
|
|
36
|
+
// Field types and render tags live in the schema, not the rows, so an
|
|
37
|
+
// agent would otherwise need a second verbose call to reach them.
|
|
38
|
+
const e = buildQueryEnvelope(rows(1), 1000, {
|
|
39
|
+
...result(),
|
|
40
|
+
query_timezone: "UTC",
|
|
41
|
+
model_annotations: [{ value: "# dashboard" }],
|
|
42
|
+
} as Malloy.Result);
|
|
43
|
+
expect(e._meta.query_timezone).toBe("UTC");
|
|
44
|
+
expect(e._meta.model_annotations).toEqual([{ value: "# dashboard" }]);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it("omits metadata keys the result did not carry", () => {
|
|
48
|
+
const e = buildQueryEnvelope(rows(1), 1000, result());
|
|
49
|
+
expect("query_timezone" in e._meta).toBe(false);
|
|
50
|
+
expect("source_annotations" in e._meta).toBe(false);
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The correctness fix, and the one field a client cannot compute for itself:
|
|
55
|
+
* the cap depends on server config and on the query's own LIMIT.
|
|
56
|
+
*/
|
|
57
|
+
describe("_limit_hit", () => {
|
|
58
|
+
it("is true when the row count lands exactly on the cap", () => {
|
|
59
|
+
const e = buildQueryEnvelope(rows(1000), 1000, result());
|
|
60
|
+
expect(e._limit_hit).toBe(true);
|
|
61
|
+
expect(e._query_row_limit).toBe(1000);
|
|
62
|
+
expect(e.warning).toContain("not a complete result");
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
it("is false when the result came in under the cap", () => {
|
|
66
|
+
const e = buildQueryEnvelope(rows(999), 1000, result());
|
|
67
|
+
expect(e._limit_hit).toBe(false);
|
|
68
|
+
expect(e.warning).toBeUndefined();
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The false positive this guards. resolveModelQueryRowLimit folds the
|
|
73
|
+
* query's own limit:/top: into the same cap, so equality holds every time
|
|
74
|
+
* an author limited the query deliberately. Three of the eight views in
|
|
75
|
+
* the bundled storefront example use `top:`, so a modelled top-N would
|
|
76
|
+
* otherwise report its complete answer as cut off, and the Contract rule
|
|
77
|
+
* would tell an agent that a top-N is "not the answer".
|
|
78
|
+
*/
|
|
79
|
+
it("is false when the author's own limit: produced the cap", () => {
|
|
80
|
+
const e = buildQueryEnvelope(
|
|
81
|
+
rows(10),
|
|
82
|
+
10,
|
|
83
|
+
result(),
|
|
84
|
+
[],
|
|
85
|
+
undefined,
|
|
86
|
+
"query",
|
|
87
|
+
);
|
|
88
|
+
expect(e._limit_hit).toBe(false);
|
|
89
|
+
expect(e._limit_source).toBe("query");
|
|
90
|
+
expect(e.warning).toBeUndefined();
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
it("still fires when the silent server default produced the cap", () => {
|
|
94
|
+
const e = buildQueryEnvelope(
|
|
95
|
+
rows(1000),
|
|
96
|
+
1000,
|
|
97
|
+
result(),
|
|
98
|
+
[],
|
|
99
|
+
undefined,
|
|
100
|
+
"server_default",
|
|
101
|
+
);
|
|
102
|
+
expect(e._limit_hit).toBe(true);
|
|
103
|
+
expect(e._limit_source).toBe("server_default");
|
|
104
|
+
expect(e.warning).toContain("not a complete result");
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
it("reports the source even when the cap was not reached", () => {
|
|
108
|
+
const e = buildQueryEnvelope(
|
|
109
|
+
rows(3),
|
|
110
|
+
10,
|
|
111
|
+
result(),
|
|
112
|
+
[],
|
|
113
|
+
undefined,
|
|
114
|
+
"query",
|
|
115
|
+
);
|
|
116
|
+
expect(e._limit_hit).toBe(false);
|
|
117
|
+
expect(e._limit_source).toBe("query");
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it("is false when no cap was applied", () => {
|
|
121
|
+
// rowLimit 0 means uncapped; equality against 0 would otherwise call
|
|
122
|
+
// an empty result "limited".
|
|
123
|
+
expect(buildQueryEnvelope([], 0, result())._limit_hit).toBe(false);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it("does not call an empty result limited", () => {
|
|
127
|
+
expect(buildQueryEnvelope([], 1000, result())._limit_hit).toBe(false);
|
|
128
|
+
});
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* compactResult is raw driver output and DuckDB returns count() as a BigInt,
|
|
133
|
+
* so a plain JSON.stringify throws on the most common query anyone writes.
|
|
134
|
+
*/
|
|
135
|
+
it("serializes BigInt values instead of throwing", () => {
|
|
136
|
+
const e = buildQueryEnvelope([{ c: 150930n }], 1000, result());
|
|
137
|
+
expect(() => serializeEnvelope(e)).not.toThrow();
|
|
138
|
+
expect(JSON.parse(serializeEnvelope(e)).rows[0].c).toBe(150930);
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
describe("payload truncation", () => {
|
|
142
|
+
it("drops rows to fit and reports both counts", () => {
|
|
143
|
+
const e = buildQueryEnvelope(rows(200), 100_000, result(), [], 3_000);
|
|
144
|
+
expect(e._rows_truncated).toBe(true);
|
|
145
|
+
expect(e._total_rows).toBe(200);
|
|
146
|
+
expect(e._returned_rows).toBe((e.rows as unknown[]).length);
|
|
147
|
+
expect(e._returned_rows).toBeGreaterThan(0);
|
|
148
|
+
expect(e._returned_rows).toBeLessThan(200);
|
|
149
|
+
expect(e.warning).toContain("of 200 rows");
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
it("keeps the finished payload under the cap", () => {
|
|
153
|
+
// The bug this pins: setting the marker fields and the warning AFTER
|
|
154
|
+
// the search pushes the payload back over the limit the truncation
|
|
155
|
+
// existed to respect.
|
|
156
|
+
const e = buildQueryEnvelope(rows(400), 100_000, result(), [], 3_000);
|
|
157
|
+
expect(serializeEnvelope(e).length).toBeLessThanOrEqual(3_000);
|
|
158
|
+
});
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Reachable because the hard ceiling is maxBytes (50MB), so one row with a
|
|
162
|
+
* large text column passes assertWithinModelResponseLimits and lands here.
|
|
163
|
+
* "Showing 0 of N rows" reads as an empty result set, and an agent will
|
|
164
|
+
* report "no rows matched" for a row that was merely too big to send.
|
|
165
|
+
*/
|
|
166
|
+
it("says no rows fit rather than implying nothing matched", () => {
|
|
167
|
+
const big = [{ doc: "z".repeat(5_000) }, { doc: "small" }];
|
|
168
|
+
const e = buildQueryEnvelope(big, 1000, result(), [], 2_000);
|
|
169
|
+
expect((e.rows as unknown[]).length).toBe(0);
|
|
170
|
+
expect(e._returned_rows).toBe(0);
|
|
171
|
+
expect(e._total_rows).toBe(2);
|
|
172
|
+
expect(e.warning).toContain("No rows fit the result size limit");
|
|
173
|
+
expect(e.warning).toContain("NOT an empty result");
|
|
174
|
+
expect(e.warning).not.toContain("Showing 0 of");
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
it("keeps the zero-row payload under the cap too", () => {
|
|
178
|
+
// The longer of the two wordings is what the search measures, so
|
|
179
|
+
// swapping it in afterwards must not push the payload back over.
|
|
180
|
+
const big = [{ doc: "z".repeat(5_000) }, { doc: "small" }];
|
|
181
|
+
const e = buildQueryEnvelope(big, 1000, result(), [], 2_000);
|
|
182
|
+
expect(serializeEnvelope(e).length).toBeLessThanOrEqual(2_000);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
it("still reports the row cap when no rows fit", () => {
|
|
186
|
+
// Both shortenings apply at once; neither may swallow the other.
|
|
187
|
+
const big = [{ doc: "z".repeat(5_000) }, { doc: "y".repeat(5_000) }];
|
|
188
|
+
const e = buildQueryEnvelope(big, 2, result(), [], 2_000);
|
|
189
|
+
expect(e._limit_hit).toBe(true);
|
|
190
|
+
expect(e.warning).toContain("not a complete result");
|
|
191
|
+
expect(e.warning).toContain("No rows fit the result size limit");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("omits the truncation fields entirely when nothing was dropped", () => {
|
|
195
|
+
// Credible's shape: absent rather than false.
|
|
196
|
+
const e = buildQueryEnvelope(rows(3), 1000, result());
|
|
197
|
+
expect("_rows_truncated" in e).toBe(false);
|
|
198
|
+
expect("_total_rows" in e).toBe(false);
|
|
199
|
+
expect("_returned_rows" in e).toBe(false);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it("reports both shortenings when they happen together", () => {
|
|
203
|
+
const e = buildQueryEnvelope(rows(200), 200, result(), [], 3_000);
|
|
204
|
+
expect(e._limit_hit).toBe(true);
|
|
205
|
+
expect(e._rows_truncated).toBe(true);
|
|
206
|
+
// One says the query was capped, the other that the payload was.
|
|
207
|
+
// Reporting only one would understate the loss.
|
|
208
|
+
expect(e.warning).toContain("not a complete result");
|
|
209
|
+
expect(e.warning).toContain("result size limit");
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
it("leaves an ordinary result well inside the default budget", () => {
|
|
213
|
+
const e = buildQueryEnvelope(rows(500), 1000, result());
|
|
214
|
+
expect("_rows_truncated" in e).toBe(false);
|
|
215
|
+
expect(serializeEnvelope(e).length).toBeLessThan(MAX_RESULT_CHARS);
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
it("passes render-tag messages through under Credible's key", () => {
|
|
220
|
+
const e = buildQueryEnvelope(rows(1), 1000, result(), ["bad tag on x"]);
|
|
221
|
+
expect(e.renderLogErrors).toEqual(["bad tag on x"]);
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
it("omits optional keys when they do not apply", () => {
|
|
225
|
+
const e = buildQueryEnvelope(rows(1), 1000, result());
|
|
226
|
+
expect("warning" in e).toBe(false);
|
|
227
|
+
expect("renderLogErrors" in e).toBe(false);
|
|
228
|
+
});
|
|
229
|
+
});
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
import type * as Malloy from "@malloydata/malloy-interfaces";
|
|
2
|
+
import { bigIntReplacer } from "../json_utils";
|
|
3
|
+
import type { QueryRowLimitSource } from "../service/model_limits";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The agent-facing shape for a query result, matched to what Credible's
|
|
7
|
+
* `execute_query` returns.
|
|
8
|
+
*
|
|
9
|
+
* Matching matters for a specific workflow: a data app is authored locally
|
|
10
|
+
* against Publisher and then served through Credible. An agent that sees one
|
|
11
|
+
* response shape while developing and a different one in production has to
|
|
12
|
+
* learn both, and a shared skill cannot describe either without forking. So the
|
|
13
|
+
* field names here are Credible's, deliberately, including the leading
|
|
14
|
+
* underscores and the mixed casing of `renderLogErrors`.
|
|
15
|
+
*
|
|
16
|
+
* Also following Credible: the truncation fields appear only when truncation
|
|
17
|
+
* happened, rather than always carrying `false`.
|
|
18
|
+
*
|
|
19
|
+
* The two `_limit_...` fields are new to both products. Three separate things
|
|
20
|
+
* can shorten a result and only one of them was ever reported:
|
|
21
|
+
*
|
|
22
|
+
* 1. The query row cap, pushed into the SQL. A query with no `limit:` of its
|
|
23
|
+
* own gets DEFAULT_QUERY_ROW_LIMIT (1000) rows, which is far under
|
|
24
|
+
* PUBLISHER_MAX_QUERY_ROWS, so nothing raises and nothing warns. An agent
|
|
25
|
+
* reports statistics on a silent sample. This is why `_limit_hit` exists,
|
|
26
|
+
* and unlike the others it is not derivable by a client: the cap depends on
|
|
27
|
+
* server config and on the query's own LIMIT.
|
|
28
|
+
* 2. The hard ceiling (maxRows / maxBytes), which throws 413 and is loud.
|
|
29
|
+
* 3. The payload cap below, which degrades to a truncated result plus a
|
|
30
|
+
* warning instead of overflowing the client's per-result limit.
|
|
31
|
+
*
|
|
32
|
+
* `_limit_hit` is a bound, not a total. The server cannot know the true row
|
|
33
|
+
* count, because the database applied the cap. Landing exactly on the limit is
|
|
34
|
+
* the only evidence available that rows were left behind.
|
|
35
|
+
*
|
|
36
|
+
* It is reported only when the cap was the server default, which `_limit_source`
|
|
37
|
+
* names. `resolveModelQueryRowLimit` folds the query's own `limit:`/`top:` into
|
|
38
|
+
* the same number, so equality also holds every time an author limited the query
|
|
39
|
+
* on purpose: three of the eight views in the bundled storefront example use
|
|
40
|
+
* `top:`, and each would otherwise report its complete answer as cut off. The
|
|
41
|
+
* silent sample this exists to catch only ever happens under the default.
|
|
42
|
+
*/
|
|
43
|
+
export interface QueryEnvelope {
|
|
44
|
+
rows: unknown;
|
|
45
|
+
/** Malloy metadata the flat rows drop: field types, render tags, timezone. */
|
|
46
|
+
_meta: {
|
|
47
|
+
schema: Malloy.Schema;
|
|
48
|
+
annotations: Malloy.Annotation[];
|
|
49
|
+
connection_name: string;
|
|
50
|
+
model_annotations?: Malloy.Annotation[];
|
|
51
|
+
query_timezone?: string;
|
|
52
|
+
source_annotations?: Malloy.Annotation[];
|
|
53
|
+
};
|
|
54
|
+
/** The cap pushed into the SQL: the query's own LIMIT, else the server default. */
|
|
55
|
+
_query_row_limit: number;
|
|
56
|
+
/** Which of those two the cap came from. */
|
|
57
|
+
_limit_source: QueryRowLimitSource;
|
|
58
|
+
/**
|
|
59
|
+
* Row count equals the cap AND the cap was the server default, so rows were
|
|
60
|
+
* almost certainly left behind. A deliberate `limit:`/`top:` that returns
|
|
61
|
+
* exactly what it asked for is a complete answer and does not set this.
|
|
62
|
+
*/
|
|
63
|
+
_limit_hit: boolean;
|
|
64
|
+
/** Present only when the payload cap dropped rows. */
|
|
65
|
+
_rows_truncated?: boolean;
|
|
66
|
+
_total_rows?: number;
|
|
67
|
+
_returned_rows?: number;
|
|
68
|
+
/**
|
|
69
|
+
* The `query_id` property attached to this query's statements: the join key
|
|
70
|
+
* into the backend's own query record (`QUERY_HISTORY`, `JOBS.labels`, the
|
|
71
|
+
* statement text). Publisher-side and new to both products, like the two
|
|
72
|
+
* `_limit_...` fields. Absent when nothing was attached, which is every query
|
|
73
|
+
* on a deployment that has not enabled query metadata.
|
|
74
|
+
*/
|
|
75
|
+
_query_id?: string;
|
|
76
|
+
warning?: string;
|
|
77
|
+
renderLogErrors?: string[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Cap on the serialized envelope, in characters. Same value Credible uses.
|
|
82
|
+
*
|
|
83
|
+
* Host-loop MCP clients enforce a per-tool-result ceiling of roughly 25k tokens;
|
|
84
|
+
* past it the result is spilled to disk or rejected outright, and the model then
|
|
85
|
+
* struggles to recover it. Chars stand in for tokens at about 4:1, with headroom
|
|
86
|
+
* for the envelope itself.
|
|
87
|
+
*/
|
|
88
|
+
export const MAX_RESULT_CHARS = 90_000;
|
|
89
|
+
|
|
90
|
+
function serialize(envelope: QueryEnvelope): string {
|
|
91
|
+
return JSON.stringify(envelope, bigIntReplacer, 2);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Build the envelope, applying the payload cap.
|
|
96
|
+
*
|
|
97
|
+
* @param rows compactResult: flat row objects, straight from the driver.
|
|
98
|
+
* @param rowLimit the cap pushed into the SQL.
|
|
99
|
+
* @param result the full Malloy result, read only for its metadata.
|
|
100
|
+
*/
|
|
101
|
+
export function buildQueryEnvelope(
|
|
102
|
+
rows: unknown,
|
|
103
|
+
rowLimit: number,
|
|
104
|
+
result: Malloy.Result,
|
|
105
|
+
renderLogErrors: string[] = [],
|
|
106
|
+
limit = MAX_RESULT_CHARS,
|
|
107
|
+
rowLimitSource: QueryRowLimitSource = "server_default",
|
|
108
|
+
queryCorrelationId: string | null = null,
|
|
109
|
+
): QueryEnvelope {
|
|
110
|
+
const rowCount = Array.isArray(rows) ? rows.length : 0;
|
|
111
|
+
// Equality, not >=: the cap is pushed into the SQL, so the database cannot
|
|
112
|
+
// return more than it. Landing exactly on it is the signal.
|
|
113
|
+
//
|
|
114
|
+
// Restricted to the server default on purpose. resolveModelQueryRowLimit
|
|
115
|
+
// folds the query's own limit:/top: into the same cap, so equality also holds
|
|
116
|
+
// every time an author deliberately limited the query: a modelled `top: 10`
|
|
117
|
+
// view returning its 10 rows would otherwise be reported as cut off, and the
|
|
118
|
+
// Contract rule would tell an agent that a top-N is "not the answer". Only
|
|
119
|
+
// the silently-applied default is evidence that rows were left behind.
|
|
120
|
+
const limitHit =
|
|
121
|
+
rowLimitSource === "server_default" &&
|
|
122
|
+
rowLimit > 0 &&
|
|
123
|
+
rowCount === rowLimit;
|
|
124
|
+
|
|
125
|
+
const envelope: QueryEnvelope = {
|
|
126
|
+
rows,
|
|
127
|
+
_meta: {
|
|
128
|
+
schema: result.schema,
|
|
129
|
+
annotations: result.annotations ?? [],
|
|
130
|
+
connection_name: result.connection_name,
|
|
131
|
+
...(result.model_annotations !== undefined && {
|
|
132
|
+
model_annotations: result.model_annotations,
|
|
133
|
+
}),
|
|
134
|
+
...(result.query_timezone !== undefined && {
|
|
135
|
+
query_timezone: result.query_timezone,
|
|
136
|
+
}),
|
|
137
|
+
...(result.source_annotations !== undefined && {
|
|
138
|
+
source_annotations: result.source_annotations,
|
|
139
|
+
}),
|
|
140
|
+
},
|
|
141
|
+
_query_row_limit: rowLimit,
|
|
142
|
+
_limit_source: rowLimitSource,
|
|
143
|
+
_limit_hit: limitHit,
|
|
144
|
+
...(queryCorrelationId !== null && { _query_id: queryCorrelationId }),
|
|
145
|
+
...(renderLogErrors.length > 0 && { renderLogErrors }),
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
if (limitHit) {
|
|
149
|
+
envelope.warning =
|
|
150
|
+
`Returned exactly ${rowLimit} rows, the row limit applied to this query, so there are probably more. ` +
|
|
151
|
+
`This is not a complete result: add an explicit limit, aggregate, or filter rather than reporting these rows as the whole set.`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
return fitToBudget(envelope, limit);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Drop rows until the serialized envelope fits, by binary search on the row
|
|
159
|
+
* count.
|
|
160
|
+
*
|
|
161
|
+
* The marker fields are set BEFORE the search, so their serialized size counts
|
|
162
|
+
* against the limit. Adding them afterwards pushes the payload back over the cap
|
|
163
|
+
* the truncation existed to respect. `_returned_rows` is measured at `total`
|
|
164
|
+
* first, whose digit width is at least that of any value it ends up holding, so
|
|
165
|
+
* the finished payload stays under the limit. Credible's `_truncate_rows` does
|
|
166
|
+
* the same thing for the same reason.
|
|
167
|
+
*
|
|
168
|
+
* The search can land on zero rows, which needs its own wording rather than
|
|
169
|
+
* "Showing 0 of N rows": that reads as an empty result set, and an agent will
|
|
170
|
+
* report "no rows matched" for what is really one row too large to send. It is
|
|
171
|
+
* reachable, because the hard ceiling upstream is maxBytes (50MB by default), so
|
|
172
|
+
* a single row carrying a large text or JSON column passes
|
|
173
|
+
* assertWithinModelResponseLimits and arrives here. Both wordings are measured,
|
|
174
|
+
* and the search uses whichever is longer, so swapping one for the other after
|
|
175
|
+
* the fact cannot push the payload back over the cap.
|
|
176
|
+
*
|
|
177
|
+
* One case cannot be fixed by dropping rows: when the envelope minus its rows
|
|
178
|
+
* already exceeds the limit (a very wide schema in `_meta`). The result is then
|
|
179
|
+
* returned over-limit rather than emptied further, and the warning says so.
|
|
180
|
+
*/
|
|
181
|
+
function fitToBudget(envelope: QueryEnvelope, limit: number): QueryEnvelope {
|
|
182
|
+
if (serialize(envelope).length <= limit) return envelope;
|
|
183
|
+
|
|
184
|
+
const rows = envelope.rows;
|
|
185
|
+
if (!Array.isArray(rows) || rows.length === 0) return envelope;
|
|
186
|
+
const total = rows.length;
|
|
187
|
+
|
|
188
|
+
const truncating: QueryEnvelope = {
|
|
189
|
+
...envelope,
|
|
190
|
+
_rows_truncated: true,
|
|
191
|
+
_total_rows: total,
|
|
192
|
+
_returned_rows: total,
|
|
193
|
+
};
|
|
194
|
+
// The size warning joins any limit warning already present, and is included
|
|
195
|
+
// in the measurement for the same reason as the counts.
|
|
196
|
+
const sizeWarning = (kept: number) =>
|
|
197
|
+
`Showing ${kept} of ${total} rows; the rest were dropped to fit the result size limit. Narrow the query rather than paging through it.`;
|
|
198
|
+
const noneFitWarning =
|
|
199
|
+
`No rows fit the result size limit: the first of ${total} rows is too large to send on its own. ` +
|
|
200
|
+
`This is NOT an empty result and does not mean nothing matched. Select fewer columns, or truncate the oversized field, then run it again.`;
|
|
201
|
+
// Measure with whichever wording is longer, so the one actually returned is
|
|
202
|
+
// never bigger than the one the search sized the payload against.
|
|
203
|
+
const measured =
|
|
204
|
+
noneFitWarning.length > sizeWarning(total).length
|
|
205
|
+
? noneFitWarning
|
|
206
|
+
: sizeWarning(total);
|
|
207
|
+
truncating.warning = [envelope.warning, measured].filter(Boolean).join(" ");
|
|
208
|
+
|
|
209
|
+
let low = 0;
|
|
210
|
+
let high = total;
|
|
211
|
+
let best = 0;
|
|
212
|
+
while (low <= high) {
|
|
213
|
+
const mid = Math.floor((low + high) / 2);
|
|
214
|
+
if (
|
|
215
|
+
serialize({ ...truncating, rows: rows.slice(0, mid) }).length <= limit
|
|
216
|
+
) {
|
|
217
|
+
best = mid;
|
|
218
|
+
low = mid + 1;
|
|
219
|
+
} else {
|
|
220
|
+
high = mid - 1;
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
...truncating,
|
|
226
|
+
rows: rows.slice(0, best),
|
|
227
|
+
_returned_rows: best,
|
|
228
|
+
warning: [
|
|
229
|
+
envelope.warning,
|
|
230
|
+
best === 0 ? noneFitWarning : sizeWarning(best),
|
|
231
|
+
]
|
|
232
|
+
.filter(Boolean)
|
|
233
|
+
.join(" "),
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Serialize an envelope for transport, BigInt-safe. */
|
|
238
|
+
export function serializeEnvelope(envelope: QueryEnvelope): string {
|
|
239
|
+
return serialize(envelope);
|
|
240
|
+
}
|