@malloy-publisher/server 0.0.228 → 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 (94) hide show
  1. package/dist/app/api-doc.yaml +102 -10
  2. package/dist/app/assets/EnvironmentPage-wa_EPkwK.js +1 -0
  3. package/dist/app/assets/{HomePage-Bkwc9Woc.js → HomePage-jnCrupQp.js} +1 -1
  4. package/dist/app/assets/{LightMode-Bum_KBpN.js → LightMode-DYbwNULZ.js} +1 -1
  5. package/dist/app/assets/MainPage-CuJLrPNI.js +2 -0
  6. package/dist/app/assets/MaterializationsPage-D_67x2ee.js +1 -0
  7. package/dist/app/assets/ModelPage-D5JtAWqR.js +1 -0
  8. package/dist/app/assets/PackagePage-BRwtqUSG.js +1 -0
  9. package/dist/app/assets/{RouteError-DmJLpLXm.js → RouteError-CBNNrnSD.js} +1 -1
  10. package/dist/app/assets/ThemeEditorPage-CTCeBneA.js +1 -0
  11. package/dist/app/assets/WorkbookPage-SN6f1RBm.js +1 -0
  12. package/dist/app/assets/{core-CEDZMHV1.es-_yGzNgNH.js → core-Dp3q5Ieu.es-CD5FvM2s.js} +10 -10
  13. package/dist/app/assets/{index-CdmFub34.js → index-B3Nn8Vm2.js} +459 -446
  14. package/dist/app/assets/index-BLCx1EdC.js +18 -0
  15. package/dist/app/assets/index-C_tJstcx.js +529 -0
  16. package/dist/app/assets/{index-CE9xhdra.js → index-CfmBVB6M.js} +1 -1
  17. package/dist/app/assets/{index-OEjKNSYb.js → index-DU4r7GdU.js} +573 -413
  18. package/dist/app/index.html +1 -1
  19. package/dist/instrumentation.mjs +1 -1
  20. package/dist/package_load_worker.mjs +109 -8
  21. package/dist/server.mjs +7504 -80
  22. package/package.json +15 -13
  23. package/scripts/bake-duckdb-extensions.js +5 -2
  24. package/src/config.spec.ts +87 -1
  25. package/src/config.ts +142 -1
  26. package/src/controller/materialization.controller.spec.ts +9 -0
  27. package/src/controller/materialization.controller.ts +15 -0
  28. package/src/ducklake_version.spec.ts +163 -0
  29. package/src/ducklake_version.ts +153 -0
  30. package/src/errors.ts +12 -0
  31. package/src/malloy_pin_prereqs.spec.ts +25 -0
  32. package/src/materialization_metrics.ts +33 -0
  33. package/src/mcp/skills/build_skills_bundle.ts +29 -9
  34. package/src/mcp/skills/skills_bundle.json +1 -1
  35. package/src/mcp/skills/skills_bundle.spec.ts +31 -2
  36. package/src/query_param_utils.ts +11 -0
  37. package/src/server.ts +74 -9
  38. package/src/service/authorize.spec.ts +22 -0
  39. package/src/service/authorize.ts +267 -10
  40. package/src/service/authorize_integration.spec.ts +1068 -26
  41. package/src/service/connection.spec.ts +79 -7
  42. package/src/service/connection.ts +312 -25
  43. package/src/service/connection_config.spec.ts +21 -0
  44. package/src/service/connection_config.ts +15 -1
  45. package/src/service/cron_evaluator.spec.ts +79 -0
  46. package/src/service/cron_evaluator.ts +105 -0
  47. package/src/service/ducklake_lazy_attach.spec.ts +110 -0
  48. package/src/service/environment.ts +156 -17
  49. package/src/service/environment_store.spec.ts +569 -14
  50. package/src/service/environment_store.ts +237 -31
  51. package/src/service/environment_store_anchoring.spec.ts +107 -0
  52. package/src/service/extension_fetch_policy.spec.ts +256 -0
  53. package/src/service/manifest_loader.spec.ts +3 -1
  54. package/src/service/manifest_loader.ts +9 -5
  55. package/src/service/materialization_scheduler.spec.ts +289 -0
  56. package/src/service/materialization_scheduler.ts +304 -0
  57. package/src/service/materialization_service.spec.ts +286 -5
  58. package/src/service/materialization_service.ts +121 -8
  59. package/src/service/materialization_test_fixtures.ts +10 -1
  60. package/src/service/model.spec.ts +67 -0
  61. package/src/service/model.ts +656 -31
  62. package/src/service/package.spec.ts +38 -0
  63. package/src/service/package.ts +102 -2
  64. package/src/service/package_quote_bound_tables.spec.ts +171 -0
  65. package/src/service/persistence_policy.spec.ts +31 -0
  66. package/src/service/quoting.spec.ts +57 -1
  67. package/src/service/quoting.ts +33 -0
  68. package/src/storage/DatabaseInterface.ts +15 -0
  69. package/src/storage/duckdb/DuckDBRepository.ts +17 -0
  70. package/src/storage/duckdb/MaterializationRepository.spec.ts +191 -0
  71. package/src/storage/duckdb/MaterializationRepository.ts +68 -0
  72. package/tests/fixtures/persist-schedule-test/data/orders.csv +5 -0
  73. package/tests/fixtures/persist-schedule-test/persist_schedule_test.malloy +11 -0
  74. package/tests/fixtures/persist-schedule-test/publisher.json +7 -0
  75. package/tests/fixtures/persist-schedule-warn-test/data/orders.csv +5 -0
  76. package/tests/fixtures/persist-schedule-warn-test/persist_warn_test.malloy +11 -0
  77. package/tests/fixtures/persist-schedule-warn-test/publisher.json +6 -0
  78. package/tests/integration/materialization/environment_list.integration.spec.ts +133 -0
  79. package/tests/integration/materialization/materialization_lifecycle.integration.spec.ts +7 -2
  80. package/tests/integration/materialization/orchestrated_rebind.integration.spec.ts +150 -0
  81. package/tests/integration/materialization/schedule_edit.integration.spec.ts +126 -0
  82. package/tests/integration/materialization/scheduler.integration.spec.ts +200 -0
  83. package/tests/integration/materialization/scheduler_recovery.integration.spec.ts +172 -0
  84. package/tests/integration/materialization/scheduler_transitions.integration.spec.ts +256 -0
  85. package/tests/integration/materialization/scheduler_wiring.integration.spec.ts +143 -0
  86. package/dist/app/assets/EnvironmentPage-EW2lbGvb.js +0 -1
  87. package/dist/app/assets/MainPage-oiEy7TNM.js +0 -2
  88. package/dist/app/assets/MaterializationsPage-C_VJsTgU.js +0 -1
  89. package/dist/app/assets/ModelPage-z8REqAmk.js +0 -1
  90. package/dist/app/assets/PackagePage-C2Vtt1Ln.js +0 -1
  91. package/dist/app/assets/ThemeEditorPage-BywFjC7A.js +0 -1
  92. package/dist/app/assets/WorkbookPage-DCMizDMR.js +0 -1
  93. package/dist/app/assets/index-DDMrjIT3.js +0 -18
  94. package/dist/app/assets/index-EqslXZ44.js +0 -527
