@malloy-publisher/server 0.0.229 → 0.0.230

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 (51) hide show
  1. package/dist/app/api-doc.yaml +18 -9
  2. package/dist/app/assets/{EnvironmentPage-QOoHiVeJ.js → EnvironmentPage-wa_EPkwK.js} +1 -1
  3. package/dist/app/assets/{HomePage-C71GOfVW.js → HomePage-jnCrupQp.js} +1 -1
  4. package/dist/app/assets/{LightMode-CrgCAwLe.js → LightMode-DYbwNULZ.js} +1 -1
  5. package/dist/app/assets/{MainPage-BG5__FN3.js → MainPage-CuJLrPNI.js} +1 -1
  6. package/dist/app/assets/{MaterializationsPage-DE6PnrDR.js → MaterializationsPage-D_67x2ee.js} +1 -1
  7. package/dist/app/assets/{ModelPage-CcBjcbLm.js → ModelPage-D5JtAWqR.js} +1 -1
  8. package/dist/app/assets/{PackagePage-JTy3ztkB.js → PackagePage-BRwtqUSG.js} +1 -1
  9. package/dist/app/assets/{RouteError-Cymbp47a.js → RouteError-CBNNrnSD.js} +1 -1
  10. package/dist/app/assets/{ThemeEditorPage-C_nMnHr8.js → ThemeEditorPage-CTCeBneA.js} +1 -1
  11. package/dist/app/assets/{WorkbookPage-CPQu-DQx.js → WorkbookPage-SN6f1RBm.js} +1 -1
  12. package/dist/app/assets/{core-Coi3caGs.es-CSOmajHS.js → core-Dp3q5Ieu.es-CD5FvM2s.js} +1 -1
  13. package/dist/app/assets/{index-DlWCXghy.js → index-B3Nn8Vm2.js} +459 -446
  14. package/dist/app/assets/index-BLCx1EdC.js +18 -0
  15. package/dist/app/assets/{index-DxArlgRD.js → index-C_tJstcx.js} +4 -4
  16. package/dist/app/assets/{index-CcuuST2X.js → index-CfmBVB6M.js} +1 -1
  17. package/dist/app/assets/{index-CkmABCAw.js → index-DU4r7GdU.js} +435 -422
  18. package/dist/app/index.html +1 -1
  19. package/dist/package_load_worker.mjs +108 -7
  20. package/dist/server.mjs +575 -49
  21. package/package.json +12 -12
  22. package/scripts/bake-duckdb-extensions.js +5 -2
  23. package/src/config.ts +40 -0
  24. package/src/ducklake_version.spec.ts +163 -0
  25. package/src/ducklake_version.ts +153 -0
  26. package/src/errors.ts +12 -0
  27. package/src/malloy_pin_prereqs.spec.ts +25 -0
  28. package/src/mcp/skills/skills_bundle.json +1 -1
  29. package/src/server.ts +7 -0
  30. package/src/service/authorize.spec.ts +22 -0
  31. package/src/service/authorize.ts +267 -10
  32. package/src/service/authorize_integration.spec.ts +1068 -26
  33. package/src/service/connection.spec.ts +71 -0
  34. package/src/service/connection.ts +312 -25
  35. package/src/service/connection_config.spec.ts +21 -0
  36. package/src/service/connection_config.ts +15 -1
  37. package/src/service/ducklake_lazy_attach.spec.ts +110 -0
  38. package/src/service/environment.ts +43 -9
  39. package/src/service/environment_store.spec.ts +197 -12
  40. package/src/service/environment_store.ts +88 -14
  41. package/src/service/extension_fetch_policy.spec.ts +256 -0
  42. package/src/service/materialization_scheduler.spec.ts +29 -0
  43. package/src/service/materialization_service.spec.ts +119 -1
  44. package/src/service/model.spec.ts +67 -0
  45. package/src/service/model.ts +656 -31
  46. package/src/service/package.spec.ts +38 -0
  47. package/src/service/package.ts +12 -1
  48. package/src/storage/duckdb/MaterializationRepository.spec.ts +39 -2
  49. package/src/storage/duckdb/MaterializationRepository.ts +12 -0
  50. package/tests/integration/materialization/scheduler_transitions.integration.spec.ts +256 -0
  51. package/dist/app/assets/index-CM2qhQCI.js +0 -18
