@malloy-publisher/server 0.0.226 → 0.0.228

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.
Files changed (112) hide show
  1. package/README.docker.md +8 -8
  2. package/README.md +2 -11
  3. package/dist/app/assets/{EnvironmentPage-DvOJ7L_b.js → EnvironmentPage-EW2lbGvb.js} +1 -1
  4. package/dist/app/assets/{HomePage-CXguJsXS.js → HomePage-Bkwc9Woc.js} +1 -1
  5. package/dist/app/assets/{LightMode-ZsshUznu.js → LightMode-Bum_KBpN.js} +1 -1
  6. package/dist/app/assets/{MainPage-BIe0VwBa.js → MainPage-oiEy7TNM.js} +1 -1
  7. package/dist/app/assets/{MaterializationsPage-BuZ6UJVx.js → MaterializationsPage-C_VJsTgU.js} +1 -1
  8. package/dist/app/assets/{ModelPage-DsPf-s8B.js → ModelPage-z8REqAmk.js} +1 -1
  9. package/dist/app/assets/{PackagePage-CEVNAKZa.js → PackagePage-C2Vtt1Ln.js} +1 -1
  10. package/dist/app/assets/{RouteError-Chn7lL96.js → RouteError-DmJLpLXm.js} +1 -1
  11. package/dist/app/assets/{ThemeEditorPage-DWC_FdNU.js → ThemeEditorPage-BywFjC7A.js} +1 -1
  12. package/dist/app/assets/{WorkbookPage-CGrsFz8p.js → WorkbookPage-DCMizDMR.js} +1 -1
  13. package/dist/app/assets/{core-vVgoO8IR.es-BD_THWs_.js → core-CEDZMHV1.es-_yGzNgNH.js} +1 -1
  14. package/dist/app/assets/{index-D6YtyiJ0.js → index-CE9xhdra.js} +1 -1
  15. package/dist/app/assets/{index-BioohWQj.js → index-CdmFub34.js} +1 -1
  16. package/dist/app/assets/{index-gEWxu09x.js → index-DDMrjIT3.js} +1 -1
  17. package/dist/app/assets/{index-DNUZpnaa.js → index-EqslXZ44.js} +4 -4
  18. package/dist/app/index.html +1 -1
  19. package/dist/default-publisher.config.json +7 -7
  20. package/dist/package_load_worker.mjs +86 -24
  21. package/dist/runtime/publisher.js +5 -0
  22. package/dist/server.mjs +1415 -7876
  23. package/package.json +1 -4
  24. package/publisher.config.example.bigquery.json +7 -7
  25. package/publisher.config.example.duckdb.json +7 -7
  26. package/publisher.config.json +7 -11
  27. package/src/config.spec.ts +2 -2
  28. package/src/controller/package.controller.ts +62 -31
  29. package/src/default-publisher.config.json +7 -7
  30. package/src/health.ts +3 -8
  31. package/src/mcp/error_messages.ts +8 -37
  32. package/src/mcp/handler_utils.spec.ts +108 -0
  33. package/src/mcp/handler_utils.ts +99 -124
  34. package/src/mcp/mcp_constants.ts +0 -16
  35. package/src/mcp/server.protocol.spec.ts +138 -0
  36. package/src/mcp/server.ts +57 -37
  37. package/src/mcp/skills/build_skills_bundle.ts +1 -1
  38. package/src/mcp/skills/skills_bundle.json +1 -1
  39. package/src/mcp/tools/compile_tool.spec.ts +207 -0
  40. package/src/mcp/tools/compile_tool.ts +177 -0
  41. package/src/mcp/tools/docs_search_tool.ts +1 -1
  42. package/src/mcp/tools/execute_query_tool.spec.ts +143 -0
  43. package/src/mcp/tools/execute_query_tool.ts +39 -6
  44. package/src/mcp/tools/get_context_eval.ts +3 -3
  45. package/src/mcp/tools/get_context_tool.spec.ts +196 -1
  46. package/src/mcp/tools/get_context_tool.ts +165 -67
  47. package/src/mcp/tools/reload_package_tool.spec.ts +232 -0
  48. package/src/mcp/tools/reload_package_tool.ts +158 -0
  49. package/src/package_load/package_load_pool.ts +3 -0
  50. package/src/package_load/package_load_worker.ts +68 -24
  51. package/src/package_load/protocol.ts +16 -0
  52. package/src/package_load/rpc_wait_accountant.spec.ts +109 -0
  53. package/src/package_load/rpc_wait_accountant.ts +76 -0
  54. package/src/package_load_metrics.spec.ts +114 -0
  55. package/src/package_load_metrics.ts +127 -0
  56. package/src/pg_helpers.spec.ts +2 -206
  57. package/src/pg_helpers.ts +4 -120
  58. package/src/runtime/publisher.js +5 -0
  59. package/src/server.ts +7 -21
  60. package/src/service/environment.ts +71 -7
  61. package/src/service/model.spec.ts +92 -0
  62. package/src/service/model.ts +58 -7
  63. package/src/service/package.ts +113 -55
  64. package/src/service/package_reload_safety.spec.ts +193 -0
  65. package/src/test_helpers/metrics_harness.ts +40 -0
  66. package/tests/fixtures/query-givens/data/orders.csv +7 -0
  67. package/tests/fixtures/query-givens/model.malloy +34 -0
  68. package/tests/fixtures/query-givens/publisher.json +5 -0
  69. package/tests/harness/mcp_test_setup.ts +1 -1
  70. package/tests/integration/mcp/mcp_execute_query_tool.integration.spec.ts +22 -22
  71. package/tests/integration/mcp/mcp_transport.integration.spec.ts +7 -31
  72. package/tests/integration/query_givens/query_givens.integration.spec.ts +146 -0
  73. package/tests/integration/query_givens/query_givens_authorize.integration.spec.ts +121 -0
  74. package/tests/integration/sdk_givens/sdk_givens.integration.spec.ts +110 -0
  75. package/tests/integration/watch-mode/watch_mode.integration.spec.ts +0 -6
  76. package/dxt/malloy_bridge.py +0 -354
  77. package/dxt/manifest.json +0 -22
  78. package/src/dto/connection.dto.spec.ts +0 -186
  79. package/src/dto/connection.dto.ts +0 -308
  80. package/src/dto/index.ts +0 -2
  81. package/src/dto/package.dto.spec.ts +0 -42
  82. package/src/dto/package.dto.ts +0 -27
  83. package/src/dto/validate.spec.ts +0 -76
  84. package/src/dto/validate.ts +0 -31
  85. package/src/ducklake_version.spec.ts +0 -43
  86. package/src/ducklake_version.ts +0 -26
  87. package/src/mcp/agent_server.protocol.spec.ts +0 -78
  88. package/src/mcp/agent_server.spec.ts +0 -18
  89. package/src/mcp/agent_server.ts +0 -144
  90. package/src/mcp/prompts/handlers.ts +0 -84
  91. package/src/mcp/prompts/index.ts +0 -11
  92. package/src/mcp/prompts/prompt_definitions.ts +0 -160
  93. package/src/mcp/prompts/prompt_service.ts +0 -67
  94. package/src/mcp/prompts/utils.ts +0 -62
  95. package/src/mcp/resource_metadata.ts +0 -47
  96. package/src/mcp/resources/environment_resource.ts +0 -187
  97. package/src/mcp/resources/model_resource.ts +0 -155
  98. package/src/mcp/resources/notebook_resource.ts +0 -137
  99. package/src/mcp/resources/package_resource.ts +0 -373
  100. package/src/mcp/resources/query_resource.ts +0 -122
  101. package/src/mcp/resources/source_resource.ts +0 -141
  102. package/src/mcp/resources/view_resource.ts +0 -136
  103. package/src/mcp/tools/discovery_tools.ts +0 -280
  104. package/src/storage/BaseRepository.ts +0 -31
  105. package/src/storage/StorageManager.mock.ts +0 -50
  106. package/tests/harness/e2e.ts +0 -96
  107. package/tests/harness/mocks.ts +0 -39
  108. package/tests/harness/uris.ts +0 -31
  109. package/tests/integration/mcp/mcp_resource.integration.spec.ts +0 -655
  110. package/tests/integration/mcp/setup.spec.ts +0 -5
  111. package/tests/unit/mcp/prompt_definitions.test.ts +0 -102
  112. package/tests/unit/mcp/prompt_happy.test.ts +0 -51