@@ -0,0 +1,256 @@
1
+ import { DuckDBConnection } from "@malloydata/db-duckdb";
2
+ import { afterEach, beforeEach, describe, expect, it } from "bun:test";
3
+ import fs from "fs/promises";
4
+ import path from "path";
5
+ import sinon from "sinon";
6
+ import { getExtensionFetchPolicy } from "../config";
7
+ import {
8
+ applyExtensionSessionSettings,
9
+ buildEnvironmentMalloyConfig,
10
+ } from "./connection";
11
+
12
+ describe("getExtensionFetchPolicy", () => {
13
+ const original = process.env.EXTENSION_FETCH_POLICY;
14
+ afterEach(() => {
15
+ if (original === undefined) delete process.env.EXTENSION_FETCH_POLICY;
16
+ else process.env.EXTENSION_FETCH_POLICY = original;
17
+ });
18
+
19
+ it("defaults to on-demand when unset or empty", () => {
20
+ delete process.env.EXTENSION_FETCH_POLICY;
21
+ expect(getExtensionFetchPolicy()).toBe("on-demand");
22
+ process.env.EXTENSION_FETCH_POLICY = " ";
23
+ expect(getExtensionFetchPolicy()).toBe("on-demand");
24
+ });
25
+
26
+ it("accepts the two policies case-insensitively", () => {
27
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
28
+ expect(getExtensionFetchPolicy()).toBe("local-only");
29
+ process.env.EXTENSION_FETCH_POLICY = "On-Demand";
30
+ expect(getExtensionFetchPolicy()).toBe("on-demand");
31
+ });
32
+
33
+ it("throws loudly on an unrecognised value", () => {
34
+ process.env.EXTENSION_FETCH_POLICY = "offline";
35
+ expect(() => getExtensionFetchPolicy()).toThrow(
36
+ /Invalid value for EXTENSION_FETCH_POLICY/,
37
+ );
38
+ });
39
+ });
40
+
41
+ describe("EXTENSION_FETCH_POLICY=local-only extension loading", () => {
42
+ const envPath = path.join(process.cwd(), "test-extension-policy");
43
+ const original = process.env.EXTENSION_FETCH_POLICY;
44
+
45
+ beforeEach(async () => {
46
+ await fs.mkdir(envPath, { recursive: true });
47
+ });
48
+ afterEach(async () => {
49
+ sinon.restore();
50
+ if (original === undefined) delete process.env.EXTENSION_FETCH_POLICY;
51
+ else process.env.EXTENSION_FETCH_POLICY = original;
52
+ await fs.rm(envPath, { recursive: true, force: true }).catch(() => {});
53
+ });
54
+
55
+ it("never runs INSTALL and raises a loud, actionable error when a required extension is missing", async () => {
56
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
57
+
58
+ // Session PRAGMAs and metadata probes succeed; the first extension LOAD
59
+ // fails, simulating an extension that was never baked into the image.
60
+ const runSQL = sinon
61
+ .stub(DuckDBConnection.prototype, "runSQL")
62
+ .resolves({ rows: [] } as never);
63
+ runSQL
64
+ .withArgs(sinon.match(/^LOAD ducklake/))
65
+ .rejects(new Error('Extension "ducklake" not found'));
66
+
67
+ const config = buildEnvironmentMalloyConfig(
68
+ [
69
+ {
70
+ name: "ducklake_localonly",
71
+ type: "ducklake",
72
+ ducklakeConnection: {
73
+ catalog: {
74
+ postgresConnection: {
75
+ host: "192.0.2.1",
76
+ port: 5432,
77
+ userName: "nobody",
78
+ password: "nobody",
79
+ databaseName: "catalog",
80
+ },
81
+ },
82
+ storage: {
83
+ bucketUrl: "s3://test-bucket",
84
+ s3Connection: {
85
+ accessKeyId: "test",
86
+ secretAccessKey: "test",
87
+ },
88
+ },
89
+ },
90
+ },
91
+ ] as never,
92
+ envPath,
93
+ );
94
+
95
+ await expect(
96
+ config.malloyConfig.connections.lookupConnection("ducklake_localonly"),
97
+ ).rejects.toThrow(/local-only.*ducklake|ducklake.*local-only/s);
98
+
99
+ // local-only must never issue an INSTALL — not even for a missing extension.
100
+ const ranInstall = runSQL
101
+ .getCalls()
102
+ .some((c) => /^\s*INSTALL\s/i.test(String(c.args[0])));
103
+ expect(ranInstall).toBe(false);
104
+
105
+ // And it did pin implicit auto-install off on the session (item 3).
106
+ const setAutoinstallOff = runSQL
107
+ .getCalls()
108
+ .some((c) =>
109
+ /autoinstall_known_extensions\s*=\s*false/i.test(String(c.args[0])),
110
+ );
111
+ expect(setAutoinstallOff).toBe(true);
112
+
113
+ await config.releaseConnections().catch(() => {});
114
+ });
115
+ });
116
+
117
+ describe("applyExtensionSessionSettings", () => {
118
+ const original = process.env.EXTENSION_FETCH_POLICY;
119
+ afterEach(() => {
120
+ sinon.restore();
121
+ if (original === undefined) delete process.env.EXTENSION_FETCH_POLICY;
122
+ else process.env.EXTENSION_FETCH_POLICY = original;
123
+ });
124
+
125
+ // Minimal stand-in — the helper only ever calls runSQL.
126
+ const mockConn = (runSQL: sinon.SinonStub) =>
127
+ ({ runSQL }) as unknown as DuckDBConnection;
128
+
129
+ it("pins autoinstall off (autoload on) under local-only", async () => {
130
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
131
+ const runSQL = sinon.stub().resolves({ rows: [] });
132
+ await applyExtensionSessionSettings(mockConn(runSQL));
133
+ const sql = runSQL.getCalls().map((c) => String(c.args[0]));
134
+ expect(
135
+ sql.some((s) => /autoinstall_known_extensions\s*=\s*false/i.test(s)),
136
+ ).toBe(true);
137
+ expect(
138
+ sql.some((s) => /autoload_known_extensions\s*=\s*true/i.test(s)),
139
+ ).toBe(true);
140
+ });
141
+
142
+ it("is a no-op for a generic session under on-demand", async () => {
143
+ delete process.env.EXTENSION_FETCH_POLICY;
144
+ const runSQL = sinon.stub().resolves({ rows: [] });
145
+ await applyExtensionSessionSettings(mockConn(runSQL));
146
+ expect(runSQL.callCount).toBe(0);
147
+ });
148
+
149
+ it("pins a tier session even under on-demand (alwaysDisableAutoinstall)", async () => {
150
+ delete process.env.EXTENSION_FETCH_POLICY;
151
+ const runSQL = sinon.stub().resolves({ rows: [] });
152
+ await applyExtensionSessionSettings(mockConn(runSQL), {
153
+ alwaysDisableAutoinstall: true,
154
+ });
155
+ expect(
156
+ runSQL
157
+ .getCalls()
158
+ .some((c) =>
159
+ /autoinstall_known_extensions\s*=\s*false/i.test(
160
+ String(c.args[0]),
161
+ ),
162
+ ),
163
+ ).toBe(true);
164
+ });
165
+
166
+ it("pins each connection only once (dedup)", async () => {
167
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
168
+ const runSQL = sinon.stub().resolves({ rows: [] });
169
+ const conn = mockConn(runSQL);
170
+ await applyExtensionSessionSettings(conn);
171
+ await applyExtensionSessionSettings(conn);
172
+ expect(runSQL.callCount).toBe(2); // two SETs from the first call only
173
+ });
174
+
175
+ it("fails closed under local-only when the pin cannot be applied", async () => {
176
+ process.env.EXTENSION_FETCH_POLICY = "local-only";
177
+ const runSQL = sinon.stub().rejects(new Error("pragma unsupported"));
178
+ await expect(
179
+ applyExtensionSessionSettings(mockConn(runSQL)),
180
+ ).rejects.toThrow(/EXTENSION_FETCH_POLICY=local-only/);
181
+ });
182
+
183
+ it("does NOT fail a tier attach under on-demand when the pin fails", async () => {
184
+ delete process.env.EXTENSION_FETCH_POLICY;
185
+ const runSQL = sinon.stub().rejects(new Error("pragma unsupported"));
186
+ // Resolves (warn-and-continue), does not throw.
187
+ await applyExtensionSessionSettings(mockConn(runSQL), {
188
+ alwaysDisableAutoinstall: true,
189
+ });
190
+ expect(runSQL.callCount).toBeGreaterThan(0);
191
+ });
192
+ });
193
+
194
+ describe("EXTENSION_FETCH_POLICY=on-demand (default) — no behaviour change", () => {
195
+ const envPath = path.join(process.cwd(), "test-extension-policy-ondemand");
196
+ const original = process.env.EXTENSION_FETCH_POLICY;
197
+
198
+ beforeEach(async () => {
199
+ await fs.mkdir(envPath, { recursive: true });
200
+ });
201
+ afterEach(async () => {
202
+ sinon.restore();
203
+ if (original === undefined) delete process.env.EXTENSION_FETCH_POLICY;
204
+ else process.env.EXTENSION_FETCH_POLICY = original;
205
+ await fs.rm(envPath, { recursive: true, force: true }).catch(() => {});
206
+ });
207
+
208
+ it("leaves autoinstall at DuckDB's default on a generic attach session", async () => {
209
+ // Default policy: an ordinary DuckDB connection with an attachment must
210
+ // behave exactly as before — Publisher installs the attachment's extension
211
+ // explicitly, but it must NOT disable DuckDB's implicit auto-install (that
212
+ // would regress a user whose query references an un-provisioned extension).
213
+ delete process.env.EXTENSION_FETCH_POLICY;
214
+
215
+ const runSQL = sinon
216
+ .stub(DuckDBConnection.prototype, "runSQL")
217
+ .resolves({ rows: [] } as never);
218
+
219
+ const config = buildEnvironmentMalloyConfig(
220
+ [
221
+ {
222
+ name: "gen_duck",
223
+ type: "duckdb",
224
+ duckdbConnection: {
225
+ attachedDatabases: [
226
+ {
227
+ name: "pg_attached",
228
+ type: "postgres",
229
+ postgresConnection: {
230
+ connectionString: "postgresql://localhost/test",
231
+ },
232
+ },
233
+ ],
234
+ },
235
+ },
236
+ ] as never,
237
+ envPath,
238
+ );
239
+
240
+ await config.malloyConfig.connections.lookupConnection("gen_duck");
241
+
242
+ const issued = runSQL.getCalls().map((c) => String(c.args[0]));
243
+ // The attachment path ran (postgres explicitly installed)...
244
+ expect(issued.some((sql) => /^\s*INSTALL\s+postgres/i.test(sql))).toBe(
245
+ true,
246
+ );
247
+ // ...but implicit auto-install was left untouched — no behaviour change.
248
+ expect(
249
+ issued.some((sql) =>
250
+ /autoinstall_known_extensions\s*=\s*false/i.test(sql),
251
+ ),
252
+ ).toBe(false);
253
+
254
+ await config.releaseConnections().catch(() => {});
255
+ });
256
+ });
@@ -42,7 +42,9 @@ describe("fetchManifestEntries", () => {
42
42
 
43
43
  expect(entries).toEqual({
44
44
  b1: { tableName: "schema.orders_mz" },
45
- b2: { tableName: "schema.daily_mz" },
45
+ // connectionName is carried through so the bind step can quote the
46
+ // table path for that connection's dialect (Package.quoteBoundTableNames).
47
+ b2: { tableName: "schema.daily_mz", connectionName: "bq" },
46
48
  });
47
49
  });