@@ -95,6 +95,44 @@ describe("service/package", () => {
95
95
  expect(pkg).toBeInstanceOf(Package);
96
96
  });
97
97
 
98
+ describe("per-package sandbox extension pinning", () => {
99
+ const originalPolicy = process.env.EXTENSION_FETCH_POLICY;
100
+ afterEach(() => {
101
+ if (originalPolicy === undefined) {
102
+ delete process.env.EXTENSION_FETCH_POLICY;
103
+ } else {
104
+ process.env.EXTENSION_FETCH_POLICY = originalPolicy;
105
+ }
106
+ });
107
+
108
+ it(
109
+ "pins autoinstall off on the :memory: sandbox under local-only",
110
+ async () => {
111
+ // Regression guard for the sandbox bypass: the per-package sandbox
112
+ // has no attached databases, so the environment attach paths never
113
+ // touch it. Under local-only its session must still be pinned
114
+ // against DuckDB's implicit auto-install, or a sandbox query
115
+ // referencing an unbaked extension could silently fetch from the
116
+ // CDN. Uses a spy (not a stub) so real DuckDB runs the pragma.
117
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
118
+ const spy = sinon.spy(DuckDBConnection.prototype, "runSQL");
119
+ await Package.create(
120
+ "testProject",
121
+ "testPackage",
122
+ testPackageDirectory,
123
+ new Map(),
124
+ );
125
+ const issued = spy.getCalls().map((c) => String(c.args[0]));
126
+ expect(
127
+ issued.some((s) =>
128
+ /autoinstall_known_extensions\s*=\s*false/i.test(s),
129
+ ),
130
+ ).toBe(true);
131
+ },
132
+ { timeout: 30000 },
133
+ );
134
+ });
135
+
98
136
  describe("instance methods", () => {
99
137
  describe("create", () => {
100
138
  it("should throw PackageNotFoundError if the package manifest does not exist", async () => {
@@ -2,6 +2,7 @@ import * as fs from "fs/promises";
2
2
  import * as path from "path";
3
3
 
4
4
  import "@malloydata/db-duckdb/native";
5
+ import { DuckDBConnection } from "@malloydata/db-duckdb";
5
6
  import {
6
7
  Connection,
7
8
  ConnectionRuntime,
@@ -27,6 +28,7 @@ import {
27
28
  PackageNotFoundError,
28
29
  ServiceUnavailableError,
29
30
  } from "../errors";
31
+ import { applyExtensionSessionSettings } from "./connection";
30
32
  import { formatDuration, logger } from "../logger";
31
33
  import {
32
34
  recordBuildPlanComputeDuration,
@@ -1256,7 +1258,16 @@ export class Package {
1256
1258
  malloyConfig.wrapConnections((base) => ({
1257
1259
  lookupConnection: async (name?: string) => {
1258
1260
  if (!name || name === "duckdb") {
1259
- return base.lookupConnection(name);
1261
+ const connection = await base.lookupConnection(name);
1262
+ // The per-package :memory: sandbox is a Publisher-owned DuckDB
1263
+ // session too. Pin it against implicit auto-install so
1264
+ // EXTENSION_FETCH_POLICY covers it — otherwise local-only's
1265
+ // no-network guarantee had a hole here (the sandbox has no
1266
+ // attached databases, so the env attach paths never touch it).
1267
+ if (connection instanceof DuckDBConnection) {
1268
+ await applyExtensionSessionSettings(connection);
1269
+ }
1270
+ return connection;
1260
1271
  }
1261
1272
  // Resolve against the *current* environment MalloyConfig so a
1262
1273
  // connection-generation swap on Environment propagates without a
@@ -3,16 +3,21 @@ import { DuckDBConnection } from "./DuckDBConnection";
3
3
  import { MaterializationRepository } from "./MaterializationRepository";
4
4
  import { initializeSchema } from "./schema";
5
5
 
6
- // Capture the SQL + params of the last query without touching a real DuckDB.
6
+ // Capture the SQL + params of reads (all) and writes (run) without touching a
7
+ // real DuckDB.
7
8
  function fakeRepo() {
8
9
  const calls: Array<{ sql: string; params: unknown[] }> = [];
10
+ const runCalls: Array<{ sql: string; params: unknown[] }> = [];
9
11
  const db = {
10
12
  all: async (sql: string, params: unknown[]) => {
11
13
  calls.push({ sql, params });
12
14
  return [];
13
15
  },
16
+ run: async (sql: string, params: unknown[]) => {
17
+ runCalls.push({ sql, params });
18
+ },
14
19
  } as unknown as DuckDBConnection;
15
- return { repo: new MaterializationRepository(db), calls };
20
+ return { repo: new MaterializationRepository(db), calls, runCalls };
16
21
  }
17
22
 
18
23
  describe("MaterializationRepository list bounds", () => {
@@ -152,3 +157,35 @@ describe("MaterializationRepository.getLatestScheduledFireAt (real DuckDB)", ()
152
157
  expect(await repo.getLatestScheduledFireAt(ENV_ID, PKG)).toBeNull();
153
158
  });
154
159
  });
160
+
161
+ // The publisher tracks materialization *records*; dropping the physical tables
162
+ // is opt-in (deleteMaterialization({ dropTables })) and otherwise the caller's
163
+ // responsibility. These cascade deletes therefore remove records only — they
164
+ // must never issue DDL — so a materialized table intentionally outlives the
165
+ // record when an environment or package is deleted. Locking that in guards the
166
+ // contract against a future refactor that "helpfully" adds a DROP here (which
167
+ // would fire against a possibly-already-torn-down connection on env delete).
168
+ //
169
+ // This pins DDL out of the low-level record deletes; it does not close the
170
+ // standalone GC gap (#901: nothing drops those tables today, so they accumulate
171
+ // in the warehouse). #901's best-effort drop-before-teardown lives ABOVE these
172
+ // methods, so adding it completes the design and leaves this test green.
173
+ describe("MaterializationRepository cascade deletes are records-only", () => {
174
+ it("deleteByEnvironmentId issues a single DELETE and no DDL", async () => {
175
+ const { repo, runCalls } = fakeRepo();
176
+ await repo.deleteByEnvironmentId("env-1");
177
+ expect(runCalls.length).toBe(1);
178
+ expect(runCalls[0].sql).toContain("DELETE FROM materializations");
179
+ expect(runCalls[0].sql).not.toContain("DROP");
180
+ expect(runCalls[0].params).toEqual(["env-1"]);
181
+ });
182
+
183
+ it("deleteByPackage issues a single DELETE and no DDL", async () => {
184
+ const { repo, runCalls } = fakeRepo();
185
+ await repo.deleteByPackage("env-1", "pkg-a");
186
+ expect(runCalls.length).toBe(1);
187
+ expect(runCalls[0].sql).toContain("DELETE FROM materializations");
188
+ expect(runCalls[0].sql).not.toContain("DROP");
189
+ expect(runCalls[0].params).toEqual(["env-1", "pkg-a"]);
190
+ });
191
+ });
@@ -263,6 +263,18 @@ export class MaterializationRepository {
263
263
  await this.db.run("DELETE FROM materializations WHERE id = ?", [id]);
264
264
  }
265
265
 
266
+ // Cascade deletes remove the publisher's records only; they intentionally
267
+ // issue no DDL. Dropping the physical tables is opt-in
268
+ // (deleteMaterialization({ dropTables })) and otherwise the caller's
269
+ // responsibility, so a materialized table outlives its record when an
270
+ // environment or package is deleted. Adding a DROP here would also risk
271
+ // firing against a connection already torn down by the delete path.
272
+ //
273
+ // Standalone caveat (#901): with no control plane owning physical GC,
274
+ // nothing drops those tables today, so they accumulate in the warehouse.
275
+ // That is an open follow-up, not a settled contract — its best-effort
276
+ // drop-before-teardown belongs ABOVE these methods, so it completes this
277
+ // design rather than moving DDL into the low-level record deletes.
266
278
  async deleteByEnvironmentId(environmentId: string): Promise<void> {
267
279
  await this.db.run(
268
280
  "DELETE FROM materializations WHERE environment_id = ?",
@@ -0,0 +1,256 @@
1
+ /// <reference types="bun-types" />
2
+
3
+ import { afterAll, afterEach, beforeAll, describe, expect, it } from "bun:test";
4
+ import path from "path";
5
+ import { fileURLToPath } from "url";
6
+ import { MaterializationScheduler } from "../../../src/service/materialization_scheduler";
7
+ import { MaterializationService } from "../../../src/service/materialization_service";
8
+ import { environmentStore } from "../../../src/server";
9
+ import { RestE2EEnv, startRestE2E } from "../../harness/rest_e2e";
10
+
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = path.dirname(__filename);
13
+
14
+ const FIXTURES = path.resolve(__dirname, "../../fixtures");
15
+ const SCHEDULED_FIXTURE = path.join(FIXTURES, "persist-schedule-test"); // cron "0 6 * * *", scope: version
16
+ const PERSIST_FIXTURE = path.join(FIXTURES, "persist-test"); // same persist source, no schedule
17
+
18
+ // Deterministic clock: tick(nowMs) is called explicitly so the daily
19
+ // "0 6 * * *" cron fires without waiting on a wall-clock minute.
20
+ const T0 = Date.parse("2026-01-01T00:00:00.000Z");
21
+ const MIN = 60_000;
22
+ const H = 60 * MIN;
23
+ const D = 24 * H;
24
+
25
+ const TERMINAL = ["MANIFEST_FILE_READY", "FAILED", "CANCELLED"];
26
+
27
+ // Integration coverage for the scheduler's state-machine transitions against the
28
+ // real store (#895): the unit spec covers the per-tick guards; these drive the
29
+ // transitions end to end through the REST-created packages the scheduler sweeps.
30
+ // Each test uses its own environment and tears it down in afterEach — the
31
+ // scheduler sweeps every loaded environment, so a leftover env would leak fires
32
+ // into another test (and steal the per-tick cap in the carryover case).
33
+ describe("MaterializationScheduler transitions (integration, real store)", () => {
34
+ let e2e: (RestE2EEnv & { stop(): Promise<void> }) | null = null;
35
+ let baseUrl: string;
36
+ let currentEnv: string | null = null;
37
+
38
+ beforeAll(async () => {
39
+ e2e = await startRestE2E();
40
+ baseUrl = e2e.baseUrl;
41
+ });
42
+
43
+ afterEach(async () => {
44
+ if (currentEnv) {
45
+ try {
46
+ await fetch(`${baseUrl}/api/v0/environments/${currentEnv}`, {
47
+ method: "DELETE",
48
+ });
49
+ } catch {
50
+ // best-effort teardown
51
+ }
52
+ currentEnv = null;
53
+ }
54
+ });
55
+
56
+ afterAll(async () => {
57
+ await e2e?.stop();
58
+ e2e = null;
59
+ });
60
+
61
+ // ── helpers ──────────────────────────────────────────────────────────
62
+
63
+ function newScheduler(maxFiresPerTick = 10): MaterializationScheduler {
64
+ return new MaterializationScheduler(
65
+ environmentStore,
66
+ new MaterializationService(environmentStore),
67
+ { tickIntervalMs: 60_000, maxFiresPerTick },
68
+ );
69
+ }
70
+
71
+ async function createEnv(
72
+ name: string,
73
+ packages: Array<{ name: string; location: string }>,
74
+ ): Promise<void> {
75
+ const res = await fetch(`${baseUrl}/api/v0/environments`, {
76
+ method: "POST",
77
+ headers: { "Content-Type": "application/json" },
78
+ body: JSON.stringify({ name, packages, connections: [] }),
79
+ });
80
+ if (!res.ok) {
81
+ throw new Error(
82
+ `create env ${name} failed (${res.status}): ${await res.text()}`,
83
+ );
84
+ }
85
+ currentEnv = name;
86
+ }
87
+
88
+ async function waitForPackage(env: string, pkg: string): Promise<void> {
89
+ const deadline = Date.now() + 30_000;
90
+ while (Date.now() < deadline) {
91
+ const res = await fetch(
92
+ `${baseUrl}/api/v0/environments/${env}/packages/${pkg}`,
93
+ );
94
+ if (res.ok) return;
95
+ await new Promise((r) => setTimeout(r, 500));
96
+ }
97
+ throw new Error(`package ${env}/${pkg} did not load in time`);
98
+ }
99
+
100
+ // Set scope: version + a cron schedule on a package (makes persist-test
101
+ // standalone-schedulable). editingPolicy is true, so the publish-gate rules
102
+ // run and must pass (version scope + valid cron, no freshness).
103
+ async function setSchedule(
104
+ env: string,
105
+ pkg: string,
106
+ schedule: string,
107
+ ): Promise<void> {
108
+ const res = await fetch(
109
+ `${baseUrl}/api/v0/environments/${env}/packages/${pkg}`,
110
+ {
111
+ method: "PATCH",
112
+ headers: { "Content-Type": "application/json" },
113
+ body: JSON.stringify({
114
+ name: pkg,
115
+ scope: "version",
116
+ materialization: { schedule },
117
+ }),
118
+ },
119
+ );
120
+ if (!res.ok) {
121
+ throw new Error(
122
+ `set schedule on ${pkg} failed (${res.status}): ${await res.text()}`,
123
+ );
124
+ }
125
+ }
126
+
127
+ type Row = Record<string, unknown>;
128
+
129
+ async function envMaterializations(env: string): Promise<Row[]> {
130
+ const res = await fetch(
131
+ `${baseUrl}/api/v0/environments/${env}/packages/materializations`,
132
+ );
133
+ expect(res.status).toBe(200);
134
+ return (await res.json()) as Row[];
135
+ }
136
+
137
+ function triggerOf(m: Row): string | undefined {
138
+ return (m.metadata as { trigger?: string } | null)?.trigger;
139
+ }
140
+
141
+ async function scheduledFireCount(env: string): Promise<number> {
142
+ return (await envMaterializations(env)).filter(
143
+ (m) => triggerOf(m) === "SCHEDULER",
144
+ ).length;
145
+ }
146
+
147
+ // Let every fired build settle so env teardown doesn't race an in-flight one.
148
+ async function waitAllTerminal(env: string): Promise<void> {
149
+ const deadline = Date.now() + 90_000;
150
+ while (Date.now() < deadline) {
151
+ const rows = await envMaterializations(env);
152
+ if (rows.every((m) => TERMINAL.includes(m.status as string))) return;
153
+ await new Promise((r) => setTimeout(r, 250));
154
+ }
155
+ throw new Error(`materializations in ${env} did not all settle`);
156
+ }
157
+
158
+ // ── transitions ─────────────────────────────────────────────────────
159
+
160
+ it(
161
+ "a cron edit between ticks re-arms from now (no stale fire from the old cadence)",
162
+ async () => {
163
+ const ENV = "sched-tx-cron-edit";
164
+ await createEnv(ENV, [
165
+ { name: "persist-schedule-test", location: SCHEDULED_FIXTURE },
166
+ ]);
167
+ await waitForPackage(ENV, "persist-schedule-test");
168
+ const sched = newScheduler();
169
+
170
+ // Arm on the original "0 6 * * *" cadence: nextFire = Jan-01 06:00.
171
+ await sched.tick(T0);
172
+
173
+ // Edit the cron to midnight before the old 06:00 occurrence fires.
174
+ await setSchedule(ENV, "persist-schedule-test", "0 0 * * *");
175
+
176
+ // Tick just past the OLD 06:00 occurrence. If the edit didn't re-arm,
177
+ // the stale nextFire would fire here; instead arm() re-anchors from now
178
+ // on the new cron (next = Jan-02 00:00), so nothing fires.
179
+ await sched.tick(T0 + 6 * H + MIN);
180
+ expect(await scheduledFireCount(ENV)).toBe(0);
181
+
182
+ // Past the NEW cron's next occurrence (Jan-02 00:00): it fires, proving
183
+ // the edit re-armed rather than silently dropping the schedule.
184
+ await sched.tick(T0 + D + MIN);
185
+ expect(await scheduledFireCount(ENV)).toBe(1);
186
+
187
+ await waitAllTerminal(ENV);
188
+ },
189
+ { timeout: 120_000 },
190
+ );
191
+
192
+ // The unload/reload prune + re-anchor transition is covered as a deterministic
193
+ // unit test (materialization_scheduler.spec.ts): it is pure in-memory arming
194
+ // state, and driving it here via a package delete + same-name re-add races the
195
+ // package-install staging rename on Windows (POSIX is fine), which is unrelated
196
+ // to the scheduler behavior under test.
197
+
198
+ it(
199
+ "a fired occurrence advances to the next occurrence (fires once per occurrence, not every tick)",
200
+ async () => {
201
+ const ENV = "sched-tx-cadence";
202
+ await createEnv(ENV, [
203
+ { name: "persist-schedule-test", location: SCHEDULED_FIXTURE },
204
+ ]);
205
+ await waitForPackage(ENV, "persist-schedule-test");
206
+ const sched = newScheduler();
207
+
208
+ await sched.tick(T0); // arm
209
+ await sched.tick(T0 + 6 * H + MIN); // due -> fire once
210
+ expect(await scheduledFireCount(ENV)).toBe(1);
211
+ await waitAllTerminal(ENV);
212
+
213
+ // Immediately after, still inside the same daily window: the scheduler
214
+ // advanced nextFire to the next occurrence, so it does NOT re-fire every
215
+ // tick. (The advance is outcome-independent — a FAILED fire advances the
216
+ // same way; that isolation is covered in the scheduler unit spec.)
217
+ await sched.tick(T0 + 6 * H + 2 * MIN);
218
+ expect(await scheduledFireCount(ENV)).toBe(1);
219
+
220
+ // The next day's 06:00 occurrence fires again.
221
+ await sched.tick(T0 + D + 6 * H + MIN);
222
+ expect(await scheduledFireCount(ENV)).toBe(2);
223
+ await waitAllTerminal(ENV);
224
+ },
225
+ { timeout: 180_000 },
226
+ );
227
+
228
+ it(
229
+ "maxFiresPerTick caps a tick and the capped package fires on the next tick",
230
+ async () => {
231
+ const ENV = "sched-tx-cap";
232
+ await createEnv(ENV, [
233
+ { name: "persist-schedule-test", location: SCHEDULED_FIXTURE },
234
+ { name: "persist-test", location: PERSIST_FIXTURE },
235
+ ]);
236
+ await waitForPackage(ENV, "persist-schedule-test");
237
+ await waitForPackage(ENV, "persist-test");
238
+ // Make the second package standalone-schedulable on the same cadence.
239
+ await setSchedule(ENV, "persist-test", "0 6 * * *");
240
+
241
+ const sched = newScheduler(1); // cap = 1 fire per tick
242
+
243
+ await sched.tick(T0); // arm both
244
+ // Both due at 06:00, but the cap lets only one fire this tick.
245
+ await sched.tick(T0 + 6 * H + MIN);
246
+ expect(await scheduledFireCount(ENV)).toBe(1);
247
+
248
+ // The capped package is still due and fires on the following tick.
249
+ await sched.tick(T0 + 6 * H + 2 * MIN);
250
+ expect(await scheduledFireCount(ENV)).toBe(2);
251
+
252
+ await waitAllTerminal(ENV);
253
+ },
254
+ { timeout: 180_000 },
255
+ );
256
+ });