@@ -0,0 +1,232 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { registerReloadPackageTool } from "./reload_package_tool";
3
+ import type { EnvironmentStore } from "../../service/environment_store";
4
+ import { PackageNotFoundError, ServiceUnavailableError } from "../../errors";
5
+
6
+ // Capture the handler registerReloadPackageTool passes to McpServer.tool, so it
7
+ // can be exercised against a mocked EnvironmentStore. The tool builds a
8
+ // PackageController internally, which calls environment.getPackage(pkg, reload),
9
+ // so the mock only needs getEnvironment -> { getPackage }.
10
+ type Handler = (params: Record<string, unknown>) => Promise<{
11
+ isError?: boolean;
12
+ content: Array<{ resource: { text: string } }>;
13
+ }>;
14
+
15
+ function captureHandler(store: Partial<EnvironmentStore>): Handler {
16
+ let handler: Handler | undefined;
17
+ const fakeServer = {
18
+ tool: (_name: string, _desc: string, _shape: unknown, h: Handler) => {
19
+ handler = h;
20
+ },
21
+ };
22
+ registerReloadPackageTool(fakeServer as never, store as EnvironmentStore);
23
+ if (!handler) throw new Error("handler was not registered");
24
+ return handler;
25
+ }
26
+
27
+ function parse(result: { content: Array<{ resource: { text: string } }> }) {
28
+ return JSON.parse(result.content[0].resource.text);
29
+ }
30
+
31
+ // A store whose package reload returns `metadata`. `location` is left undefined
32
+ // so PackageController takes the in-place-reload branch (no re-download). The
33
+ // optional `calls` array records the `reload` flag of every getPackage call.
34
+ function storeReturning(
35
+ metadata: Record<string, unknown>,
36
+ calls?: boolean[],
37
+ ): Partial<EnvironmentStore> {
38
+ return {
39
+ getEnvironment: async () =>
40
+ ({
41
+ getPackage: async (_pkg: string, reload: boolean) => {
42
+ calls?.push(reload);
43
+ return { getPackageMetadata: () => metadata } as never;
44
+ },
45
+ }) as never,
46
+ };
47
+ }
48
+
49
+ // A store whose cached package metadata carries `location`, so PackageController
50
+ // takes the re-fetch branch: installPackage instead of an in-place recompile.
51
+ // This is the only remaining path that overwrites on-disk edits, so it is worth
52
+ // pinning that the routing and the reported mode both match.
53
+ function storeWithInstallLocation(installed: Record<string, unknown>): {
54
+ store: Partial<EnvironmentStore>;
55
+ installCalls: string[];
56
+ } {
57
+ const installCalls: string[] = [];
58
+ return {
59
+ installCalls,
60
+ store: {
61
+ getEnvironment: async () =>
62
+ ({
63
+ getPackage: async () =>
64
+ ({
65
+ getPackageMetadata: () => ({
66
+ name: "ecommerce",
67
+ location: "https://github.com/example/pkg",
68
+ }),
69
+ }) as never,
70
+ installPackage: async (pkg: string) => {
71
+ installCalls.push(pkg);
72
+ return { getPackageMetadata: () => installed } as never;
73
+ },
74
+ }) as never,
75
+ },
76
+ };
77
+ }
78
+
79
+ const args = { environmentName: "malloy-samples", packageName: "ecommerce" };
80
+
81
+ describe("malloy_reloadPackage tool", () => {
82
+ it("returns status reloaded with the package name", async () => {
83
+ const handler = captureHandler(storeReturning({ name: "ecommerce" }));
84
+ const result = await handler(args);
85
+ expect(result.isError).toBe(false);
86
+ expect(parse(result)).toEqual({
87
+ status: "reloaded",
88
+ mode: "in-place",
89
+ name: "ecommerce",
90
+ });
91
+ });
92
+
93
+ it("includes description and non-empty warnings", async () => {
94
+ const warnings = [
95
+ {
96
+ model: "ecommerce.malloy",
97
+ target: "top_categories",
98
+ severity: "error",
99
+ },
100
+ ];
101
+ const handler = captureHandler(
102
+ storeReturning({ name: "ecommerce", description: "shop", warnings }),
103
+ );
104
+ const parsed = parse(await handler(args));
105
+ expect(parsed).toEqual({
106
+ status: "reloaded",
107
+ mode: "in-place",
108
+ name: "ecommerce",
109
+ description: "shop",
110
+ warnings,
111
+ });
112
+ });
113
+
114
+ it("omits warnings when the reloaded package has none", async () => {
115
+ const handler = captureHandler(
116
+ storeReturning({ name: "ecommerce", warnings: [] }),
117
+ );
118
+ const parsed = parse(await handler(args));
119
+ expect(parsed.warnings).toBeUndefined();
120
+ expect(parsed.status).toBe("reloaded");
121
+ });
122
+
123
+ it("forwards reload=true (recompiles, not just reads)", async () => {
124
+ const calls: boolean[] = [];
125
+ const handler = captureHandler(
126
+ storeReturning({ name: "ecommerce" }, calls),
127
+ );
128
+ await handler(args);
129
+ // The controller probes cached metadata (reload=false) then reloads
130
+ // (reload=true); the tool must trigger the recompile.
131
+ expect(calls).toContain(true);
132
+ });
133
+
134
+ it("surfaces a thrown error as a tool error, not a transport fault", async () => {
135
+ const handler = captureHandler({
136
+ getEnvironment: async () => {
137
+ throw new Error("Environment 'nope' could not be resolved");
138
+ },
139
+ });
140
+ const result = await handler({ ...args, environmentName: "nope" });
141
+ expect(result.isError).toBe(true);
142
+ expect(parse(result).error).toBeDefined();
143
+ });
144
+
145
+ it("reports a missing package as not-found, not as a Malloy syntax problem", async () => {
146
+ // Pin the remediation text, not just that an error came back. Asserting
147
+ // only that `error` is defined is what let every error class funnel
148
+ // through the Malloy helper unnoticed: a typo'd package name told the
149
+ // caller to go check its Malloy syntax.
150
+ const handler = captureHandler({
151
+ getEnvironment: async () => {
152
+ throw new PackageNotFoundError("Package 'nope' not found");
153
+ },
154
+ });
155
+ const parsed = parse(await handler({ ...args, packageName: "nope" }));
156
+ expect(parsed.error).toContain("Resource not found");
157
+ expect(JSON.stringify(parsed.suggestions)).not.toContain("Malloy file");
158
+ });
159
+
160
+ it("reports back-pressure as retryable, not as a Malloy syntax problem", async () => {
161
+ const handler = captureHandler({
162
+ getEnvironment: async () => {
163
+ throw new ServiceUnavailableError("Memory limit reached");
164
+ },
165
+ });
166
+ const parsed = parse(await handler(args));
167
+ expect(parsed.error).toContain("Memory limit reached");
168
+ expect(JSON.stringify(parsed.suggestions)).toContain("Retry");
169
+ expect(JSON.stringify(parsed.suggestions)).not.toContain("Malloy file");
170
+ });
171
+
172
+ it("surfaces a hard compile failure on reload as a tool error", async () => {
173
+ // A Package.create compile failure propagates out of environment.getPackage
174
+ // (the reload site), not out of getEnvironment. The controller swallows the
175
+ // first probe call and re-throws on the reload call.
176
+ const handler = captureHandler({
177
+ getEnvironment: async () =>
178
+ ({
179
+ getPackage: async () => {
180
+ throw new Error("'nonexistent_status_field' is not defined");
181
+ },
182
+ }) as never,
183
+ });
184
+ const result = await handler(args);
185
+ expect(result.isError).toBe(true);
186
+ expect(parse(result).error).toBeDefined();
187
+ });
188
+
189
+ it("reports mode in-place for a package with no install location", async () => {
190
+ const handler = captureHandler(storeReturning({ name: "ecommerce" }));
191
+ expect(parse(await handler(args)).mode).toBe("in-place");
192
+ });
193
+
194
+ it("re-fetches and reports mode reinstalled when the package carries an install location", async () => {
195
+ // The one path that still overwrites on-disk edits. It must route through
196
+ // installPackage, and the payload must say so, since an agent cannot
197
+ // otherwise tell that its saved edit was just re-fetched over.
198
+ const { store, installCalls } = storeWithInstallLocation({
199
+ name: "ecommerce",
200
+ location: "https://github.com/example/pkg",
201
+ });
202
+ const handler = captureHandler(store);
203
+ const result = await handler(args);
204
+ expect(result.isError).toBe(false);
205
+ expect(installCalls).toEqual(["ecommerce"]);
206
+ expect(parse(result).mode).toBe("reinstalled");
207
+ });
208
+
209
+ it("never echoes the package location back to the caller", async () => {
210
+ // The payload hand-picks fields; REST spreads the whole ApiPackage. Pin
211
+ // that the allowlist holds, since location is the one field here that is
212
+ // deployment detail rather than something an agent needs.
213
+ const { store } = storeWithInstallLocation({
214
+ name: "ecommerce",
215
+ location: "https://github.com/example/pkg",
216
+ });
217
+ const parsed = parse(await captureHandler(store)(args));
218
+ expect(parsed.location).toBeUndefined();
219
+ });
220
+
221
+ it("surfaces exploresWarnings (a mistyped explores entry is not swallowed)", async () => {
222
+ const exploresWarnings = [
223
+ "explore 'ordrs' does not resolve to a model in this package",
224
+ ];
225
+ const handler = captureHandler(
226
+ storeReturning({ name: "ecommerce", exploresWarnings }),
227
+ );
228
+ const parsed = parse(await handler(args));
229
+ expect(parsed.status).toBe("reloaded");
230
+ expect(parsed.exploresWarnings).toEqual(exploresWarnings);
231
+ });
232
+ });
@@ -0,0 +1,158 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { z } from "zod";
3
+ import { logger } from "../../logger";
4
+ import { EnvironmentStore } from "../../service/environment_store";
5
+ import { PackageController } from "../../controller/package.controller";
6
+ import { type ErrorDetails } from "../error_messages";
7
+ import { buildMalloyUri, classifyToolError } from "../handler_utils";
8
+
9
+ // Zod shape for malloy_reloadPackage. environmentName/packageName mirror the
10
+ // other tools and point the agent at malloy_getContext for name discovery.
11
+ const reloadShape = {
12
+ environmentName: z
13
+ .string()
14
+ .describe(
15
+ "Environment name. Call malloy_getContext with no arguments to list the available environments.",
16
+ ),
17
+ packageName: z
18
+ .string()
19
+ .describe(
20
+ "Package to reload. Call malloy_getContext with just environmentName to list its packages.",
21
+ ),
22
+ };
23
+
24
+ /**
25
+ * What a failed reload does, in one sentence, shared with MCP_INSTRUCTIONS
26
+ * rather than restated there. Both surfaces describe the same behavior, so one
27
+ * copy is what stops them drifting.
28
+ *
29
+ * SECURITY: interpolated into MCP_INSTRUCTIONS, which is delivered
30
+ * pre-authorization to any connecting client. Keep this a static string
31
+ * literal; never derive it from config, environment, or request data.
32
+ */
33
+ export const RELOAD_FAILURE_IS_SAFE =
34
+ "A reload that fails to compile leaves your files on disk alone and keeps serving the previously compiled model, returning the compile errors.";
35
+
36
+ const RELOAD_DESCRIPTION = `Reload a package so edits to its model files on disk are picked up, making newly added or changed sources, views, and named queries resolvable by malloy_executeQuery WITHOUT restarting the server. Publisher compiles each configured package at boot and serves that cached model, so a source or view you add afterwards is not queryable by name until the package is reloaded. Use this to close the edit -> run loop after saving a model change.
37
+
38
+ ${RELOAD_FAILURE_IS_SAFE} Running malloy_compile first is still the faster way to see diagnostics, and it keeps a broken model from ever reaching the reload.
39
+
40
+ ## Parameters
41
+ - environmentName, packageName (required): the package to recompile. Use the names malloy_getContext returns.
42
+
43
+ ## Behavior
44
+ Recompiles the package from its current on-disk content under publisher_data/, so your saved edits are picked up. This is the path every package from publisher.config.json takes. A package whose stored metadata carries an install location (only a PATCH that supplies one sets it) is re-fetched from that source instead, which overwrites on-disk edits.
45
+
46
+ ## Response
47
+ A JSON object with status "reloaded", a mode of "in-place" or "reinstalled", the package name, any render-tag warnings, and any exploresWarnings (curated-discovery entries that did not resolve to a model). Check mode if you had unsaved-elsewhere edits on disk: "in-place" recompiled them, "reinstalled" re-fetched over them. A reload that hits a hard compile error returns an error payload instead.`;
48
+
49
+ /**
50
+ * Registers the malloy_reloadPackage MCP tool: recompiles a package from its
51
+ * on-disk content so a saved model edit becomes queryable by name without a
52
+ * server restart. Wraps the same PackageController.getPackage(reload=true) path
53
+ * the REST GET /environments/:env/packages/:pkg?reload=true endpoint uses, so it
54
+ * adds no capability beyond that already-exposed endpoint (SECURITY: parity with
55
+ * REST. The MCP surface is unauthenticated, and so is that endpoint; a reload
56
+ * mutates the shared in-memory package but returns only names and warnings,
57
+ * never row data or the package's location).
58
+ */
59
+ export function registerReloadPackageTool(
60
+ mcpServer: McpServer,
61
+ environmentStore: EnvironmentStore,
62
+ ): void {
63
+ const packageController = new PackageController(environmentStore);
64
+
65
+ mcpServer.tool(
66
+ "malloy_reloadPackage",
67
+ RELOAD_DESCRIPTION,
68
+ reloadShape,
69
+ async (params) => {
70
+ const { environmentName, packageName } = params;
71
+
72
+ logger.info("[MCP Tool reloadPackage] Reloading package", {
73
+ environmentName,
74
+ packageName,
75
+ });
76
+
77
+ const uri = buildMalloyUri(
78
+ { environment: environmentName, package: packageName },
79
+ "reloadPackage",
80
+ );
81
+
82
+ try {
83
+ const { metadata: pkg, mode } =
84
+ await packageController.reloadPackage(
85
+ environmentName,
86
+ packageName,
87
+ );
88
+
89
+ const payload = {
90
+ status: "reloaded" as const,
91
+ // Which path ran. "in-place" recompiled the tree on disk and left
92
+ // it alone; "reinstalled" re-fetched from the package's install
93
+ // location, so any on-disk edits are gone. The caller cannot tell
94
+ // these apart otherwise, and only one of them keeps their work.
95
+ mode,
96
+ name: pkg.name,
97
+ ...(pkg.description !== undefined && {
98
+ description: pkg.description,
99
+ }),
100
+ ...(pkg.warnings !== undefined &&
101
+ pkg.warnings.length > 0 && { warnings: pkg.warnings }),
102
+ // exploresWarnings is a distinct signal from render-tag warnings:
103
+ // it flags a curated-discovery (explores) entry that did not
104
+ // resolve to a model, so a mistyped explores edit is not silently
105
+ // swallowed on reload.
106
+ ...(pkg.exploresWarnings !== undefined &&
107
+ pkg.exploresWarnings.length > 0 && {
108
+ exploresWarnings: pkg.exploresWarnings,
109
+ }),
110
+ };
111
+
112
+ return {
113
+ isError: false,
114
+ content: [
115
+ {
116
+ type: "resource" as const,
117
+ resource: {
118
+ type: "application/json",
119
+ uri,
120
+ text: JSON.stringify(payload),
121
+ },
122
+ },
123
+ ],
124
+ };
125
+ } catch (error) {
126
+ // Unknown environment/package, or a compile error in the reloaded
127
+ // package: surface as a clean isError payload rather than a
128
+ // transport fault.
129
+ logger.warn("[MCP Tool reloadPackage] reload failed", {
130
+ environmentName,
131
+ packageName,
132
+ error: error instanceof Error ? error.message : String(error),
133
+ });
134
+ const errorDetails: ErrorDetails = classifyToolError(
135
+ "reloadPackage",
136
+ `${environmentName}/${packageName}`,
137
+ error,
138
+ );
139
+ return {
140
+ isError: true,
141
+ content: [
142
+ {
143
+ type: "resource" as const,
144
+ resource: {
145
+ type: "application/json",
146
+ uri,
147
+ text: JSON.stringify({
148
+ error: errorDetails.message,
149
+ suggestions: errorDetails.suggestions,
150
+ }),
151
+ },
152
+ },
153
+ ],
154
+ };
155
+ }
156
+ },
157
+ );
158
+ }
@@ -247,6 +247,8 @@ export interface LoadPackageOutcome {
247
247
  }