48
50
 
@@ -58,11 +58,14 @@ async function readManifestBytes(uri: string): Promise<string> {
58
58
 
59
59
  /**
60
60
  * Fetch and parse the control-plane-computed build manifest at `uri`, returning
61
- * the full wire binding map (`sourceEntityId -> { tableName, dataAsOf,
62
- * freshnessWindowSeconds, freshnessFallback }`). The wire manifest keys physical
63
- * tables under `physicalTableName`; the Malloy runtime consumes `tableName`, so
64
- * we translate that field here but otherwise carry the control-plane freshness
65
- * fields verbatim so the serve path can gate `age vs window` per query. Entries
61
+ * the full wire binding map (`sourceEntityId -> { tableName, connectionName,
62
+ * dataAsOf, freshnessWindowSeconds, freshnessFallback }`). The wire manifest
63
+ * keys physical tables under `physicalTableName`; the Malloy runtime consumes
64
+ * `tableName`, so we translate that field here but otherwise carry the
65
+ * control-plane fields verbatim — the freshness fields so the serve path can
66
+ * gate `age vs window` per query, and `connectionName` so the bind step can
67
+ * quote the path for that connection's dialect (see
68
+ * Package.quoteBoundTableNames). Entries
66
69
  * missing a physical table are skipped. This is a pure fetch + parse: it does
67
70
  * **not** filter on freshness (that happens per query on the serve path). Throws
68
71
  * if the URI can't be read or parsed.
@@ -95,6 +98,7 @@ export async function fetchManifestEntries(
95
98
  }
96
99
  entries[sourceEntityId] = {
97
100
  tableName: physicalTableName,
101
+ connectionName: entry.connectionName,
98
102
  dataAsOf: entry.dataAsOf,
99
103
  freshnessWindowSeconds: entry.freshnessWindowSeconds,
100
104
  freshnessFallback: entry.freshnessFallback,
@@ -0,0 +1,289 @@
1
+ import { describe, expect, it } from "bun:test";
2
+ import { MaterializationConflictError } from "../errors";
3
+ import type { CronEvaluator } from "./cron_evaluator";
4
+ import type { EnvironmentStore } from "./environment_store";
5
+ import type { MaterializationService } from "./materialization_service";
6
+ import { MaterializationScheduler } from "./materialization_scheduler";
7
+
8
+ // ── Fakes ────────────────────────────────────────────────────────────────
9
+
10
+ interface FakePkgOpts {
11
+ schedule?: string | null;
12
+ manifestLocation?: string | null;
13
+ policyWarnings?: string[];
14
+ }
15
+
16
+ function fakePackage(name: string, opts: FakePkgOpts = {}) {
17
+ const {
18
+ schedule = null,
19
+ manifestLocation = null,
20
+ policyWarnings = [],
21
+ } = opts;
22
+ return {
23
+ getPackageName: () => name,
24
+ getPackageMetadata: () => ({
25
+ materialization: schedule ? { schedule } : null,
26
+ manifestLocation,
27
+ }),
28
+ persistencePolicyWarnings: () => policyWarnings,
29
+ };
30
+ }
31
+
32
+ function fakeEnv(name: string, pkgs: ReturnType<typeof fakePackage>[]) {
33
+ return {
34
+ getEnvironmentName: () => name,
35
+ getLoadedPackages: () => pkgs,
36
+ };
37
+ }
38
+
39
+ function fakeStore(envs: ReturnType<typeof fakeEnv>[]): EnvironmentStore {
40
+ return {
41
+ getLoadedEnvironments: () => envs,
42
+ } as unknown as EnvironmentStore;
43
+ }
44
+
45
+ interface FireCall {
46
+ env: string;
47
+ pkg: string;
48
+ opts: { forceRefresh?: boolean; trigger?: string };
49
+ }
50
+
51
+ function fakeService(
52
+ opts: {
53
+ throwConflict?: boolean;
54
+ throwError?: boolean;
55
+ // Newest recorded SCHEDULER fire, used by the restart-recovery anchor.
56
+ lastFireAt?: Date | null;
57
+ } = {},
58
+ ) {
59
+ const calls: FireCall[] = [];
60
+ const service = {
61
+ calls,
62
+ createMaterialization: (
63
+ env: string,
64
+ pkg: string,
65
+ o: { forceRefresh?: boolean; trigger?: string },
66
+ ) => {
67
+ calls.push({ env, pkg, opts: o });
68
+ if (opts.throwConflict) {
69
+ return Promise.reject(new MaterializationConflictError("busy"));
70
+ }
71
+ if (opts.throwError) {
72
+ return Promise.reject(new Error("boom"));
73
+ }
74
+ return Promise.resolve({});
75
+ },
76
+ getLatestScheduledFireAt: () => Promise.resolve(opts.lastFireAt ?? null),
77
+ };
78
+ return service as unknown as MaterializationService & { calls: FireCall[] };
79
+ }
80
+
81
+ // A deterministic cron: nextAfter is always `from + 60s`; isValid configurable.
82
+ function fakeCron(
83
+ isValid: (expr: string) => boolean = () => true,
84
+ ): CronEvaluator {
85
+ return {
86
+ isValid,
87
+ nextAfter: (_expr: string, from: Date) =>
88
+ new Date(from.getTime() + 60_000),
89
+ } as unknown as CronEvaluator;
90
+ }
91
+
92
+ const CONFIG = { tickIntervalMs: 60_000, maxFiresPerTick: 10 };
93
+
94
+ function makeScheduler(
95
+ pkgs: ReturnType<typeof fakePackage>[],
96
+ service: ReturnType<typeof fakeService>,
97
+ cron: CronEvaluator = fakeCron(),
98
+ config = CONFIG,
99
+ ) {
100
+ const store = fakeStore([fakeEnv("env1", pkgs)]);
101
+ return new MaterializationScheduler(store, service, config, cron);
102
+ }
103
+
104
+ // ── Tests ────────────────────────────────────────────────────────────────
105
+
106
+ describe("MaterializationScheduler", () => {
107
+ const t0 = 1_000_000_000_000; // fixed epoch ms
108
+ const dueLater = t0 + 60_001; // just past the armed nextFire (t0 + 60s)
109
+
110
+ it("does not fire on the arming tick (nextFire is strictly future)", async () => {
111
+ const service = fakeService();
112
+ const sched = makeScheduler(
113
+ [fakePackage("p", { schedule: "* * * * *" })],
114
+ service,
115
+ );
116
+ await sched.tick(t0);
117
+ expect(service.calls.length).toBe(0);
118
+ });
119
+
120
+ it("recovers a missed occurrence on first arm, firing once then jumping forward", async () => {
121
+ // A prior SCHEDULER fire well in the past: anchoring nextFire to
122
+ // nextAfter(lastFire) lands before t0, so the occurrence missed during
123
+ // "downtime" is due on the very first tick (a restart recovering).
124
+ const service = fakeService({ lastFireAt: new Date(t0 - 10 * 60_000) });
125
+ const sched = makeScheduler(
126
+ [fakePackage("p", { schedule: "* * * * *" })],
127
+ service,
128
+ );
129
+ await sched.tick(t0);
130
+ expect(service.calls.length).toBe(1); // one catch-up fire
131
+ // Jumped forward to nextAfter(now); not due again on the next tick.
132
+ await sched.tick(t0 + 1);
133
+ expect(service.calls.length).toBe(1);
134
+ });
135
+
136
+ it("does not catch up a never-fired schedule on first arm", async () => {
137
+ // No prior SCHEDULER fire on record -> anchor is now -> strictly future,
138
+ // so a freshly-scheduled (never-fired) package does not fire on arm.
139
+ const service = fakeService({ lastFireAt: null });
140
+ const sched = makeScheduler(
141
+ [fakePackage("p", { schedule: "* * * * *" })],
142
+ service,
143
+ );
144
+ await sched.tick(t0);
145
+ expect(service.calls.length).toBe(0);
146
+ });
147
+
148
+ it("fires a due, valid, standalone package as SCHEDULER + forceRefresh", async () => {
149
+ const service = fakeService();
150
+ const sched = makeScheduler(
151
+ [fakePackage("p", { schedule: "* * * * *" })],
152
+ service,
153
+ );
154
+ await sched.tick(t0); // arm
155
+ await sched.tick(dueLater); // due -> fire
156
+ expect(service.calls).toEqual([
157
+ {
158
+ env: "env1",
159
+ pkg: "p",
160
+ opts: { forceRefresh: true, trigger: "SCHEDULER" },
161
+ },
162
+ ]);
163
+ });
164
+
165
+ it("skips a package with no schedule", async () => {
166
+ const service = fakeService();
167
+ const sched = makeScheduler([fakePackage("p", {})], service);
168
+ await sched.tick(t0);
169
+ await sched.tick(dueLater);
170
+ expect(service.calls.length).toBe(0);
171
+ });
172
+
173
+ it("skips an orchestrated package (manifestLocation set) — Guard 2", async () => {
174
+ const service = fakeService();
175
+ const sched = makeScheduler(
176
+ [
177
+ fakePackage("p", {
178
+ schedule: "* * * * *",
179
+ manifestLocation: "gs://cp/manifest.json",
180
+ }),
181
+ ],
182
+ service,
183
+ );
184
+ await sched.tick(t0);
185
+ await sched.tick(dueLater);
186
+ expect(service.calls.length).toBe(0);
187
+ });
188
+
189
+ it("skips a package whose persistence policy is invalid", async () => {
190
+ const service = fakeService();
191
+ const sched = makeScheduler(
192
+ [
193
+ fakePackage("p", {
194
+ schedule: "* * * * *",
195
+ policyWarnings: ["schedule requires scope: version"],
196
+ }),
197
+ ],
198
+ service,
199
+ );
200
+ await sched.tick(t0);
201
+ await sched.tick(dueLater);
202
+ expect(service.calls.length).toBe(0);
203
+ });
204
+
205
+ it("skips an invalid cron", async () => {
206
+ const service = fakeService();
207
+ const sched = makeScheduler(
208
+ [fakePackage("p", { schedule: "not a cron" })],
209
+ service,
210
+ fakeCron(() => false),
211
+ );
212
+ await sched.tick(t0);
213
+ await sched.tick(dueLater);
214
+ expect(service.calls.length).toBe(0);
215
+ });
216
+
217
+ it("coalesces when a materialization is already active (no throw)", async () => {
218
+ const service = fakeService({ throwConflict: true });
219
+ const sched = makeScheduler(
220
+ [fakePackage("p", { schedule: "* * * * *" })],
221
+ service,
222
+ );
223
+ await sched.tick(t0);
224
+ await sched.tick(dueLater); // due -> fire attempt -> conflict, swallowed
225
+ expect(service.calls.length).toBe(1); // attempted once
226
+ // Advanced past this occurrence: not due again until the next window.
227
+ await sched.tick(dueLater + 1);
228
+ expect(service.calls.length).toBe(1);
229
+ });
230
+
231
+ it("isolates an unexpected fire error (sweep keeps going)", async () => {
232
+ const service = fakeService({ throwError: true });
233
+ const sched = makeScheduler(
234
+ [fakePackage("p", { schedule: "* * * * *" })],
235
+ service,
236
+ );
237
+ await sched.tick(t0);
238
+ await expect(sched.tick(dueLater)).resolves.toBeUndefined();
239
+ expect(service.calls.length).toBe(1);
240
+ });
241
+
242
+ it("caps fires per tick (stampede guard)", async () => {
243
+ const service = fakeService();
244
+ const pkgs = [
245
+ fakePackage("a", { schedule: "* * * * *" }),
246
+ fakePackage("b", { schedule: "* * * * *" }),
247
+ fakePackage("c", { schedule: "* * * * *" }),
248
+ ];
249
+ const sched = makeScheduler(pkgs, service, fakeCron(), {
250
+ tickIntervalMs: 60_000,
251
+ maxFiresPerTick: 2,
252
+ });
253
+ await sched.tick(t0); // arm all
254
+ await sched.tick(dueLater); // all due, but cap = 2
255
+ expect(service.calls.length).toBe(2);
256
+ // The capped one is still due and fires on the next tick.
257
+ await sched.tick(dueLater + 1);
258
+ expect(service.calls.length).toBe(3);
259
+ });
260
+
261
+ it("prunes arming state when a package unloads, then re-anchors on reload without a stale fire", async () => {
262
+ // A never-fired schedule (fakeService default lastFireAt = null), so a
263
+ // fresh arm anchors from `now` and does not catch up.
264
+ const service = fakeService();
265
+ const p = fakePackage("p", { schedule: "* * * * *" });
266
+ // makeScheduler closes over this array via getLoadedPackages, so mutating
267
+ // it simulates the package leaving and re-entering the loaded set.
268
+ const loaded = [p];
269
+ const sched = makeScheduler(loaded, service);
270
+
271
+ await sched.tick(t0); // arm: nextFire = t0 + 60s
272
+
273
+ // Unload: the package leaves the loaded set, so the sweep prunes its state
274
+ // (tick's not-seen cleanup) instead of leaving a stale nextFire behind.
275
+ loaded.length = 0;
276
+ await sched.tick(dueLater); // past the old nextFire, but the package is gone
277
+ expect(service.calls.length).toBe(0);
278
+
279
+ // Reload: with the state pruned, arm is fresh — anchored from `now`, so the
280
+ // pre-unload nextFire can't resurface as a spurious catch-up.
281
+ loaded.push(p);
282
+ await sched.tick(dueLater + 1); // now < fresh nextFire -> no fire
283
+ expect(service.calls.length).toBe(0);
284
+
285
+ // It is genuinely re-armed (not inert): the next occurrence still fires.
286
+ await sched.tick(dueLater + 1 + 60_001);
287
+ expect(service.calls.length).toBe(1);
288
+ });
289
+ });