248
248
  >;
249
249
  loadDurationMs: number;
250
+ /** Per-load phase timing breakdown (see {@link LoadPackageResult.timings}). */
251
+ timings: LoadPackageResult["timings"];
250
252
  }
251
253
 
252
254
  // ──────────────────────────────────────────────────────────────────────
@@ -844,6 +846,7 @@ function adaptResult(result: LoadPackageResult): LoadPackageOutcome {
844
846
  sourceInfos: m.sourceInfos as Malloy.SourceInfo[] | undefined,
845
847
  })),
846
848
  loadDurationMs: result.loadDurationMs,
849
+ timings: result.timings,
847
850
  };
848
851
  }
849
852
 
@@ -99,6 +99,7 @@ import {
99
99
  type MalloyGivenApi,
100
100
  } from "../service/given";
101
101
  import { ignoreDotfiles } from "../utils";
102
+ import { RpcWaitAccountant } from "./rpc_wait_accountant";
102
103
  import type {
103
104
  ConnectionMetadata,
104
105
  ConnectionMetadataRequest,
@@ -152,6 +153,13 @@ function callMain<T>(send: (requestId: string) => void): Promise<T> {
152
153
  });
153
154
  }
154
155
 
156
+ // Per-load phase timing: brackets the wall-clock spent awaiting proxied schema
157
+ // fetches so `loadPackage` can separate connection I/O from compile CPU. The
158
+ // pool runs one load per worker at a time, so a single module-level instance
159
+ // is safe; it's still keyed by jobId to shrug off a straggler fetch from a
160
+ // prior, reused-worker load. See {@link RpcWaitAccountant}.
161
+ const schemaWait = new RpcWaitAccountant();
162
+
155
163
  function dispatchMainResponse(message: MainToWorkerMessage): void {
156
164
  if (
157
165
  message.type === "schema-for-tables-response" ||
@@ -202,18 +210,25 @@ class ProxyConnection {
202
210
  schemas: Record<string, TableSourceDef>;
203
211
  errors: Record<string, string>;
204
212
  }> {
205
- const response = await callMain<SchemaForTablesResponse>((requestId) => {
206
- const req: SchemaForTablesRequest = {
207
- type: "schema-for-tables",
208
- requestId,
209
- jobId: this.jobId,
210
- connectionName: this.name,
211
- tables,
212
- options: serializeFetchOptions(options),
213
- };
214
- port.postMessage(req);
215
- });
216
- return { schemas: response.schemas, errors: response.errors };
213
+ schemaWait.noteStart(this.jobId);
214
+ try {
215
+ const response = await callMain<SchemaForTablesResponse>(
216
+ (requestId) => {
217
+ const req: SchemaForTablesRequest = {
218
+ type: "schema-for-tables",
219
+ requestId,
220
+ jobId: this.jobId,
221
+ connectionName: this.name,
222
+ tables,
223
+ options: serializeFetchOptions(options),
224
+ };
225
+ port.postMessage(req);
226
+ },
227
+ );
228
+ return { schemas: response.schemas, errors: response.errors };
229
+ } finally {
230
+ schemaWait.noteSettle(this.jobId);
231
+ }
217
232
  }
218
233
 
219
234
  async fetchSchemaForSQLStruct(
@@ -223,17 +238,23 @@ class ProxyConnection {
223
238
  | { structDef: SQLSourceDef; error?: undefined }
224
239
  | { error: string; structDef?: undefined }
225
240
  > {
226
- const response = await callMain<SchemaForSqlResponse>((requestId) => {
227
- const req: SchemaForSqlRequest = {
228
- type: "schema-for-sql",
229
- requestId,
230
- jobId: this.jobId,
231
- connectionName: this.name,
232
- sentence: sentence as unknown,
233
- options: serializeFetchOptions(options),
234
- };
235
- port.postMessage(req);
236
- });
241
+ schemaWait.noteStart(this.jobId);
242
+ let response: SchemaForSqlResponse;
243
+ try {
244
+ response = await callMain<SchemaForSqlResponse>((requestId) => {
245
+ const req: SchemaForSqlRequest = {
246
+ type: "schema-for-sql",
247
+ requestId,
248
+ jobId: this.jobId,
249
+ connectionName: this.name,
250
+ sentence: sentence as unknown,
251
+ options: serializeFetchOptions(options),
252
+ };
253
+ port.postMessage(req);
254
+ });
255
+ } finally {
256
+ schemaWait.noteSettle(this.jobId);
257
+ }
237
258
  if (response.error !== undefined) return { error: response.error };
238
259
  if (response.structDef === undefined) {
239
260
  return { error: "Empty SQL schema response from main thread" };
@@ -856,18 +877,41 @@ async function loadPackage(
856
877
  const allFiles = await listPackageFiles(job.packagePath);
857
878
  const modelPaths = filterModelPaths(allFiles);
858
879
 
880
+ // Bracket the compile region: only work from here on is compilation +
881
+ // proxied schema fetches. The setup above (manifest read + file listing)
882
+ // is excluded so it can't inflate the compile figure — it stays in the
883
+ // derivable remainder (loadDuration - compile - schemaFetch). Begin the
884
+ // schema-fetch accounting HERE, at the region boundary, not at load start:
885
+ // that keeps `compileDurationMs = compileRegion - schemaFetchWait` exact
886
+ // regardless of whether any fetch ever happens during setup (none do
887
+ // today, but this stops that assumption from silently mattering).
888
+ const compileRegionStart = performance.now();
889
+ schemaWait.begin(job.requestId);
859
890
  const models = await Promise.all(
860
891
  modelPaths.map((modelPath) =>
861
892
  compileOneModel(job, malloyConfig, modelPath),
862
893
  ),
863
894
  );
864
895
 
896
+ const loadEnd = performance.now();
897
+ const schemaFetchDurationMs = schemaWait.waitMs;
865
898
  return {
866
899
  type: "load-package-result",
867
900
  requestId: job.requestId,
868
901
  packageMetadata,
869
902
  models,
870
- loadDurationMs: performance.now() - loadStart,
903
+ loadDurationMs: loadEnd - loadStart,
904
+ timings: {
905
+ // Compile-region wall minus the schema-fetch wait it contains — a
906
+ // conservative ceiling on compile CPU (clamped: rounding can nudge
907
+ // it slightly negative).
908
+ compileDurationMs: Math.max(
909
+ 0,
910
+ loadEnd - compileRegionStart - schemaFetchDurationMs,
911
+ ),
912
+ schemaFetchDurationMs,
913
+ schemaFetchCount: schemaWait.fetches,
914
+ },
871
915
  };
872
916
  }
873
917
 
@@ -189,6 +189,22 @@ export interface LoadPackageResult {
189
189
  models: SerializedModel[];
190
190
  /** Wall-clock ms inside the worker for the full package load. */
191
191
  loadDurationMs: number;
192
+ /**
193
+ * Per-load timing breakdown (subset of {@link loadDurationMs}; the
194
+ * remainder is worker setup + post-compile extraction). See
195
+ * `rpc_wait_accountant.ts` for how compile time is separated from I/O.
196
+ */
197
+ timings: {
198
+ /**
199
+ * Compile-region wall-clock minus time awaiting proxied schema fetches —
200
+ * a conservative ceiling on Malloy compile CPU.
201
+ */
202
+ compileDurationMs: number;
203
+ /** Wall-clock awaiting proxied connection schema fetches (union). */
204
+ schemaFetchDurationMs: number;
205
+ /** Number of proxied connection schema fetches the load drove. */
206
+ schemaFetchCount: number;
207
+ };
192
208
  }
193
209
 
194
210
  export interface LoadPackageError {
@@ -0,0 +1,109 @@
1
+ import { describe, expect, it } from "bun:test";
2
+
3
+ import { RpcWaitAccountant } from "./rpc_wait_accountant";
4
+
5
+ /** Accountant driven by a settable fake clock. */
6
+ function withClock(): { acc: RpcWaitAccountant; at: (ms: number) => void } {
7
+ let t = 0;
8
+ const acc = new RpcWaitAccountant(() => t);
9
+ return { acc, at: (ms) => (t = ms) };
10
+ }
11
+
12
+ describe("RpcWaitAccountant", () => {
13
+ it("brackets a single fetch's wait", () => {
14
+ const { acc, at } = withClock();
15
+ at(0);
16
+ acc.begin("A");
17
+ at(10);
18
+ acc.noteStart("A");
19
+ at(60);
20
+ acc.noteSettle("A");
21
+ expect(acc.waitMs).toBe(50);
22
+ });
23
+
24
+ it("counts overlapping fetches as their union, not the sum", () => {
25
+ const { acc, at } = withClock();
26
+ at(0);
27
+ acc.begin("A");
28
+ at(0);
29
+ acc.noteStart("A"); // window opens
30
+ at(10);
31
+ acc.noteStart("A"); // second fetch, window stays open
32
+ at(40);
33
+ acc.noteSettle("A"); // one still outstanding
34
+ at(60);
35
+ acc.noteSettle("A"); // window closes
36
+ expect(acc.waitMs).toBe(60); // union [0,60], not 30+50
37
+ });
38
+
39
+ it("accumulates disjoint fetch windows", () => {
40
+ const { acc, at } = withClock();
41
+ at(0);
42
+ acc.begin("A");
43
+ at(0);
44
+ acc.noteStart("A");
45
+ at(20);
46
+ acc.noteSettle("A");
47
+ at(50);
48
+ acc.noteStart("A");
49
+ at(70);
50
+ acc.noteSettle("A");
51
+ expect(acc.waitMs).toBe(40);
52
+ });
53
+
54
+ it("ignores a straggler fetch from a prior reused-worker load", () => {
55
+ const { acc, at } = withClock();
56
+ at(0);
57
+ acc.begin("A");
58
+ at(0);
59
+ acc.noteStart("A"); // load A opens a fetch and never settles it (failed)
60
+
61
+ at(100);
62
+ acc.begin("B"); // worker reused for load B
63
+ at(110);
64
+ acc.noteStart("B");
65
+ at(130);
66
+ acc.noteSettle("B");
67
+
68
+ at(140);
69
+ acc.noteSettle("A"); // A's late response — must be a no-op
70
+
71
+ expect(acc.waitMs).toBe(20); // only B's [110,130]
72
+ });
73
+
74
+ it("ignores a stray start from a non-active load", () => {
75
+ const { acc, at } = withClock();
76
+ at(0);
77
+ acc.begin("B");
78
+ at(10);
79
+ acc.noteStart("A"); // wrong load
80
+ at(50);
81
+ acc.noteSettle("A");
82
+ expect(acc.waitMs).toBe(0);
83
+ });
84
+
85
+ it("counts active-load fetches only", () => {
86
+ const { acc, at } = withClock();
87
+ at(0);
88
+ acc.begin("B");
89
+ acc.noteStart("B");
90
+ acc.noteSettle("B");
91
+ acc.noteStart("B");
92
+ acc.noteStart("A"); // straggler — not counted
93
+ expect(acc.fetches).toBe(2);
94
+ });
95
+
96
+ it("begin() discards prior-load state", () => {
97
+ const { acc, at } = withClock();
98
+ at(0);
99
+ acc.begin("A");
100
+ at(0);
101
+ acc.noteStart("A");
102
+ at(50);
103
+ acc.noteSettle("A");
104
+ expect(acc.waitMs).toBe(50);
105
+ at(60);
106
+ acc.begin("B");
107
+ expect(acc.waitMs).toBe(0);
108
+ });
109
+ });