@malloy-publisher/server 0.18.3 → 0.18.4
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/dist/app/api-doc.yaml +39 -8
- package/dist/app/assets/{EnvironmentPage-CsFUI8IX.js → EnvironmentPage-BxNqq3cN.js} +1 -1
- package/dist/app/assets/{HomePage-B_FVtnN-.js → HomePage-B4iN5rso.js} +1 -1
- package/dist/app/assets/{MainPage-wFF9nPEr.js → MainPage-DGiMH0eU.js} +1 -1
- package/dist/app/assets/{ModelPage-CxenqDcz.js → ModelPage-BJmyMnQo.js} +2 -2
- package/dist/app/assets/{PackagePage-dcF6vrvw.js → PackagePage-D2Pay_Xy.js} +1 -1
- package/dist/app/assets/{PackageSplatRoute-CASBZk0k.js → PackageSplatRoute-CQ7PxhkD.js} +2 -2
- package/dist/app/assets/{RenderedResult--fYcsY1h.es-DzOt5Lwv.js → RenderedResult-BEJ_GMaW.es-DS2oXAjc.js} +1 -1
- package/dist/app/assets/{RouteError-CUIolYwb.js → RouteError-BysHaT0t.js} +1 -1
- package/dist/app/assets/{ThemeEditorPage-DgU2YYq6.js → ThemeEditorPage-BFyTBbqA.js} +1 -1
- package/dist/app/assets/{ToggleButtonGroup-Dmr-hVlD.js → ToggleButtonGroup-eURRljZv.js} +1 -1
- package/dist/app/assets/{documentRoutes-Drv-WDwO.js → documentRoutes-DgTzGqfC.js} +1 -1
- package/dist/app/assets/{editPageMounted-C5yJiIVi.js → editPageMounted-CWBeAIbE.js} +2 -2
- package/dist/app/assets/{index-BSyL0zds.js → index-CCLHq9po.js} +15 -15
- package/dist/app/assets/{index-Dtw4eTxH.js → index-D4DhR2vg.js} +1 -1
- package/dist/app/assets/{index-BIoSdsU9.js → index-N8X9kVzc.js} +1 -1
- package/dist/app/assets/{index-DxF3kMLJ.js → index-We9Zzxmt.js} +1 -1
- package/dist/app/assets/{index.es-CX9m4CBD.js → index.es-D_O2KdNW.js} +1 -1
- package/dist/app/assets/usePackageLinkNavigate-CllycPZP.js +1 -0
- package/dist/app/assets/{usePackageRoute-wJGaZEiY.js → usePackageRoute-DEUbQLf3.js} +1 -1
- package/dist/app/index.html +1 -1
- package/dist/instrumentation.mjs +1 -1
- package/dist/package_load_worker.mjs +413 -272
- package/dist/server.mjs +946 -323
- package/package.json +2 -2
- package/dist/app/assets/usePackageLinkNavigate-qNjcXPcY.js +0 -1
package/dist/server.mjs
CHANGED
|
@@ -132137,12 +132137,83 @@ function normalizeRecord(row) {
|
|
|
132137
132137
|
}
|
|
132138
132138
|
return out;
|
|
132139
132139
|
}
|
|
132140
|
-
|
|
132140
|
+
function executorInternals(executor) {
|
|
132141
|
+
const e = executor;
|
|
132142
|
+
const pool = e?.pool_;
|
|
132143
|
+
return typeof pool?.acquire === "function" && typeof pool.release === "function" && typeof pool.destroy === "function" && typeof e.ensureSessionInitialized === "function" && typeof e._execute === "function" ? e : undefined;
|
|
132144
|
+
}
|
|
132145
|
+
function pinnedExecutor(base, conn) {
|
|
132146
|
+
const batch = async (sql, options, timeoutMs, binds) => {
|
|
132147
|
+
await base.ensureSessionInitialized(conn, options, timeoutMs);
|
|
132148
|
+
return base._execute(sql, conn, options, timeoutMs, binds);
|
|
132149
|
+
};
|
|
132150
|
+
const pinned = {
|
|
132151
|
+
batch,
|
|
132152
|
+
tryBatch: async (sql, options, timeoutMs, binds) => {
|
|
132153
|
+
try {
|
|
132154
|
+
return await batch(sql, options, timeoutMs, binds);
|
|
132155
|
+
} catch {
|
|
132156
|
+
return;
|
|
132157
|
+
}
|
|
132158
|
+
},
|
|
132159
|
+
stream: async (sql, options) => {
|
|
132160
|
+
const rows = await batch(sql, options) ?? [];
|
|
132161
|
+
const limit = options?.rowLimit ?? rows.length;
|
|
132162
|
+
return async function* () {
|
|
132163
|
+
yield* rows.slice(0, limit);
|
|
132164
|
+
}();
|
|
132165
|
+
},
|
|
132166
|
+
_execute: base._execute.bind(base),
|
|
132167
|
+
done: async () => {}
|
|
132168
|
+
};
|
|
132169
|
+
return new Proxy(pinned, {
|
|
132170
|
+
get(target, prop, receiver) {
|
|
132171
|
+
if (typeof prop === "string" && !(prop in target)) {
|
|
132172
|
+
const value = base[prop];
|
|
132173
|
+
if (typeof value === "function") {
|
|
132174
|
+
throw new UnpinnedExecutorMethodError(prop);
|
|
132175
|
+
}
|
|
132176
|
+
return value;
|
|
132177
|
+
}
|
|
132178
|
+
return Reflect.get(target, prop, receiver);
|
|
132179
|
+
}
|
|
132180
|
+
});
|
|
132181
|
+
}
|
|
132182
|
+
var MAX_SAFE, UnpinnedExecutorMethodError, PublisherSnowflakeConnection;
|
|
132141
132183
|
var init_snowflake_connection = __esm(() => {
|
|
132142
132184
|
init_connection_config();
|
|
132143
132185
|
init_snowflake();
|
|
132144
132186
|
MAX_SAFE = BigInt(Number.MAX_SAFE_INTEGER);
|
|
132187
|
+
UnpinnedExecutorMethodError = class UnpinnedExecutorMethodError extends Error {
|
|
132188
|
+
method;
|
|
132189
|
+
constructor(method) {
|
|
132190
|
+
super(`the Snowflake schema read called executor.${method}, which Publisher ` + `does not pin to one session`);
|
|
132191
|
+
this.method = method;
|
|
132192
|
+
}
|
|
132193
|
+
};
|
|
132145
132194
|
PublisherSnowflakeConnection = class PublisherSnowflakeConnection extends SnowflakeConnection {
|
|
132195
|
+
async fetchSelectSchema(sqlRef) {
|
|
132196
|
+
const base = executorInternals(this.executor);
|
|
132197
|
+
if (!base)
|
|
132198
|
+
return super.fetchSelectSchema(sqlRef);
|
|
132199
|
+
const conn = await base.pool_.acquire();
|
|
132200
|
+
const pinned = Object.create(this, {
|
|
132201
|
+
executor: { value: pinnedExecutor(base, conn) }
|
|
132202
|
+
});
|
|
132203
|
+
let result;
|
|
132204
|
+
try {
|
|
132205
|
+
result = await super.fetchSelectSchema.call(pinned, sqlRef);
|
|
132206
|
+
} catch (error) {
|
|
132207
|
+
if (error instanceof UnpinnedExecutorMethodError) {
|
|
132208
|
+
await base.pool_.release(conn).catch(() => {});
|
|
132209
|
+
return super.fetchSelectSchema(sqlRef);
|
|
132210
|
+
}
|
|
132211
|
+
await base.pool_.destroy(conn).catch(() => {});
|
|
132212
|
+
throw error;
|
|
132213
|
+
}
|
|
132214
|
+
await base.pool_.release(conn).catch(() => {});
|
|
132215
|
+
return result;
|
|
132216
|
+
}
|
|
132146
132217
|
async runSQL(sql, options) {
|
|
132147
132218
|
const result = await super.runSQL(sql, options);
|
|
132148
132219
|
return { ...result, rows: result.rows.map(normalizeRecord) };
|
|
@@ -132155,6 +132226,26 @@ var init_snowflake_connection = __esm(() => {
|
|
|
132155
132226
|
};
|
|
132156
132227
|
});
|
|
132157
132228
|
|
|
132229
|
+
// src/service/bigquery_request_timeout.ts
|
|
132230
|
+
function extendBigQueryRequestTimeout(connection) {
|
|
132231
|
+
const client = connection.bigQuery;
|
|
132232
|
+
if (!client || typeof client.request !== "function") {
|
|
132233
|
+
if (!warnedUnreachable) {
|
|
132234
|
+
warnedUnreachable = true;
|
|
132235
|
+
logger.warn("Could not set the BigQuery client's request timeout; a long query's results poll may time out at the SDK's default", { connectionName: connection.name });
|
|
132236
|
+
}
|
|
132237
|
+
return false;
|
|
132238
|
+
}
|
|
132239
|
+
if (typeof client.timeout !== "number" || client.timeout < BIGQUERY_REQUEST_TIMEOUT_MS) {
|
|
132240
|
+
client.timeout = BIGQUERY_REQUEST_TIMEOUT_MS;
|
|
132241
|
+
}
|
|
132242
|
+
return true;
|
|
132243
|
+
}
|
|
132244
|
+
var BIGQUERY_REQUEST_TIMEOUT_MS = 180000, warnedUnreachable = false;
|
|
132245
|
+
var init_bigquery_request_timeout = __esm(() => {
|
|
132246
|
+
init_logger();
|
|
132247
|
+
});
|
|
132248
|
+
|
|
132158
132249
|
// src/service/bigquery_truncation.ts
|
|
132159
132250
|
function assertCompleteBigQueryPage(data, rowLimit, rowIndex = 0) {
|
|
132160
132251
|
if (rowLimit === undefined || rowLimit <= 0)
|
|
@@ -132953,6 +133044,7 @@ function buildEnvironmentMalloyConfig(connections = [], environmentPath = "", is
|
|
|
132953
133044
|
ownDuckDBConnection(malloyConfig, connection);
|
|
132954
133045
|
if (metadata?.apiConnection.type === "bigquery") {
|
|
132955
133046
|
guardBigQueryTruncation(connection);
|
|
133047
|
+
extendBigQueryRequestTimeout(connection);
|
|
132956
133048
|
}
|
|
132957
133049
|
if (metadata) {
|
|
132958
133050
|
await attachOnce(connection, metadata);
|
|
@@ -133216,6 +133308,7 @@ var init_connection = __esm(() => {
|
|
|
133216
133308
|
init_duckdb_session_setup();
|
|
133217
133309
|
init_postgres_conninfo();
|
|
133218
133310
|
init_snowflake_connection();
|
|
133311
|
+
init_bigquery_request_timeout();
|
|
133219
133312
|
init_bigquery_truncation();
|
|
133220
133313
|
init_gcp_impersonation();
|
|
133221
133314
|
init_google_credentials();
|
|
@@ -140866,11 +140959,22 @@ function errorCodeOf(err) {
|
|
|
140866
140959
|
}
|
|
140867
140960
|
return "Error";
|
|
140868
140961
|
}
|
|
140869
|
-
|
|
140962
|
+
function runtimeErrorTextOf(err) {
|
|
140963
|
+
for (const e of causeChain(err)) {
|
|
140964
|
+
const { code } = e;
|
|
140965
|
+
if (typeof code === "number" && RUNTIME_ERROR_NAMES.has(e.name) && typeof e.message === "string" && RUNTIME_TEXT.test(e.message)) {
|
|
140966
|
+
return e.message;
|
|
140967
|
+
}
|
|
140968
|
+
}
|
|
140969
|
+
return;
|
|
140970
|
+
}
|
|
140971
|
+
var CODE_PATTERN, RUNTIME_ERROR_NAMES, RUNTIME_TEXT;
|
|
140870
140972
|
var init_error_code = __esm(() => {
|
|
140871
140973
|
init_driver_errors();
|
|
140872
140974
|
init_errors2();
|
|
140873
140975
|
CODE_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;
|
|
140976
|
+
RUNTIME_ERROR_NAMES = new Set(["TimeoutError", "AbortError"]);
|
|
140977
|
+
RUNTIME_TEXT = /^[A-Za-z][A-Za-z ,.'-]{0,119}$/;
|
|
140874
140978
|
});
|
|
140875
140979
|
|
|
140876
140980
|
// src/service/materialization/plan/refusal_key.ts
|
|
@@ -141288,6 +141392,21 @@ function kindOf2(def, base) {
|
|
|
141288
141392
|
return "rename";
|
|
141289
141393
|
return "query";
|
|
141290
141394
|
}
|
|
141395
|
+
function detachedNode(def) {
|
|
141396
|
+
const d = def;
|
|
141397
|
+
if (!d || typeof d !== "object" || typeof d.sourceID !== "string") {
|
|
141398
|
+
return;
|
|
141399
|
+
}
|
|
141400
|
+
const base = baseEdgeOf(d, undefined);
|
|
141401
|
+
return {
|
|
141402
|
+
sourceID: d.sourceID,
|
|
141403
|
+
name: undefined,
|
|
141404
|
+
kind: kindOf2(d, base),
|
|
141405
|
+
base,
|
|
141406
|
+
members: compositeMemberIds(d),
|
|
141407
|
+
def: d
|
|
141408
|
+
};
|
|
141409
|
+
}
|
|
141291
141410
|
function sourceChain(struct, modelDef) {
|
|
141292
141411
|
return SourceMap.of(modelDef).chainOf(struct);
|
|
141293
141412
|
}
|
|
@@ -158150,7 +158269,7 @@ var init_generated_files = __esm(() => {
|
|
|
158150
158269
|
});
|
|
158151
158270
|
|
|
158152
158271
|
// package.json
|
|
158153
|
-
var version = "0.18.
|
|
158272
|
+
var version = "0.18.4";
|
|
158154
158273
|
var init_package = () => {};
|
|
158155
158274
|
|
|
158156
158275
|
// src/version.ts
|
|
@@ -162685,13 +162804,14 @@ async function collectGeneratedTables(parts, args) {
|
|
|
162685
162804
|
parts.modelGateLines.nameProblems.push(...persistNameProblems(text, modelPath));
|
|
162686
162805
|
}
|
|
162687
162806
|
}
|
|
162807
|
+
const materializeOn = getMaterializeEnabled();
|
|
162688
162808
|
collectPersistQueryFindings(parts, {
|
|
162689
162809
|
modelPath,
|
|
162690
162810
|
packagePath,
|
|
162691
162811
|
malloyModel,
|
|
162692
|
-
notBuilt: !
|
|
162812
|
+
notBuilt: !materializeOn
|
|
162693
162813
|
});
|
|
162694
|
-
if (!
|
|
162814
|
+
if (!materializeOn) {
|
|
162695
162815
|
collectPersistViewFindingsSwitchedOff(parts, {
|
|
162696
162816
|
modelPath,
|
|
162697
162817
|
packagePath,
|
|
@@ -162699,7 +162819,7 @@ async function collectGeneratedTables(parts, args) {
|
|
|
162699
162819
|
});
|
|
162700
162820
|
}
|
|
162701
162821
|
let materialized;
|
|
162702
|
-
if (
|
|
162822
|
+
if (materializeOn) {
|
|
162703
162823
|
materialized = await collectGeneratedMaterialize(parts, {
|
|
162704
162824
|
modelPath,
|
|
162705
162825
|
packagePath,
|
|
@@ -162816,7 +162936,7 @@ function reportPersistLineFindings(parts, targets, planned, args) {
|
|
|
162816
162936
|
route: "@",
|
|
162817
162937
|
tier: "malformed",
|
|
162818
162938
|
code: "persist-not-materializable",
|
|
162819
|
-
message: `#@ persist source "${name}" is not a source Malloy can ` + `materialize: only a query or aggregate source builds, and a ` + `filtered pass-through, a table with only added fields, or an ` + `unbound parameterized source does not.
|
|
162939
|
+
message: `#@ persist source "${name}" is not a source Malloy can ` + `materialize: only a query or aggregate source builds, and a ` + `filtered pass-through, a table with only added fields, or an ` + `unbound parameterized source does not. ` + (getMaterializeEnabled() ? `Mark a table-shaped source \`#(materialize)\` instead, ` + `which stores a table-shaped source as well as a ` + `query-shaped one; or persist a query source over it, ` : `Persist a query source over it, `) + `invoke a parameterized source with a bound argument, or ` + `remove the annotation`,
|
|
162820
162940
|
subject: name,
|
|
162821
162941
|
model: modelPath
|
|
162822
162942
|
});
|
|
@@ -168793,6 +168913,9 @@ var init_served_copy_containment = __esm(() => {
|
|
|
168793
168913
|
});
|
|
168794
168914
|
|
|
168795
168915
|
// src/service/materialization/text/kept_ancestors.ts
|
|
168916
|
+
function nodeIn(map, sourceID, elsewhere) {
|
|
168917
|
+
return map.node(sourceID) ?? detachedNode(elsewhere?.(sourceID));
|
|
168918
|
+
}
|
|
168796
168919
|
function plainRenamesOf(map, sourceID, url) {
|
|
168797
168920
|
const out = [];
|
|
168798
168921
|
const reached = new Set([sourceID]);
|
|
@@ -168842,15 +168965,15 @@ function locatedIn(def, url) {
|
|
|
168842
168965
|
const location = def?.location;
|
|
168843
168966
|
return location?.url === url && typeof location.range?.start?.line === "number" && typeof location.range?.end?.line === "number" ? location.range : undefined;
|
|
168844
168967
|
}
|
|
168845
|
-
function keptAncestorChain(map, sourceID, url) {
|
|
168968
|
+
function keptAncestorChain(map, sourceID, url, elsewhere) {
|
|
168846
168969
|
const out = [];
|
|
168847
|
-
let node = map
|
|
168970
|
+
let node = nodeIn(map, sourceID, elsewhere);
|
|
168848
168971
|
let childURL = url;
|
|
168849
168972
|
for (let hops = 0;node && hops < MAX_HOPS; hops++) {
|
|
168850
168973
|
const base = node.base;
|
|
168851
168974
|
if (!base || base.hop === "query" || base.sourceID === undefined)
|
|
168852
168975
|
break;
|
|
168853
|
-
const parent = map
|
|
168976
|
+
const parent = nodeIn(map, base.sourceID, elsewhere);
|
|
168854
168977
|
const parentURL = declaringURLOf(parent?.def);
|
|
168855
168978
|
const range = parentURL ? locatedIn(parent?.def, parentURL) : undefined;
|
|
168856
168979
|
if (!parent || !parentURL || !range)
|
|
@@ -168867,17 +168990,29 @@ function keptAncestorChain(map, sourceID, url) {
|
|
|
168867
168990
|
}
|
|
168868
168991
|
return out;
|
|
168869
168992
|
}
|
|
168870
|
-
function keptAncestorChainOrDeclared(map, sourceID, url, fileText) {
|
|
168871
|
-
const
|
|
168872
|
-
const
|
|
168873
|
-
|
|
168874
|
-
|
|
168875
|
-
|
|
168876
|
-
|
|
168877
|
-
|
|
168878
|
-
|
|
168993
|
+
function keptAncestorChainOrDeclared(map, sourceID, url, fileText, elsewhere) {
|
|
168994
|
+
const out = [];
|
|
168995
|
+
const seen = new Set([sourceID]);
|
|
168996
|
+
let tail = { sourceID, url };
|
|
168997
|
+
for (let hops = 0;hops < MAX_HOPS; hops++) {
|
|
168998
|
+
const chain = keptAncestorChain(map, tail.sourceID, tail.url, elsewhere);
|
|
168999
|
+
out.push(...chain);
|
|
169000
|
+
tail = chain.at(-1) ?? tail;
|
|
169001
|
+
const node = nodeIn(map, tail.sourceID, elsewhere);
|
|
169002
|
+
if (!node || node.base !== undefined)
|
|
169003
|
+
break;
|
|
169004
|
+
const base = declaredTableBase(node.def, tail.url, fileText, (id) => nodeIn(map, id, elsewhere));
|
|
169005
|
+
for (const a of chain)
|
|
169006
|
+
seen.add(a.sourceID);
|
|
169007
|
+
if (!base || seen.has(base.sourceID))
|
|
169008
|
+
break;
|
|
169009
|
+
seen.add(base.sourceID);
|
|
169010
|
+
out.push(base);
|
|
169011
|
+
tail = base;
|
|
169012
|
+
}
|
|
169013
|
+
return out;
|
|
168879
169014
|
}
|
|
168880
|
-
function declaredTableBase(def, url,
|
|
169015
|
+
function declaredTableBase(def, url, fileText, nodeOf) {
|
|
168881
169016
|
const own = def;
|
|
168882
169017
|
if (own?.type !== "table")
|
|
168883
169018
|
return;
|
|
@@ -168888,8 +169023,8 @@ function declaredTableBase(def, url, map, fileText) {
|
|
|
168888
169023
|
const name = declaredBaseName(text, range);
|
|
168889
169024
|
if (name === undefined)
|
|
168890
169025
|
return;
|
|
168891
|
-
const parentID =
|
|
168892
|
-
const parent = parentID ?
|
|
169026
|
+
const parentID = declaredBaseID(name, url, text, nodeOf);
|
|
169027
|
+
const parent = parentID ? nodeOf(parentID) : undefined;
|
|
168893
169028
|
const base = parent?.def;
|
|
168894
169029
|
if (!parent || base?.type !== "table" || base.connection !== own.connection || base.tablePath !== own.tablePath) {
|
|
168895
169030
|
return;
|
|
@@ -168905,6 +169040,16 @@ function declaredTableBase(def, url, map, fileText) {
|
|
|
168905
169040
|
}
|
|
168906
169041
|
return { sourceID: parent.sourceID, url: parentURL, range: parentRange };
|
|
168907
169042
|
}
|
|
169043
|
+
function declaredBaseID(name, url, text, nodeOf) {
|
|
169044
|
+
const imports = topLevelImports(text, url);
|
|
169045
|
+
if (!imports)
|
|
169046
|
+
return;
|
|
169047
|
+
const found = [
|
|
169048
|
+
`${name}@${url}`,
|
|
169049
|
+
...imports.filter((i) => i.whole).map((i) => `${name}@${i.resolved}`)
|
|
169050
|
+
].filter((id) => nodeOf(id) !== undefined);
|
|
169051
|
+
return found.length === 1 ? found[0] : undefined;
|
|
169052
|
+
}
|
|
168908
169053
|
function fieldList(def) {
|
|
168909
169054
|
return Array.isArray(def.fields) ? def.fields : [];
|
|
168910
169055
|
}
|
|
@@ -169100,6 +169245,7 @@ var MAX_HOPS = 64;
|
|
|
169100
169245
|
var init_kept_ancestors = __esm(() => {
|
|
169101
169246
|
init_declaration_text();
|
|
169102
169247
|
init_malloy_lexer_core();
|
|
169248
|
+
init_source_map();
|
|
169103
169249
|
init_table_plans();
|
|
169104
169250
|
});
|
|
169105
169251
|
|
|
@@ -170733,6 +170879,21 @@ class ServedCopyServe {
|
|
|
170733
170879
|
async loadQuery(queryString, givens, pinned = this.current()) {
|
|
170734
170880
|
return this.answer(await this.ensureCompiled(pinned), queryString, givens, pinned);
|
|
170735
170881
|
}
|
|
170882
|
+
async queriedSourceIDs(compiled, queryString) {
|
|
170883
|
+
if (!compiled.leftOutColumns?.size)
|
|
170884
|
+
return;
|
|
170885
|
+
try {
|
|
170886
|
+
const prepared = await this.host.authorPreparedQuery?.(queryString);
|
|
170887
|
+
if (prepared === undefined)
|
|
170888
|
+
return;
|
|
170889
|
+
const view = preparedQueryView(prepared);
|
|
170890
|
+
const modelDef = view.modelDef ?? this.host.modelDef();
|
|
170891
|
+
const struct = resolveStructRefSource(view.structRef, modelDef);
|
|
170892
|
+
return struct ? sourceIDsReadThrough(struct, modelDef) : undefined;
|
|
170893
|
+
} catch {
|
|
170894
|
+
return;
|
|
170895
|
+
}
|
|
170896
|
+
}
|
|
170736
170897
|
async beginAttempt(compiled, queryString, givens) {
|
|
170737
170898
|
if (!compiled.materializer || compiled.rerooted.length === 0) {
|
|
170738
170899
|
const crossConnection = compiled.problems.some((p) => p.reason === "cross_connection_unbuilt");
|
|
@@ -170769,24 +170930,9 @@ class ServedCopyServe {
|
|
|
170769
170930
|
if (zoned.size > 0 && readsMissingName(zoned, error, queryString)) {
|
|
170770
170931
|
decline(ZONED_TRUNCATION_REASON, "served_copy_time_zone");
|
|
170771
170932
|
}
|
|
170772
|
-
const
|
|
170773
|
-
|
|
170774
|
-
|
|
170775
|
-
if (storedLeftOut.size > 0 && readsMissingName(storedLeftOut, error, queryString)) {
|
|
170776
|
-
const missing = new Set([
|
|
170777
|
-
...String(error instanceof Error ? error.message : error).matchAll(/'([^']+)' is not defined/g)
|
|
170778
|
-
].map((m) => m[1]));
|
|
170779
|
-
const read = [...storedLeftOut].filter((n) => missing.has(n));
|
|
170780
|
-
const named = read.length > 0 ? read : [...storedLeftOut];
|
|
170781
|
-
const sourceIDs = new Set([...compiled.leftOutColumns ?? []].filter(([, names]) => names.some((n) => named.includes(n))).map(([sourceID]) => sourceID));
|
|
170782
|
-
const tableIds = compiled.aliased.filter((b) => b.sourceIDs?.some((id) => sourceIDs.has(id))).map((b) => b.virtualHandle);
|
|
170783
|
-
const why = [
|
|
170784
|
-
...new Set(named.flatMap((c) => {
|
|
170785
|
-
const reasons = [...sourceIDs].map((id) => compiled.leftOutWhy?.get(id)?.get(c)).filter((w) => w !== undefined);
|
|
170786
|
-
return reasons.length > 0 ? reasons : [noCastPhrase("a stored column")];
|
|
170787
|
-
}))
|
|
170788
|
-
];
|
|
170789
|
-
decline("the query reads a stored column the served copy leaves out of its table's type", "served_copy_column_left_out", `the stored table cannot answer with live's columns: ${why.join("; ")}`, tableIds);
|
|
170933
|
+
const leftOut = columnLeftOutDecline(compiled, error, queryString, await this.queriedSourceIDs(compiled, queryString));
|
|
170934
|
+
if (leftOut) {
|
|
170935
|
+
decline("the query reads a stored column the served copy leaves out of its table's type", "served_copy_column_left_out", leftOut.detail, leftOut.tableIds);
|
|
170790
170936
|
}
|
|
170791
170937
|
throw error;
|
|
170792
170938
|
}
|
|
@@ -171214,8 +171360,8 @@ class ServedCopyServe {
|
|
|
171214
171360
|
const plan = this.materializePlans[reroot.sourceID];
|
|
171215
171361
|
if (!plan)
|
|
171216
171362
|
return;
|
|
171217
|
-
const confirmed = confirmedAncestors(fileText, reroot.url, reroot.range, keptAncestorChainOrDeclared(map, reroot.sourceID, reroot.url, fileText));
|
|
171218
|
-
const needed = confirmed.some((a) => this.materializePlans[a.sourceID] !== undefined) || confirmed.some((a) => declaresBlocks(map.node(a.sourceID)?.def));
|
|
171363
|
+
const confirmed = confirmedAncestors(fileText, reroot.url, reroot.range, keptAncestorChainOrDeclared(map, reroot.sourceID, reroot.url, fileText, this.declarationOf));
|
|
171364
|
+
const needed = confirmed.some((a) => this.materializePlans[a.sourceID] !== undefined) || confirmed.some((a) => declaresBlocks(map.node(a.sourceID)?.def ?? this.declarationOf?.(a.sourceID)));
|
|
171219
171365
|
if (!needed)
|
|
171220
171366
|
return;
|
|
171221
171367
|
return confirmed.flatMap((a) => a.runText ? [a.runText] : []).reverse().join(" ");
|
|
@@ -172068,6 +172214,66 @@ function leftOutPhrase(ref, field, storedType) {
|
|
|
172068
172214
|
function leftOutPhraseOf(subject, c) {
|
|
172069
172215
|
return leftOutPhrase(subject.columnRef(c.name), subject.fieldsByName.get(c.name), c.type);
|
|
172070
172216
|
}
|
|
172217
|
+
function sourceIDsReadThrough(struct, modelDef) {
|
|
172218
|
+
const map = SourceMap.of(modelDef);
|
|
172219
|
+
const out = new Map;
|
|
172220
|
+
const walk = (def, path, depth) => {
|
|
172221
|
+
for (const id of map.chainOf(def)) {
|
|
172222
|
+
if (!out.has(id))
|
|
172223
|
+
out.set(id, path);
|
|
172224
|
+
}
|
|
172225
|
+
if (depth >= JOIN_DEPTH_LIMIT)
|
|
172226
|
+
return;
|
|
172227
|
+
const fields = def?.fields;
|
|
172228
|
+
if (!Array.isArray(fields))
|
|
172229
|
+
return;
|
|
172230
|
+
for (const f of fields) {
|
|
172231
|
+
if (f?.join === undefined)
|
|
172232
|
+
continue;
|
|
172233
|
+
const name = f.as ?? f.name;
|
|
172234
|
+
if (!name)
|
|
172235
|
+
continue;
|
|
172236
|
+
walk(f, path ? `${path}.${name}` : name, depth + 1);
|
|
172237
|
+
}
|
|
172238
|
+
};
|
|
172239
|
+
walk(struct, "", 0);
|
|
172240
|
+
return out;
|
|
172241
|
+
}
|
|
172242
|
+
function columnLeftOutDecline(compiled, error, queryString, readIDs) {
|
|
172243
|
+
const storedLeftOut = new Set([...compiled.leftOutColumns?.values() ?? []].flatMap((n) => [...n]));
|
|
172244
|
+
if (storedLeftOut.size === 0 || !readsMissingName(storedLeftOut, error, queryString)) {
|
|
172245
|
+
return;
|
|
172246
|
+
}
|
|
172247
|
+
const missing = new Set([
|
|
172248
|
+
...String(error instanceof Error ? error.message : error).matchAll(/'([^']+)' is not defined/g)
|
|
172249
|
+
].map((m) => m[1]));
|
|
172250
|
+
const read = [...storedLeftOut].filter((n) => missing.has(n));
|
|
172251
|
+
const named = read.length > 0 ? read : [...storedLeftOut];
|
|
172252
|
+
const leaving = [...compiled.leftOutColumns ?? []].filter(([, names]) => names.some((n) => named.includes(n))).map(([sourceID]) => sourceID);
|
|
172253
|
+
const scoped = readIDs ? leaving.filter((id) => readIDs.has(id)) : [];
|
|
172254
|
+
const sourceIDs = new Set(scoped.length > 0 ? scoped : leaving);
|
|
172255
|
+
const pathOf = (id) => scoped.length > 0 ? readIDs?.get(id) : "";
|
|
172256
|
+
const tableIds = compiled.aliased.filter((b) => b.sourceIDs?.some((id) => sourceIDs.has(id))).map((b) => b.virtualHandle);
|
|
172257
|
+
const why = [
|
|
172258
|
+
...new Set(named.flatMap((c) => {
|
|
172259
|
+
const reasons = [...sourceIDs].flatMap((id) => {
|
|
172260
|
+
const phrase = compiled.leftOutWhy?.get(id)?.get(c);
|
|
172261
|
+
if (phrase === undefined)
|
|
172262
|
+
return [];
|
|
172263
|
+
const path = pathOf(id);
|
|
172264
|
+
const own = `column \`${c}\``;
|
|
172265
|
+
return [
|
|
172266
|
+
path && phrase.startsWith(own) ? `column \`${path}.${c}\`${phrase.slice(own.length)}` : phrase
|
|
172267
|
+
];
|
|
172268
|
+
});
|
|
172269
|
+
return reasons.length > 0 ? reasons : [noCastPhrase("a stored column")];
|
|
172270
|
+
}))
|
|
172271
|
+
];
|
|
172272
|
+
return {
|
|
172273
|
+
detail: `the stored table cannot answer with live's columns: ${why.join("; ")}`,
|
|
172274
|
+
tableIds
|
|
172275
|
+
};
|
|
172276
|
+
}
|
|
172071
172277
|
function noCastPhrase(ref) {
|
|
172072
172278
|
return `no cast reads ${ref} as declared`;
|
|
172073
172279
|
}
|
|
@@ -172930,7 +173136,7 @@ function zonedTruncations(columns, def, fieldsByName, chainZone, restatesStageZo
|
|
|
172930
173136
|
restated: []
|
|
172931
173137
|
};
|
|
172932
173138
|
}
|
|
172933
|
-
var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig4({ connections: {} }), PAIR_BLOCKS_DETAIL = "The table stores more than one inlined join_many, one block of rows each, and the query reads more than one of them (live aggregates each by its own key over their cross product, which no block holds), so it is answered without this table.", LEFT_OUT_JOIN_DETAIL = "The query uses a join to a source on another connection than the destination this table is stored in, so it is answered live.", MISSING_FIELD_CODES, SERVED_COPY_WARNING_CODE = "served-copy-not-served", DECLINED_LIMIT = 1000, knownRerootFailures, REROOT_FAILURE_TTL_MS, ESCAPED_FAILURE_RETRY_MS = 30000, REROOT_FAILURES_PER_CONFIG = 64, GATE_GRAFT_DECLINE, HIDDEN_COLUMN = "a hidden column";
|
|
173139
|
+
var NOTHING_PINNED, NO_DESTINATIONS = () => new MalloyConfig4({ connections: {} }), PAIR_BLOCKS_DETAIL = "The table stores more than one inlined join_many, one block of rows each, and the query reads more than one of them (live aggregates each by its own key over their cross product, which no block holds), so it is answered without this table.", LEFT_OUT_JOIN_DETAIL = "The query uses a join to a source on another connection than the destination this table is stored in, so it is answered live.", MISSING_FIELD_CODES, SERVED_COPY_WARNING_CODE = "served-copy-not-served", DECLINED_LIMIT = 1000, knownRerootFailures, REROOT_FAILURE_TTL_MS, ESCAPED_FAILURE_RETRY_MS = 30000, REROOT_FAILURES_PER_CONFIG = 64, GATE_GRAFT_DECLINE, HIDDEN_COLUMN = "a hidden column", JOIN_DEPTH_LIMIT = 8;
|
|
172934
173140
|
var init_served_copy_serve = __esm(() => {
|
|
172935
173141
|
init_ducklake_catalog_unavailable();
|
|
172936
173142
|
init_served_copy_lanes();
|
|
@@ -180479,6 +180685,7 @@ class PlanLifecycle {
|
|
|
180479
180685
|
};
|
|
180480
180686
|
connectionsChangedSinceDerived = new Set;
|
|
180481
180687
|
refreshFailedTransiently = false;
|
|
180688
|
+
heldWithdrawn = new Set;
|
|
180482
180689
|
stale;
|
|
180483
180690
|
staleSeq = 0;
|
|
180484
180691
|
refreshChain = Promise.resolve(true);
|
|
@@ -180577,6 +180784,9 @@ class PlanLifecycle {
|
|
|
180577
180784
|
get withdrawn() {
|
|
180578
180785
|
return this.serving().withdrawn;
|
|
180579
180786
|
}
|
|
180787
|
+
holdWithdrawn(hold) {
|
|
180788
|
+
this.heldWithdrawn = hold ? new Set(this.withdrawn) : new Set;
|
|
180789
|
+
}
|
|
180580
180790
|
servingPlan() {
|
|
180581
180791
|
return this.state.serving?.plan ?? null;
|
|
180582
180792
|
}
|
|
@@ -180626,7 +180836,7 @@ class PlanLifecycle {
|
|
|
180626
180836
|
buildConnectionNames: new Set(outcome.buildConnectionNames),
|
|
180627
180837
|
asOfBuild: outcome.asOfBuild ?? {},
|
|
180628
180838
|
upstreamSchemas: outcome.upstreamSchemas ?? {},
|
|
180629
|
-
withdrawn: new Set,
|
|
180839
|
+
withdrawn: new Set(this.heldWithdrawn),
|
|
180630
180840
|
stringCapabilityReads: outcome.stringCapabilityReads ?? {}
|
|
180631
180841
|
};
|
|
180632
180842
|
}
|
|
@@ -186131,6 +186341,7 @@ var init_inline_uniqueness = __esm(() => {
|
|
|
186131
186341
|
|
|
186132
186342
|
// src/service/materialization/run/build_failure_class.ts
|
|
186133
186343
|
import { MalloyError as MalloyError6 } from "@malloydata/malloy";
|
|
186344
|
+
import * as path27 from "path";
|
|
186134
186345
|
function isDeterministicWarehouseError(err) {
|
|
186135
186346
|
for (const e of causeChain(err)) {
|
|
186136
186347
|
const fields = e;
|
|
@@ -186196,6 +186407,49 @@ function classifySourceFailure(err, failedUpstreams) {
|
|
|
186196
186407
|
const upstreamDetail = failedUpstreams.map((u) => `upstream '${u.name}' failed in this run: ${u.reason}`).join("; ");
|
|
186197
186408
|
return { retryable, upstreamDetail };
|
|
186198
186409
|
}
|
|
186410
|
+
function modelLabelOf(sourceID, packagePath) {
|
|
186411
|
+
const at = sourceID.indexOf("@");
|
|
186412
|
+
if (at < 0)
|
|
186413
|
+
return;
|
|
186414
|
+
const model = sourceID.slice(at + 1);
|
|
186415
|
+
if (!model)
|
|
186416
|
+
return;
|
|
186417
|
+
if (!model.includes("://"))
|
|
186418
|
+
return model;
|
|
186419
|
+
if (packagePath !== undefined) {
|
|
186420
|
+
const relative = packageRelativeSourceID(packagePath, sourceID);
|
|
186421
|
+
const file = relative.slice(relative.indexOf("@") + 1);
|
|
186422
|
+
if (relative !== sourceID && file && !file.startsWith("../") && !path27.isAbsolute(file)) {
|
|
186423
|
+
return file;
|
|
186424
|
+
}
|
|
186425
|
+
}
|
|
186426
|
+
try {
|
|
186427
|
+
const segments = new URL(model).pathname.split("/").filter(Boolean);
|
|
186428
|
+
return segments.length > 0 ? decodeURIComponent(segments[segments.length - 1]) : undefined;
|
|
186429
|
+
} catch {
|
|
186430
|
+
return;
|
|
186431
|
+
}
|
|
186432
|
+
}
|
|
186433
|
+
function strictMissReason(sourceName, err, failedUpstreams, options = {}) {
|
|
186434
|
+
const message = options.message ?? String(err?.message);
|
|
186435
|
+
const miss = strictMissSourceId(err);
|
|
186436
|
+
if (miss === undefined)
|
|
186437
|
+
return;
|
|
186438
|
+
const prefix = `Failed to materialize source '${sourceName}': `;
|
|
186439
|
+
const label = miss.sourceID ? modelLabelOf(miss.sourceID, options.packagePath) : undefined;
|
|
186440
|
+
const named = (name) => `its persisted upstream '${name}'${label ? ` (${label})` : ""}`;
|
|
186441
|
+
const perValue = message.includes(GIVENS_MISS_HINT) ? ` ${GIVENS_MISS_HINT}` : "";
|
|
186442
|
+
const newline = message.indexOf(`
|
|
186443
|
+
`);
|
|
186444
|
+
const loadError = newline >= 0 ? message.slice(newline + 1).trim() : undefined;
|
|
186445
|
+
const tail = perValue + (loadError ? ` The build manifest failed to load: ${loadError}` : "");
|
|
186446
|
+
if (failedUpstreams.length > 0) {
|
|
186447
|
+
return prefix + failedUpstreams.map((u) => `${named(u.name)} failed to build in this run: ${u.reason}`).join("; ") + (tail ? `.${tail}` : "");
|
|
186448
|
+
}
|
|
186449
|
+
const upstream = miss.sourceID ? named(miss.sourceID.split("@")[0]) : "a persisted upstream it reads";
|
|
186450
|
+
const why = perValue ? `${upstream} has no table this build can read.${tail}` : `${upstream} has no table this build can read (it is not built ` + `yet, or was supplied where this build cannot read it), and a build ` + `never recomputes a persisted upstream from its definition` + (tail ? `.${tail}` : "");
|
|
186451
|
+
return prefix + why;
|
|
186452
|
+
}
|
|
186199
186453
|
function failedUpstreamsOf(sourceID, err, upstreamsBySourceID, failedBySourceID) {
|
|
186200
186454
|
const declared = upstreamsBySourceID.get(sourceID) ?? [];
|
|
186201
186455
|
const missedId = strictMissSourceId(err)?.sourceID;
|
|
@@ -186254,8 +186508,9 @@ function failedRunManifestOf(err) {
|
|
|
186254
186508
|
function classifyRunFailure(err) {
|
|
186255
186509
|
return err instanceof BuildRunFailedError ? err.retryable : classifyBuildError(err);
|
|
186256
186510
|
}
|
|
186257
|
-
var DETERMINISTIC_MARKERS, TRANSIENT_MARKERS, TRANSIENT_CODES_IN_MESSAGES, DETERMINISTIC_SQLSTATE, UNCLASSIFIED_SQLSTATES, BIGQUERY_DETERMINISTIC_REASONS, BIGQUERY_MISSING_NAME, BuildRunFailedError;
|
|
186511
|
+
var DETERMINISTIC_MARKERS, TRANSIENT_MARKERS, TRANSIENT_CODES_IN_MESSAGES, DETERMINISTIC_SQLSTATE, UNCLASSIFIED_SQLSTATES, BIGQUERY_DETERMINISTIC_REASONS, BIGQUERY_MISSING_NAME, GIVENS_MISS_HINT = "This source reads givens, and no table was built for the given values this query supplies.", BuildRunFailedError;
|
|
186258
186512
|
var init_build_failure_class = __esm(() => {
|
|
186513
|
+
init_read_text();
|
|
186259
186514
|
init_errors2();
|
|
186260
186515
|
init_driver_errors();
|
|
186261
186516
|
init_utils();
|
|
@@ -187808,7 +188063,7 @@ var init_database_build_strategy = __esm(() => {
|
|
|
187808
188063
|
|
|
187809
188064
|
// src/service/materialization/run/storage_admin.ts
|
|
187810
188065
|
import { existsSync as existsSync3, readdirSync as readdirSync3 } from "node:fs";
|
|
187811
|
-
import
|
|
188066
|
+
import path28 from "node:path";
|
|
187812
188067
|
function dropStorageTableSql(destinationName, physicalTableName, schema) {
|
|
187813
188068
|
return `DROP TABLE IF EXISTS ${quoteManifestTablePath(storageTablePath(destinationName, physicalTableName, schema), STORAGE_DIALECT)}`;
|
|
187814
188069
|
}
|
|
@@ -187851,7 +188106,7 @@ async function listStorageTables(params) {
|
|
|
187851
188106
|
} else {
|
|
187852
188107
|
const dbPath = storageDestinationFile(environmentPath, destinationName);
|
|
187853
188108
|
const destinationRoot = storageDestinationRoot(environmentPath);
|
|
187854
|
-
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(
|
|
188109
|
+
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(path28.basename(dbPath))) {
|
|
187855
188110
|
return [];
|
|
187856
188111
|
}
|
|
187857
188112
|
await session.runSQL(`ATTACH '${escapeSQL(dbPath)}' AS ${quoteIdentifier(destinationName, STORAGE_DIALECT)} (READ_ONLY)`);
|
|
@@ -188716,10 +188971,14 @@ class RunTelemetry {
|
|
|
188716
188971
|
refused,
|
|
188717
188972
|
failed,
|
|
188718
188973
|
...cancelled > 0 ? { cancelled } : {},
|
|
188719
|
-
...err !== undefined ?
|
|
188974
|
+
...err !== undefined ? errorLogFields(err) : {}
|
|
188720
188975
|
});
|
|
188721
188976
|
}
|
|
188722
188977
|
}
|
|
188978
|
+
function errorLogFields(err) {
|
|
188979
|
+
const detail = runtimeErrorTextOf(err);
|
|
188980
|
+
return { code: errorCodeOf(err), ...detail ? { detail } : {} };
|
|
188981
|
+
}
|
|
188723
188982
|
function markRunFailureReported(err) {
|
|
188724
188983
|
if (typeof err === "object" && err !== null)
|
|
188725
188984
|
reportedRunFailures.add(err);
|
|
@@ -188805,7 +189064,7 @@ function reportSourceFailed(source, err, retryable, cancelled) {
|
|
|
188805
189064
|
...source.durationMs !== undefined ? { durationMs: source.durationMs } : {},
|
|
188806
189065
|
outcome: failureClass === "none" ? "cancelled" : "failed",
|
|
188807
189066
|
failureClass,
|
|
188808
|
-
|
|
189067
|
+
...errorLogFields(err),
|
|
188809
189068
|
...source.destination ? { destinationName: source.destination } : {}
|
|
188810
189069
|
});
|
|
188811
189070
|
}
|
|
@@ -188983,8 +189242,30 @@ function assertInstructedDestinationWritable(persistSource, instruction, compile
|
|
|
188983
189242
|
}
|
|
188984
189243
|
const declared = declaredStorage(persistSource);
|
|
188985
189244
|
if (declared && !instruction.destination) {
|
|
188986
|
-
|
|
188987
|
-
|
|
189245
|
+
throw new BadRequestError(`${declaredStorageSubject(persistSource, compiled, declared)}` + `, but the build was instructed with no storage ` + `destination, so there is nowhere it may be written. ` + `Refusing rather than building the table into the source ` + `warehouse, which the annotation asked it not to be ` + `written to.`);
|
|
189246
|
+
}
|
|
189247
|
+
}
|
|
189248
|
+
function declaredStorageSubject(persistSource, compiled, declared) {
|
|
189249
|
+
const table = compiled.tables[persistSource.sourceID];
|
|
189250
|
+
const origin = table ? originOfTable(table.kind, persistSource.sourceID) : "persist";
|
|
189251
|
+
switch (origin) {
|
|
189252
|
+
case "rollup": {
|
|
189253
|
+
const rollup = table?.rollup;
|
|
189254
|
+
const at = rollup ? `Measures of \`${rollup.baseSourceName}\` pre-aggregated at ` + `grain (${rollup.grainDimensions.join(", ")})` : `Rollup '${persistSource.name}'`;
|
|
189255
|
+
return `${at} declare \`storage=${declared}\` on ` + `\`#(rollup)\` (or v1's \`#@ preaggregate\`)`;
|
|
189256
|
+
}
|
|
189257
|
+
case "materialize":
|
|
189258
|
+
return `Source '${table?.materialize?.sourceName ?? persistSource.name}' ` + `declares \`#(materialize) storage=${declared}\``;
|
|
189259
|
+
case "view": {
|
|
189260
|
+
const [, source, view] = /^(.+)__(.+)__view$/.exec(persistSource.name) ?? [];
|
|
189261
|
+
return view ? `\`#@ persist storage=${declared}\` on view '${view}' of ` + `source '${source}'` : `View source '${persistSource.name}' declares ` + `\`#@ persist storage=${declared}\``;
|
|
189262
|
+
}
|
|
189263
|
+
case "query": {
|
|
189264
|
+
const [, query] = /^(.+)__query$/.exec(persistSource.name) ?? [];
|
|
189265
|
+
return `\`#@ persist storage=${declared}\` on query '${query ?? persistSource.name}'`;
|
|
189266
|
+
}
|
|
189267
|
+
default:
|
|
189268
|
+
return `Source '${persistSource.name}' declares ` + `\`#@ persist storage=${declared}\``;
|
|
188988
189269
|
}
|
|
188989
189270
|
}
|
|
188990
189271
|
function recordInstructedBuildFailure(run, persistSource, instruction, sourceEntityId, buildErr, build) {
|
|
@@ -188994,8 +189275,12 @@ function recordInstructedBuildFailure(run, persistSource, instruction, sourceEnt
|
|
|
188994
189275
|
} catch {
|
|
188995
189276
|
reason = redactStorageUrls(redactPgSecrets(errMessage(buildErr)));
|
|
188996
189277
|
}
|
|
188997
|
-
const
|
|
188998
|
-
|
|
189278
|
+
const failedUpstreams = failedUpstreamsOf(persistSource.sourceID, buildErr, run.upstreamsBySourceID, run.failedBySourceID);
|
|
189279
|
+
const { retryable, upstreamDetail } = classifySourceFailure(buildErr, failedUpstreams);
|
|
189280
|
+
const missReason = strictMissReason(persistSource.name, buildErr, failedUpstreams, { message: reason, packagePath: run.environment.getPackagePath?.() });
|
|
189281
|
+
if (missReason !== undefined)
|
|
189282
|
+
reason = missReason;
|
|
189283
|
+
else if (upstreamDetail)
|
|
188999
189284
|
reason = `${reason}; ${upstreamDetail}`;
|
|
189000
189285
|
run.failedBySourceID.set(persistSource.sourceID, {
|
|
189001
189286
|
name: persistSource.name,
|
|
@@ -189688,7 +189973,7 @@ var init_table_ownership = __esm(() => {
|
|
|
189688
189973
|
});
|
|
189689
189974
|
|
|
189690
189975
|
// src/service/materialization/run/run_instructions.ts
|
|
189691
|
-
import * as
|
|
189976
|
+
import * as path29 from "path";
|
|
189692
189977
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
189693
189978
|
function gateSources(compiled, include, pulledIn = new Set) {
|
|
189694
189979
|
const sources = [];
|
|
@@ -189755,9 +190040,9 @@ function modelPathOf(compiled, persistSource, packagePath) {
|
|
|
189755
190040
|
if (packagePath && url.startsWith("file:")) {
|
|
189756
190041
|
try {
|
|
189757
190042
|
const file = authorModelPath(fileURLToPath11(url));
|
|
189758
|
-
const relative =
|
|
189759
|
-
if (relative && !relative.startsWith("..") && !
|
|
189760
|
-
return relative.split(
|
|
190043
|
+
const relative = path29.relative(packagePath, file);
|
|
190044
|
+
if (relative && !relative.startsWith("..") && !path29.isAbsolute(relative)) {
|
|
190045
|
+
return relative.split(path29.sep).join("/");
|
|
189761
190046
|
}
|
|
189762
190047
|
} catch {}
|
|
189763
190048
|
}
|
|
@@ -194055,7 +194340,7 @@ class MaterializationService {
|
|
|
194055
194340
|
const environment = await this.host.getEnvironment(parseEnvironmentName(environmentName), false);
|
|
194056
194341
|
const version = await this.resolveRunVersion(environmentName, packageName, options.versionId ?? VersionRef.LATEST);
|
|
194057
194342
|
const pkg = await environment.getPackage(parsePackageName(packageName), false, version !== null ? { versionId: VersionRef.parse(version) } : {});
|
|
194058
|
-
if (version === null && environment.
|
|
194343
|
+
if (version === null && environment.getRefusedReloads().has(packageName)) {
|
|
194059
194344
|
throw new BuildPlanUnavailableError(`Package ${packageName} serves an older model than its files: its last reload refused them. Fix the files and reload the package, then run again.`);
|
|
194060
194345
|
}
|
|
194061
194346
|
const scope = version !== null ? pkg.getPackageMetadata().scope ?? "package" : null;
|
|
@@ -194311,7 +194596,7 @@ class MaterializationService {
|
|
|
194311
194596
|
const owned = versionId !== undefined ? ownedVersionOf(pkg) : undefined;
|
|
194312
194597
|
const reader = versionId !== undefined ? { versionId, owned } : {};
|
|
194313
194598
|
const { runPlan: compiled, packagePlan } = versionId !== undefined ? await compileRunPlan(pkg, signal) : await environment.withPackageLock(packageName, () => compileRunPlan(pkg, signal));
|
|
194314
|
-
const stale = versionId === undefined && environment.
|
|
194599
|
+
const stale = versionId === undefined && environment.getRefusedReloads().has(packageName);
|
|
194315
194600
|
const invalid = runPlanGateText(packagePlan, {
|
|
194316
194601
|
enforceCollisions: getPersistCollisionEnforce(),
|
|
194317
194602
|
versionScoped: owned !== undefined
|
|
@@ -194454,7 +194739,7 @@ Fix the files and reload the package, then run again.`);
|
|
|
194454
194739
|
return await this.collaborators.executeInstructedBuild({
|
|
194455
194740
|
refusedAtPlan,
|
|
194456
194741
|
compiled,
|
|
194457
|
-
environment: withChainBuildText(environment, pkg, () => versionId === undefined && (environment.
|
|
194742
|
+
environment: withChainBuildText(environment, pkg, () => versionId === undefined && (environment.getRefusedReloads?.().has(packageName) ?? false)),
|
|
194458
194743
|
instructions,
|
|
194459
194744
|
seedEntries: carried,
|
|
194460
194745
|
signal,
|
|
@@ -195947,19 +196232,19 @@ var init_package_load_metrics = __esm(() => {
|
|
|
195947
196232
|
});
|
|
195948
196233
|
|
|
195949
196234
|
// src/controller/manifest_location.ts
|
|
195950
|
-
import * as
|
|
196235
|
+
import * as path30 from "path";
|
|
195951
196236
|
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
195952
196237
|
function isManifestLocation(value) {
|
|
195953
196238
|
if (/^(gs|s3):\/\/[^/]+\/./.test(value))
|
|
195954
196239
|
return true;
|
|
195955
196240
|
if (value.startsWith("file://")) {
|
|
195956
196241
|
try {
|
|
195957
|
-
return
|
|
196242
|
+
return path30.isAbsolute(fileURLToPath12(value));
|
|
195958
196243
|
} catch {
|
|
195959
196244
|
return false;
|
|
195960
196245
|
}
|
|
195961
196246
|
}
|
|
195962
|
-
return !value.includes("://") &&
|
|
196247
|
+
return !value.includes("://") && path30.isAbsolute(value);
|
|
195963
196248
|
}
|
|
195964
196249
|
function versionManifestLocation(value) {
|
|
195965
196250
|
if (value === undefined)
|
|
@@ -197857,7 +198142,7 @@ var init_report_controller = __esm(() => {
|
|
|
197857
198142
|
|
|
197858
198143
|
// src/service/skills/build_skills_bundle.ts
|
|
197859
198144
|
import * as fs13 from "fs";
|
|
197860
|
-
import * as
|
|
198145
|
+
import * as path31 from "path";
|
|
197861
198146
|
function unquote3(s) {
|
|
197862
198147
|
return s.trim().replace(/^["']|["']$/g, "");
|
|
197863
198148
|
}
|
|
@@ -197875,7 +198160,7 @@ function parseSkill(md, dirName) {
|
|
|
197875
198160
|
return { name, description, body };
|
|
197876
198161
|
}
|
|
197877
198162
|
function referenceName(skillName, file) {
|
|
197878
|
-
return `${skillName}/${
|
|
198163
|
+
return `${skillName}/${path31.basename(file, ".md")}`;
|
|
197879
198164
|
}
|
|
197880
198165
|
function parseReference(md, skillName, file) {
|
|
197881
198166
|
const body = stripLicenseHeader(md.replace(/\r\n/g, `
|
|
@@ -197888,7 +198173,7 @@ function parseReference(md, skillName, file) {
|
|
|
197888
198173
|
};
|
|
197889
198174
|
}
|
|
197890
198175
|
function referencePointer(skillName, files, channel = "bundled") {
|
|
197891
|
-
const stems = files.map((f) =>
|
|
198176
|
+
const stems = files.map((f) => path31.basename(f, ".md"));
|
|
197892
198177
|
const how = channel === "bundled" ? `served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read \`${REFERENCE_DIR}/<name>.md\`, get the prompt named \`${skillName}/<name>\` instead.` : `served as separate guides, one per file, fetched only when you ask for them. Where the text above says to read \`${REFERENCE_DIR}/<name>.md\`, call get_skill with skill_name \`${skillName}/<name>\` and the same \`scopes\` you used for this skill instead.`;
|
|
197893
198178
|
return [
|
|
197894
198179
|
`## Reference files over MCP`,
|
|
@@ -197900,7 +198185,7 @@ function referencePointer(skillName, files, channel = "bundled") {
|
|
|
197900
198185
|
`);
|
|
197901
198186
|
}
|
|
197902
198187
|
function referenceFiles(skillDir) {
|
|
197903
|
-
const dir =
|
|
198188
|
+
const dir = path31.join(skillDir, REFERENCE_DIR);
|
|
197904
198189
|
if (!fs13.existsSync(dir))
|
|
197905
198190
|
return [];
|
|
197906
198191
|
return fs13.readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
|
|
@@ -202339,7 +202624,7 @@ End with a short **Next steps**: one or two specific deeper analyses the data co
|
|
|
202339
202624
|
{
|
|
202340
202625
|
name: "malloy-analysis-report",
|
|
202341
202626
|
description: 'Combine validated Malloy queries into a report (a linear report, read top to bottom). Use when the user asks to "create a report", "combine these into a report", or wants a persistent multi-query artifact.',
|
|
202342
|
-
body: "# Creating Reports\n\nAn ad-hoc report is a Publisher **report** with `layout=linear`: a `.malloy` file at the package root, `<slug>.malloy` (unless the user asks for another location), that combines markdown narrative with live Malloy queries, as text tiles and query tiles read top to bottom. Load `skill:malloy-reports` for the full format and authoring rules; this skill covers when to build one and how to design good report content (tiles, chart annotations, narrative structure). Never write a
|
|
202627
|
+
body: "# Creating Reports\n\nAn ad-hoc report is a Publisher **report** with `layout=linear`: a `.malloy` file at the package root, `<slug>.malloy` (unless the user asks for another location), that combines markdown narrative with live Malloy queries, as text tiles and query tiles read top to bottom. Load `skill:malloy-reports` for the full format and authoring rules; this skill covers when to build one and how to design good report content (tiles, chart annotations, narrative structure). Never write a report as bare `run:` statements (that older form is no longer read), and do not create a `notebooks/` or `dashboards/` directory for it.\n\n## Before building a report\n\n1. **Run each query first** via `execute_query` to verify it works and returns expected results.\n2. **Explain the results** to the user as you go: walk through the analysis step by step.\n3. **Then assemble the report** once the analysis is validated.\n\nDo NOT build the report in the same turn as `execute_query`. Explain first, then build.\n\n## Filters belong to the report, never to the source\n\nAn ad-hoc report usually needs no filters: it records an analysis already run. If the user wants one a reader can change (a manufacturer, a date range), declare the given in the report and bind it on its tiles, as `skill:malloy-reports` describes. Do not add a `given:` to the source for it: a model-level `where:` filters every read of the source, chat and every other report included, and the report builder can show such a filter but not change or remove it. A given the source already reads (a gate, a value every query must supply) shows in the report with no work, and stays in the model.\n\nNever add a `#(filter)` annotation: it is deprecated, and every use has a `given:` form (`malloy-model` covers the migration).\n\n## What goes in the report\n\nDo NOT add an H1 heading in any markdown (use H2 and below for sections); the `title` in the `## artifact` tag serves as the title. To redo the structure rather than tweak one tile, rewrite the report file end-to-end.\n\nText tiles own narrative; query tiles own a single Malloy query whose chart annotation tells the renderer how to display the result. Markdown supports H2 headings, lists, bold, and inline code. Keep text tiles short, one idea per tile, so the rendered output reads as a story instead of a wall of text.\n\nThe file has four parts, in this order:\n\n1. **The tag**, `##| artifact { layout=linear title=\"...\" tiles=[…] }`, listing every tile in reading order. A text tile is `name { kind=text }`; a query tile is the quoted string `\"<extension> -> <view>\"`.\n2. **The `import`** of the model file, relative to the report's own location (`\"order_analysis.malloy\"` from the package root).\n3. **The text tiles**, each a `##|(markdown) name` block: the name on the opener line, the body on the lines below, `|##` closing it.\n4. **One extension of the source**, `source: <source>_tiles is <source> extend { … }`, holding a `view:` per query tile. The view's chart tag and `# label=\"…\"` (the tile's heading) go directly above it.\n\nCompile the file with `/compile` (`\"scope\": \"file\"`, at the path `<slug>.malloy`) before saving; a report compiles as a model, so its errors come back there. After saving and reloading, read the package warnings: a tile that names a missing view is reported there, not by the compile. A complete report:\n\n```malloy\n##| artifact { layout=linear title=\"Sales report\"\n tiles=[\n overview { kind=text },\n \"order_analysis_tiles -> headline\",\n trend { kind=text },\n \"order_analysis_tiles -> revenue_by_month\",\n breakdown { kind=text },\n \"order_analysis_tiles -> top_categories\",\n takeaways { kind=text }\n ]\n}\n|##\nimport \"order_analysis.malloy\"\n\n##|(markdown) overview\n## Overview\nWhat is driving sales, and which categories carry it? The tiles below cover every order in the model.\n|##\n\n##|(markdown) trend\n## Trend\nHow does revenue move over time?\n|##\n\n##|(markdown) breakdown\n## Breakdown\nWhich categories account for the most revenue?\n|##\n\n##|(markdown) takeaways\n## Key takeaways\nWhat to look at next.\n|##\n\nsource: order_analysis_tiles is order_analysis extend {\n # big_value\n # label=\"Headline\"\n view: headline is {\n aggregate:\n # label=\"Revenue\"\n # currency\n total_revenue\n\n # label=\"Orders\"\n # number=auto\n order_count\n }\n\n # line_chart\n # label=\"Revenue by month\"\n view: revenue_by_month is {\n group_by: order_date.month\n aggregate: total_revenue\n order_by: 1\n }\n\n # bar_chart\n # label=\"Top ten categories by revenue\"\n view: top_categories is {\n group_by: category\n aggregate: total_revenue\n order_by: total_revenue desc\n limit: 10\n }\n}\n```\n\nWhen the model already has the view you want, the tile view refines it rather than repeating it: `view: top_categories is by_category + { limit: 10 }`.\n\nA well-structured report typically follows this pattern:\n\n```\n[Text] ## Overview: what question are we answering, what data is in scope (date range, entity count)\n[Query] KPI tile: headline numbers (e.g., # big_value, or # dashboard with nested # big_value views)\n[Text] ## Trend: describe what we should look for over time\n[Query] Time-series tile (e.g., # line_chart on a date dimension)\n[Text] ## Breakdown: where the signal is\n[Query] Categorical tile (e.g., # bar_chart on a categorical dimension)\n[Text] ## Key takeaways: what the user should walk away with\n```\n\nUse this as a default; deviate when the analysis warrants. A grounded report names the time range and entity count up front so every number that follows has context.\n\n## Choosing chart types and annotations\n\nRead `skill:malloy-charts` before picking visualizations: it owns chart-type selection, properties, and the placement rules for chart annotations. `skill:malloy-queries` covers Malloy query patterns and the critical placement rules for chart-annotation tags.\n\nWhen in doubt:\n\n- KPIs / single numbers -> `# big_value`, often nested inside `# dashboard`.\n- Trend over time -> `# line_chart`, usually on the primary date dimension.\n- Category comparisons -> `# bar_chart`, ordered by the metric.\n- Tabular data with many columns -> a plain table tile with `# table.size=fill`.\n- Multiple coordinated charts -> `# dashboard` with `nest:` blocks.\n\nAnnotations go **directly above** the tile's `view:`, never inside its curly braces:\n\n```malloy\n# bar_chart\nview: top_categories is {\n group_by: category\n aggregate: revenue\n order_by: revenue desc\n limit: 10\n}\n```\n\nA `# dashboard` tile composes nested views, useful for KPIs alongside a trend in a single tile. Each `nest:` is a tile; any top-level `aggregate:` measures render as KPI cards. For a fixed grid, use `# dashboard { columns=N }` with `# colspan` on each tile (see `skill:malloy-charts`):\n\n```malloy\n# dashboard { columns=2 }\nview: summary is {\n nest:\n # colspan=2\n # big_value\n kpis is {\n aggregate:\n # label=\"Revenue\"\n # currency\n total_revenue\n\n # label=\"Orders\"\n # number=auto\n order_count\n }\n nest:\n # line_chart\n trend is {\n group_by: order_date.month\n aggregate: total_revenue\n order_by: 1\n }\n}\n```\n\nKey rendering rules to keep in mind when shaping a tile:\n\n- FIRST `group_by` = x-axis, FIRST `aggregate` = y-axis.\n- Override field roles with `# x`, `# y`, `# series` on individual fields.\n- For multiple measure series, place `# y` above the `aggregate:` keyword.\n- One aggregate per chart view: use `# dashboard` with nested views for multiple charts.\n- Use `# table.size=fill` for standalone table queries.\n\n## Editing an existing report\n\nFor small targeted changes (fix one view, insert one tile), edit that view or text block in place and add its entry to `tiles=[…]`, rather than recreating the whole report. For structural rewrites (reordering many tiles, changing the narrative arc), rewrite the report file. A tag that sets `kind=notebook` is no longer read, so the file is not a report (`report-kind-removed`): replace it with `layout=linear` and list the tiles. A linear file with no `tiles=[…]`, written as bare `run:` statements, is no longer a report: rewrite it as tiles (`skill:malloy-reports`, `reference/linear.md`).\n\n## IMPORTANT\n\nYou CANNOT see the rendered output of report tiles. Do not claim to see charts, values, or patterns from report tiles you haven't explicitly executed via `execute_query`. If you need to analyze results, run the query via `execute_query` first."
|
|
202343
202628
|
},
|
|
202344
202629
|
{
|
|
202345
202630
|
name: "malloy-charts",
|
|
@@ -206133,7 +206418,7 @@ If you did not start the server (someone handed you a running one), **probe befo
|
|
|
206133
206418
|
}
|
|
206134
206419
|
\`\`\`
|
|
206135
206420
|
|
|
206136
|
-
A local package uses a filesystem \`location\` (\`"./<pkg>"\`, relative to the directory holding \`publisher.config.json\`); a remote one uses a GitHub \`tree\` URL. If one model in the package fails to compile, the **whole package** fails to load, so a stray notebook/model error blanks every tile. (Common one: a
|
|
206421
|
+
A local package uses a filesystem \`location\` (\`"./<pkg>"\`, relative to the directory holding \`publisher.config.json\`); a remote one uses a GitHub \`tree\` URL. If one model in the package fails to compile, the **whole package** fails to load, so a stray notebook/model error blanks every tile. (Common one: a report that imports \`x.malloy\` more than once compiles as one batch, so the repeated import errors \`Cannot redefine 'x'\`. Import once, at the top.)
|
|
206137
206422
|
|
|
206138
206423
|
### Publishing
|
|
206139
206424
|
|
|
@@ -208276,7 +208561,7 @@ Present coverage in this order:
|
|
|
208276
208561
|
{
|
|
208277
208562
|
name: "malloy-materialization",
|
|
208278
208563
|
description: "Add, confirm and debug Malloy Persistence materializations in a package - persist an expensive source so queries read a pre-built table, in the source's own warehouse or in a storage destination. Read this whenever the user wants to materialize a source, add a persist annotation, speed up a slow source, build one stored rollup over another, tune what to persist, or asks why a persist source isn't building or isn't being read.",
|
|
208279
|
-
body: "# Materialization (Malloy Persistence)\n\nMaterialize an expensive source once so queries read a **pre-built table** instead of recomputing it every time. You tag a source `#@ persist`, a materialization run builds it into a physical table, and queries against it are rewritten to read that table.\n\n> **The #1 gotcha, up front:** if a persist source isn't materializing, it is almost always one of four things - no build ever ran (a standalone Publisher does not build on publish - see **Building and refreshing**), a build ran and failed or lost that one source (a run can finish ready with `failures`; read them), the model declaring the source has no `##! experimental.persistence` flag and nothing flagged imports it (it is skipped without a warning), or the package was reloaded since the build (a reload drops the bindings until the next run). Jump to **Debugging a no-op build**.\n\nThis file is the core. The details live beside it, one topic per file, and each is a prompt of its own:\n\n- `reference/annotation.md` - the `#@ persist` tag: what can carry it, the name rules, identity and reuse, readers of a persisted source, and every option with where it is explained.\n- `reference/policy.md` - the `publisher.json` block: `scope`, `queryMetadata`, and where the rules are enforced.\n- `reference/storage.md` - building into a **storage destination** (`storage=`), where a given may sit, which sources that tier refuses, and how a stored table is served.\n- `reference/chaining.md` - one stored source built **over another stored source**: what makes it build over the parent's table, why one that cannot is refused rather than recomputed from the warehouse, and how to read what happened.\n- `reference/refresh.md` - keeping a table current: `freshness`, `schedule`, and `refresh=\"incremental\"`.\n- `reference/access-filter.md` - persisting a `#(access_filter)`-gated source, and the bound on a stale access decision.\n- `reference/tuning.md` - reading the materialization history to decide what to persist, stop persisting, or reschedule (recommendations only).\n\n## v1 or v2: which spelling to write\n\nPublisher has two spellings. **v1** is `#@ persist` on a source and `#@ preaggregate` on a measure, and every server reads it. **v2** is `#(materialize)` on a source and `#(rollup)` on a measure, on by default behind the server switch `PUBLISHER_MATERIALIZE` (`false` turns it off; the switch is removed one release after the default ships). Since the v1 cutover both are served the same way: a stored table by the served copy (the author's own files with each stored source re-rooted on its table), a rollup by the rollup leg, so a query reads a table only when the path report says so. Everything else in this skill describes v1 unless it says otherwise.\n\n**Pick by what the server runs, then by where the table goes:**\n\n| The server | A table in a storage destination | A table in the source's own warehouse | A rollup on a measure |\n|---|---|---|---|\n| `PUBLISHER_MATERIALIZE` on (the default) | `#(materialize) storage=\"lake\"` (needs `PERSIST_STORAGE_MODE=on` too) | `#(materialize)`, or `#(materialize) name=\"schema.table\"` to name and place it | `#(rollup) grain=[\"a\", \"b\"]` |\n| switch off (`PUBLISHER_MATERIALIZE=false`) | `#@ persist name=\"...\" storage=\"lake\"` | `#@ persist name=\"...\"` | `#@ preaggregate grain=\"a, b\"` |\n\nSo for new work, write v2 where the server has the switch on, and v1 where it is off. A source with a row-level gate (`#(authorize)`, `#(access_filter)`) of its own is built and served past that gate on either tier, database or `storage=`, `#(materialize)` or `#@ persist`, with `PUBLISHER_MATERIALIZE_GATED_SOURCES` off: the table holds every caller's rows and the gate is re-applied on every read. A `storage=` table puts those rows, ungated, in the destination, where anyone with direct access to it can read them; say so when you materialize a gated source there. A row filter it inherits, a gate reached through a join, or a gate over a source whose build reads a given is refused on both tiers. Ask whoever runs the server if you cannot tell; the startup log lists `materialize.enabled=true from PUBLISHER_MATERIALIZE` when it is on. **With the switch off, `#(materialize)` is ignored with no warning at all** (no build, no serve verdict, answered live), and `#(rollup)` is only an `annotation-near-miss` warning, so a v2 annotation on a v1 server looks exactly like a build that never ran.\n\n```malloy\n// v2, switch on: no ##! experimental.persistence needed in this file\n#(materialize) name=\"east_orders\" storage=\"lake\"\nsource: east_orders is orders_base extend {\n where: region = 'east'\n measure: order_count is count()\n}\n\nsource: sales is orders_base extend {\n #(rollup) grain=[\"category\"]\n #(rollup) grain=[\"category\", \"region\"]\n measure: revenue is amount.sum()\n}\n```\n\nWhat is different about v2, briefly:\n\n- **It stores the source as written** - every dimension (computed, private and internal ones too) with its `where:` applied, not a query's output - so a plain `extend` over a table is fine and needs no `-> { select: * }`. Keys are closed: `name`, `storage`, `refresh`, `watermark`, `merge_key`, `lookback`, `freshness.*`, `queryMetadata.*`, `inline`. Any other key fails the publish and the load (`materialize-unknown-key`; the retired `partition=` is `materialize-retired-key`).\n- **The base must not declare measures, views or joins**, unless the base is materialized too. A `#(materialize)` source that inherits one is built but never read: `served-copy-not-served` (\"This source inherits fields ...\"), serve verdict `live` / `served_copy`, every query live. Build over a base with none (as above), or keep the query shape (`orders -> { select: * } extend { ... }`) and declare the measures after it.\n- **Joins are references by default.** `inline=[\"j\"]` stores a join_one as `j__<field>` columns, or a join_many as a pair table; an incremental pair table names a watermark on each side, `watermark=[\"updated_at\", \"j.updated_at\"]`.\n- **`#@ persist` on a view and `#@ -persist` on a reader are the same in both.** A persisted view is built only with the switch on, and so is `#@ persist` on a named `query:` (`reference/annotation.md`). Off, either is answered live, its line is still read (an invalid one fails the load), and a valid one warns `persist-view-not-built` or `persist-query-not-built`. `#@ preaggregate` is deprecated (a `deprecated-preaggregate-annotation` warning with the switch on; it still builds). So is `#(preaggregate)`, `#(rollup)`'s former name: it is read the same for one release, with the same warning, and a measure that carries both fails the load (`rollup-invalid`). Write `#(rollup)`.\n- **Confirm it the v2 way.** The package's serve verdicts (`GET .../packages/{pkg}/status`, `serveVerdicts`) read `serves`; a query's path report reads `servedBy.kind: \"materialized\"` with `via: \"served_copy\"` (a rollup: `kind: \"rollup\"`; a persisted view: `kind: \"view\"`; a persisted named query: `kind: \"query\"`). `manifestBindingStatus` does not cover v2 tables.\n\n**Existing v1 code is not wrong**, and moving it is optional. When asked to move it, follow `docs/materialization-migration.md` in the Publisher repository: one v1 spelling at a time, a dry-run publish (`POST .../packages?dryRun=true`) to read the warnings and serve verdicts, a build (every migrated source rebuilds once, because its content address moves), then the path report and a served-versus-live comparison against an opted-out reader (`#@ -persist source: x_live is x extend {}`, declared in a model file, not in the query text). Keep the v1 source's `name=` when you move it: an unversioned or `scope: \"package\"` package's table stays at that name (the package's own runs wrote it). Without `name=`, a v2 table takes a readable name, `<package>__<file>__<source>__p<hash>`, and on BigQuery a database table then is not built: a `#(materialize)` or `#@ persist` source with no dataset-qualified `name=`, or a rollup whose `name=` (or its base's) gives no dataset, is refused at plan (reason `needs_qualified_name`) and serves live, so give it a dataset-qualified `name=`. Under `scope: \"version\"` a `name=` sets the start of the table's name, schema or dataset included, and the version and a hash follow it (`analytics.summary_t__v1_2_0__p<hash>`), and no view is ever made at `name=`.\n\n## The recipe (get this right and it just works)\n\n1. **`##! experimental.persistence` on every `.malloy` file that declares a `#@ persist` source** (a file whose only materializations are v2 `#(materialize)` needs none). Either form enables it:\n - `##! experimental.persistence`, or\n - `##! experimental { access_modifiers, sql_functions, persistence }` (add `persistence` to the existing list).\n\n **Why it matters:** the build plan walks only the models that carry the flag, and skips every other file **without a warning**. The flag is a property of the model being *walked*, not of the file that declares the annotation: a flagged model builds every persist source its walk reaches, including ones declared in a flagless file it imports, and a flagless file's persist sources build only when some flagged model imports it. So a `#@ persist` in a flagless file that nothing flagged imports is silently never built, while adding a flagged entry model that imports it starts building tables that were inert - neither state warns. Put the flag in the declaring file itself: that is the one placement whose effect does not depend on what else imports it. A file with no persist source of its own does not need the flag; adding it anyway is harmless. (`#@ preaggregate` rollups are the one exception: they build from an unflagged file, because they live in a model Publisher synthesizes.)\n\n2. **`#@ persist name=\"...\"` on a query-based source, with the name quoted:**\n ```malloy\n #@ persist name=\"my_dataset.my_table\"\n source: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n ```\n - **Only `query_source` and `sql_select` sources are persistable** - a `-> { ... }` pipeline or a `conn.sql(\"...\")`, including one refined by a trailing `extend { ... }`. A `#@ persist` on a *plain* `extend` over a bare `conn.table(...)` is **refused, not ignored**: the package warns, and every run that covers it fails naming the source, so a whole-package run builds nothing until you fix it. Persist a query source instead (`source: x is raw -> { where: ...; select: * }`).\n - **Quote the name, once.** A bare `name=my_table` fails the package load with `persist annotation name must be quoted`; a name quoted *inside* the quotes (`name=\"\\\"My Table\\\"\"`) also fails the load, as not a plain identifier path. Publisher quotes each segment itself, so mixed case and reserved words need no extra quoting. The target's container must already exist and be writable by the connection.\n - **The name is not the identity.** A persist source is identified by a content address of its connection and SQL, so a rebuild with unchanged logic reuses the table and two sources with the same body share one. An `extend` of a persisted source reads the same table and is not a second build target.\n - **A `name=` is one table on its schema, whichever package asks.** Publisher's own builds give a table with no `name=` a readable name, `<package>__<file>__<source>__p<8 hex>` (`ecommerce__orders__orders__p3f9c2a1b`), the hex a hash of the environment, package, model and source, so packages sharing a schema never collide. A `name=` is used as written and marked as its package's; if another package already holds it, that source's build is refused (`table-owned-elsewhere` in the run's failures) and it answers live. Give it a different `name=`.\n\n The name rules, bound arguments, `#@ -persist`, and every option (`storage=`, `refresh=`, `freshness.*`, `queryMetadata.*`) are in `reference/annotation.md`.\n\n3. **Package persistence policy in `publisher.json`** (all optional):\n ```jsonc\n {\n \"name\": \"my-package\",\n \"queryMetadata\": { \"team\": \"finance\" }, // root level: tags every statement a build OR a query issues\n \"materialization\": {\n \"scope\": \"package\", // default; \"version\" = each published version owns its own tables\n \"freshness\": { \"window\": \"24h\", \"fallback\": \"live\" }\n }\n }\n ```\n - **`scope`** is a package-level contract about sharing tables across versions; on a standalone server it changes nothing except gating `schedule`. Its deprecated root-level home still works, but the two homes disagreeing **fails the load**.\n - **`freshness`** bounds how old a served table may be, the same way on every mechanism (rollups included) and in both deployments: a standalone run stamps the window on the tables it builds and rebuilds one past it on its next run; a **hosted control plane** stamps its own manifest and schedules refreshes to meet it. `fail` behaves like `live` today; only `stale_ok` keeps serving a stale table.\n - **`queryMetadata`** tags every build statement and every query for the backend's cost attribution. Root level; the home inside `materialization` is deprecated. Observability only.\n - **`schedule`** is a 5-field UTC cron that **requires `scope: \"version\"`** and **excludes `freshness`**; it fires only on a standalone server whose scheduler is enabled.\n\n The coherence rules are rejected at publish and at a policy edit, warned at load, and skipped by the scheduler. `reference/policy.md` has `scope` and `queryMetadata` in full; `reference/refresh.md` has `freshness` and `schedule`.\n\n## Building and refreshing (standalone vs. hosted)\n\nA `#@ persist` tag declares *what* to materialize; it does not by itself build anything.\n\n- **Standalone Publisher:** publishing or loading a package only computes its build plan - **no table is built until a materialization run executes.** Trigger one explicitly (`malloy-pub materialize --environment <env> --package <pkg> --wait`, or the materialization API), or turn on the opt-in local scheduler (off unless `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` is set) to fire the package's `schedule` cron. Refresh is a re-run or that cron; `freshness` is not a refresh trigger here, so a freshness-only standalone package builds once and is not auto-refreshed. Two flags to know: `--force-refresh` builds every source even when its content address is unchanged (which is what every scheduler fire does), and `--reseed` is the only thing that rebuilds an incremental source from scratch. `--wait` gives up after **120 s by default** (`--timeout <s>`) and exits non-zero while the build keeps running; `malloy-pub get materialization <id>` then shows where it got to.\n- **Hosted (control-plane) deployment:** the build runs automatically on publish, best-effort - a build failure does **not** fail the publish (which is why a broken persist can look like a silent no-op), and the control plane drives refresh to meet the `freshness` objective.\n\nTwo mechanics either way. **One build at a time per package**: a second run requested while one is active is rejected with a 409 conflict rather than queued, and the scheduler skips a fire while a run is active. **A build can be partial**: `sourceNames` on the request builds only the sources it names and leaves the others exactly as they were (live if never built), which is how to add one source to a package without rebuilding the rest.\n\nEither way, a successful publish alone does not prove a table exists - confirm the build separately.\n\n## Confirming it worked\n\nA green run is not proof, and neither is a fast query (on small data a live recompute is fast too). Check what the server says it serves:\n\n1. **The run lists your source, and did not lose it.** A run's detail (`malloy-pub get materialization <id> --environment <env> --package <pkg>`) carries `manifest.entries`, a map keyed by `sourceEntityId` whose values name each built or reused source (`sourceName`) and its physical table. A run can finish `MANIFEST_FILE_READY` having built nothing (every source skipped for a missing flag, or carried forward unchanged) **or having lost a source**: a source that failed is absent from `entries` and present in `manifest.failures` with its error, and a source the eligibility gate refused is in `metadata.refusedSources`, while the run still reads ready. `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed` / `sourcesRefused` are the counts. For a source built over another stored source, the entry's `upstreamReuse` says whether it read the parent's table (`reused`) or recomputed it (`recomputed`, with `upstreamRecomputeReason`) - see `reference/chaining.md`.\n2. **The package is bound to those tables.** On a standalone Publisher the package's serving state, `GET /api/v0/environments/{env}/packages/{pkg}/status`, reports `manifestBindingStatus` and `manifestEntryCount` (an older server: its entry in `GET /api/v0/status`, or the package's details). The count covers tables built in the source's own warehouse only: it reads `bound` with a nonzero count when such a table is bound and `unbound` otherwise. A `storage=` table never counts there - it appears under the package's `storageServeBindings`, so a package whose only persist sources are `storage=` reads `unbound` while serving from the store. `live_fallback` is a hosted-only status: a configured `manifestLocation` could not be fetched or bound, and the previously bound manifest (if any) stays in force.\n3. **The query names the table.** A query's full result (the REST query response without `compactJson`) carries the SQL it ran. Served from the table, its `FROM` names the physical table; computed live, it carries the source's own SQL instead. This is the per-query proof.\n4. **A reload unbinds them.** Reloading the package - including the automatic reload when a watched file is saved - drops the binding, and queries compute live until the next materialization run, which reuses unchanged tables and binds them again. (A server *restart* re-establishes the bindings from its store; a reload does not.) After editing a model, run a build before you trust a timing.\n\nA query response's `servedFrom` field names the tier that answered: `database` for a table built in the source's own connection, `storage` for a `storage=` table, `live_fallback` when a `storage=` read failed and live answered, and empty when no table answered. The path report's `servedBy.tier` names the same tier.\n\n## Debugging a no-op build\n\nSymptom: no table was built and the source still recomputes on every query. Check, in order:\n\n0. **Did a build actually run?** On a standalone Publisher, publish/load does **not** build - run `malloy-pub materialize` (or enable the scheduler). \"Publishes fine, no table\" is the *expected* standalone state, not a model bug. On a hosted deployment the build is automatic but best-effort, so a failure is silent - look for a `FAILED` run, and for a ready run with `failures`.\n1. **Did the run fail, or lose this source?** A `FAILED` run's `error` names what stopped it. A ready run's `manifest.failures` names each source that did not build, and `metadata.refusedSources` each one the gate refused, with the reason to act on. The package flags some of these before any run: an unbuildable persist source appears in its warnings, and `GET …/packages/{pkg}/build-plan` lists the sources a run will build, the ones it will refuse, and under `omittedSources` any the planner itself failed on (a code per source, or under `omittedFiles` a file whose sources it could not name; the server log has the error). A `#@ persist` on a non-persistable source fails every run that covers it, naming the source.\n2. **The declaring model is missing the persistence flag** and nothing flagged imports it: skipped without any warning, the run succeeds, the source is simply absent from what was built. Add the flag to the declaring file.\n3. **An unquoted persist name** - a bare `name=foo` **always** stops the load with `persist annotation name must be quoted`. (If you got *no* error at all, it isn't this.)\n4. **The package was reloaded** after the build (a saved file under watch mode counts). The tables exist and the run reads ready; the binding is gone. Run a build. And if a watched edit failed to compile, the server keeps serving the **old** model and its binding, and records the error under `staleCompileErrors` on `/status` - so \"still bound\" after an edit can mean the edit never took.\n5. **A `storage=` source serves live while the store is switched off.** With `PERSIST_STORAGE_MODE=off` a `storage=` source is skipped by the build and served live, with no error; it is never built into the warehouse instead. See `reference/storage.md`.\n\n**Isolation test** - add a trivial, self-contained persist source in its own file and rebuild:\n```malloy\n##! experimental.persistence\nsource: smoke_raw is my_conn.table('some_dataset.some_table')\n#@ persist name=\"scratch_dataset.persist_smoke_test\"\nsource: persist_smoke is smoke_raw -> { aggregate: n is count() }\n```\nIf **even this** doesn't build after a real run, the problem is package-wide: read the run's error (a non-persistable source anywhere fails the whole run and names it), then check that the connection can write the target dataset. If the smoke source builds and your real one doesn't, your real source is the problem: its file's flag, or its entry in `failures` / `refusedSources`. Delete the smoke file, delete its run (`malloy-pub delete materialization <id>`, record-only), and drop its table (`DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}`, which refuses a table still in use).\n\n## Gotchas\n\n- **Flag every file that declares a persist source** - a flagless model nothing flagged imports is skipped without a warning.\n- **A `#@ persist` on a plain `extend` over `conn.table(...)` fails the run** - every run that covers it, naming the source.\n- **A tag doesn't build** - only an explicit run, the standalone scheduler, or a hosted control plane does.\n- **Quote the name, once** - bare stops the load, and so does a name with quotes inside it; Publisher quotes each segment for you.\n- **A ready run can still have lost a source** - read `manifest.failures` and `metadata.refusedSources`.\n- **A reload unbinds; a restart rebinds** - run a build before trusting a timing.\n- **Reuse is by content address, not by name** - `--force-refresh` and every scheduler fire defeat it.\n- **Removing a persist source does not drop its table** - and neither does `delete materialization`, which is record-only. Drop the table once no remaining ready run, of any version (list runs per version with `versionId`), names a table with that name in any place: `DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}` checks that itself and answers 409 `TABLE_IN_USE` otherwise; serving reverts to live in place.\n- **A given inside the persisted query is refused; in the source's own `extend` block it is applied per caller; inherited from a base it is refused and the source answers live** - `reference/storage.md`.\n- **A join to a non-persisted source, or a nested column, serves live for the queries that touch it** - the source's own fields still serve from the table.\n- **A `#(access_filter)`-gated source freezes its gating column when persisted** - `#@ preaggregate` refuses it outright; a `storage=` table holds every caller's rows, ungated, in the destination; `reference/access-filter.md`.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-materialization/<name>` instead.\n\nAvailable: access-filter, annotation, chaining, policy, refresh, storage, tuning."
|
|
208564
|
+
body: "# Materialization (Malloy Persistence)\n\nMaterialize an expensive source once so queries read a **pre-built table** instead of recomputing it every time. You tag a source `#@ persist`, a materialization run builds it into a physical table, and queries against it are rewritten to read that table.\n\n> **The #1 gotcha, up front:** if a persist source isn't materializing, it is almost always one of four things - no build ever ran (a standalone Publisher does not build on publish - see **Building and refreshing**), a build ran and failed or lost that one source (a run can finish ready with `failures`; read them), the model declaring the source has no `##! experimental.persistence` flag and nothing flagged imports it (it is skipped without a warning), or the package was reloaded since the build (a reload drops the bindings until the next run). Jump to **Debugging a no-op build**.\n\nThis file is the core. The details live beside it, one topic per file, and each is a prompt of its own:\n\n- `reference/annotation.md` - the `#@ persist` tag: what can carry it, the name rules, identity and reuse, readers of a persisted source, and every option with where it is explained.\n- `reference/policy.md` - the `publisher.json` block: `scope`, `queryMetadata`, and where the rules are enforced.\n- `reference/storage.md` - building into a **storage destination** (`storage=`), where a given may sit, which sources that tier refuses, and how a stored table is served.\n- `reference/chaining.md` - one stored source built **over another stored source**: what makes it build over the parent's table, why one that cannot is refused rather than recomputed from the warehouse, and how to read what happened.\n- `reference/refresh.md` - keeping a table current: `freshness`, `schedule`, and `refresh=\"incremental\"`.\n- `reference/access-filter.md` - persisting a `#(access_filter)`-gated source, and the bound on a stale access decision.\n- `reference/tuning.md` - reading the materialization history to decide what to persist, stop persisting, or reschedule (recommendations only).\n\n## v1 or v2: which spelling to write\n\nPublisher has two spellings. **v1** is `#@ persist` on a source and `#@ preaggregate` on a measure, and every server reads it. **v2** is `#(materialize)` on a source and `#(rollup)` on a measure, on by default behind the server switch `PUBLISHER_MATERIALIZE` (`false` turns it off; the switch is removed one release after the default ships). Since the v1 cutover both are served the same way: a stored table by the served copy (the author's own files with each stored source re-rooted on its table), a rollup by the rollup leg, so a query reads a table only when the path report says so. Everything else in this skill describes v1 unless it says otherwise.\n\n**Pick by what the server runs, then by where the table goes:**\n\n| The server | A table in a storage destination | A table in the source's own warehouse | A rollup on a measure |\n|---|---|---|---|\n| `PUBLISHER_MATERIALIZE` on (the default) | `#(materialize) storage=\"lake\"` (needs `PERSIST_STORAGE_MODE=on` too) | `#(materialize)`, or `#(materialize) name=\"schema.table\"` to name and place it | `#(rollup) grain=[\"a\", \"b\"]` |\n| switch off (`PUBLISHER_MATERIALIZE=false`) | `#@ persist name=\"...\" storage=\"lake\"` | `#@ persist name=\"...\"` | `#@ preaggregate grain=\"a, b\"` |\n\nSo for new work, write v2 where the server has the switch on, and v1 where it is off. A source with a row-level gate (`#(authorize)`, `#(access_filter)`) of its own is built and served past that gate on either tier, database or `storage=`, `#(materialize)` or `#@ persist`, with `PUBLISHER_MATERIALIZE_GATED_SOURCES` off: the table holds every caller's rows and the gate is re-applied on every read. A `storage=` table puts those rows, ungated, in the destination, where anyone with direct access to it can read them; say so when you materialize a gated source there. A row filter it inherits, a gate reached through a join, or a gate over a source whose build reads a given is refused on both tiers. Ask whoever runs the server if you cannot tell; the startup log lists `materialize.enabled=true from PUBLISHER_MATERIALIZE` when it is on. **With the switch off, `#(materialize)` is ignored with no warning at all** (no build, no serve verdict, answered live), and `#(rollup)` is only an `annotation-near-miss` warning, so a v2 annotation on a v1 server looks exactly like a build that never ran.\n\n```malloy\n// v2, switch on: no ##! experimental.persistence needed in this file\n#(materialize) name=\"east_orders\" storage=\"lake\"\nsource: east_orders is orders_base extend {\n where: region = 'east'\n measure: order_count is count()\n}\n\nsource: sales is orders_base extend {\n #(rollup) grain=[\"category\"]\n #(rollup) grain=[\"category\", \"region\"]\n measure: revenue is amount.sum()\n}\n```\n\nWhat is different about v2, briefly:\n\n- **It stores the source as written** - every dimension (computed, private and internal ones too) with its `where:` applied, not a query's output - so a plain `extend` over a table is fine and needs no `-> { select: * }`. Keys are closed: `name`, `storage`, `refresh`, `watermark`, `merge_key`, `lookback`, `freshness.*`, `queryMetadata.*`, `inline`. Any other key fails the publish and the load (`materialize-unknown-key`; the retired `partition=` is `materialize-retired-key`).\n- **A base's measures, views and joins are carried** when the base is named by its own name, in the source's file or a file it imports whole: the served copy writes the base's `extend` block again over the table, and every file that imports the source reads the table. It cannot when the base comes in under another name or by a selective import (`import { o is orders } from ...`), or its block reads a name its own file imports (a join to an imported source): then the source is built but answered live, `served-copy-not-served` (\"This source inherits fields ...\"), serve verdict `live` / `served_copy`. Import the base's file whole, build over a base with none (as above), or keep the query shape (`orders -> { select: * } extend { ... }`) and declare the measures after it.\n- **Joins are references by default.** `inline=[\"j\"]` stores a join_one as `j__<field>` columns, or a join_many as a pair table; an incremental pair table names a watermark on each side, `watermark=[\"updated_at\", \"j.updated_at\"]`.\n- **`#@ persist` on a view and `#@ -persist` on a reader are the same in both.** A persisted view is built only with the switch on, and so is `#@ persist` on a named `query:` (`reference/annotation.md`). Off, either is answered live, its line is still read (an invalid one fails the load), and a valid one warns `persist-view-not-built` or `persist-query-not-built`. `#@ preaggregate` is deprecated (a `deprecated-preaggregate-annotation` warning with the switch on; it still builds). So is `#(preaggregate)`, `#(rollup)`'s former name: it is read the same for one release, with the same warning, and a measure that carries both fails the load (`rollup-invalid`). Write `#(rollup)`.\n- **Confirm it the v2 way.** The package's serve verdicts (`GET .../packages/{pkg}/status`, `serveVerdicts`) read `serves`; a query's path report reads `servedBy.kind: \"materialized\"` with `via: \"served_copy\"` (a rollup: `kind: \"rollup\"`; a persisted view: `kind: \"view\"`; a persisted named query: `kind: \"query\"`). `manifestBindingStatus` does not cover v2 tables.\n\n**Existing v1 code is not wrong**, and moving it is optional. When asked to move it, follow `docs/materialization-migration.md` in the Publisher repository: one v1 spelling at a time, a dry-run publish (`POST .../packages?dryRun=true`) to read the warnings and serve verdicts, a build (every migrated source rebuilds once, because its content address moves), then the path report and a served-versus-live comparison against an opted-out reader (`#@ -persist source: x_live is x extend {}`, declared in a model file, not in the query text). Keep the v1 source's `name=` when you move it: an unversioned or `scope: \"package\"` package's table stays at that name (the package's own runs wrote it). Without `name=`, a v2 table takes a readable name, `<package>__<file>__<source>__p<hash>`, and on BigQuery a database table then is not built: a `#(materialize)` or `#@ persist` source with no dataset-qualified `name=`, or a rollup whose `name=` (or its base's) gives no dataset, is refused at plan (reason `needs_qualified_name`) and serves live, so give it a dataset-qualified `name=`. Under `scope: \"version\"` a `name=` sets the start of the table's name, schema or dataset included, and the version and a hash follow it (`analytics.summary_t__v1_2_0__p<hash>`), and no view is ever made at `name=`.\n\n## The recipe (get this right and it just works)\n\n1. **`##! experimental.persistence` on every `.malloy` file that declares a `#@ persist` source** (a file whose only materializations are v2 `#(materialize)` needs none). Either form enables it:\n - `##! experimental.persistence`, or\n - `##! experimental { access_modifiers, sql_functions, persistence }` (add `persistence` to the existing list).\n\n **Why it matters:** the build plan walks only the models that carry the flag, and skips every other file **without a warning**. The flag is a property of the model being *walked*, not of the file that declares the annotation: a flagged model builds every persist source its walk reaches, including ones declared in a flagless file it imports, and a flagless file's persist sources build only when some flagged model imports it. So a `#@ persist` in a flagless file that nothing flagged imports is silently never built, while adding a flagged entry model that imports it starts building tables that were inert - neither state warns. Put the flag in the declaring file itself: that is the one placement whose effect does not depend on what else imports it. A file with no persist source of its own does not need the flag; adding it anyway is harmless. (`#@ preaggregate` rollups are the one exception: they build from an unflagged file, because they live in a model Publisher synthesizes.)\n\n2. **`#@ persist name=\"...\"` on a query-based source, with the name quoted:**\n ```malloy\n #@ persist name=\"my_dataset.my_table\"\n source: my_rollup is some_source -> { group_by: ...; aggregate: ... }\n ```\n - **Only `query_source` and `sql_select` sources are persistable** - a `-> { ... }` pipeline or a `conn.sql(\"...\")`, including one refined by a trailing `extend { ... }`. A `#@ persist` on a *plain* `extend` over a bare `conn.table(...)` is **refused, not ignored**: the package warns, and every run that covers it fails naming the source, so a whole-package run builds nothing until you fix it. Persist a query source instead (`source: x is raw -> { where: ...; select: * }`).\n - **Quote the name, once.** A bare `name=my_table` fails the package load with `persist annotation name must be quoted`; a name quoted *inside* the quotes (`name=\"\\\"My Table\\\"\"`) also fails the load, as not a plain identifier path. Publisher quotes each segment itself, so mixed case and reserved words need no extra quoting. The target's container must already exist and be writable by the connection.\n - **The name is not the identity.** A persist source is identified by a content address of its connection and SQL, so a rebuild with unchanged logic reuses the table and two sources with the same body share one. An `extend` of a persisted source reads the same table and is not a second build target.\n - **A `name=` is one table on its schema, whichever package asks.** Publisher's own builds give a table with no `name=` a readable name, `<package>__<file>__<source>__p<8 hex>` (`ecommerce__orders__orders__p3f9c2a1b`), the hex a hash of the environment, package, model and source, so packages sharing a schema never collide. A `name=` is used as written and marked as its package's; if another package already holds it, that source's build is refused (`table-owned-elsewhere` in the run's failures) and it answers live. Give it a different `name=`.\n\n The name rules, bound arguments, `#@ -persist`, and every option (`storage=`, `refresh=`, `freshness.*`, `queryMetadata.*`) are in `reference/annotation.md`.\n\n3. **Package persistence policy in `publisher.json`** (all optional):\n ```jsonc\n {\n \"name\": \"my-package\",\n \"queryMetadata\": { \"team\": \"finance\" }, // root level: tags every statement a build OR a query issues\n \"materialization\": {\n \"scope\": \"package\", // default; \"version\" = each published version owns its own tables\n \"freshness\": { \"window\": \"24h\", \"fallback\": \"live\" }\n }\n }\n ```\n - **`scope`** is a package-level contract about sharing tables across versions; on a standalone server it changes nothing except gating `schedule`. Its deprecated root-level home still works, but the two homes disagreeing **fails the load**.\n - **`freshness`** bounds how old a served table may be, the same way on every mechanism (rollups included) and in both deployments: a standalone run stamps the window on the tables it builds and rebuilds one past it on its next run; a **hosted control plane** stamps its own manifest and schedules refreshes to meet it. `fail` behaves like `live` today; only `stale_ok` keeps serving a stale table.\n - **`queryMetadata`** tags every build statement and every query for the backend's cost attribution. Root level; the home inside `materialization` is deprecated. Observability only.\n - **`schedule`** is a 5-field UTC cron that **requires `scope: \"version\"`** and **excludes `freshness`**; it fires only on a standalone server whose scheduler is enabled.\n\n The coherence rules are rejected at publish and at a policy edit, warned at load, and skipped by the scheduler. `reference/policy.md` has `scope` and `queryMetadata` in full; `reference/refresh.md` has `freshness` and `schedule`.\n\n## Building and refreshing (standalone vs. hosted)\n\nA `#@ persist` tag declares *what* to materialize; it does not by itself build anything.\n\n- **Standalone Publisher:** publishing or loading a package only computes its build plan - **no table is built until a materialization run executes.** Trigger one explicitly (`malloy-pub materialize --environment <env> --package <pkg> --wait`, or the materialization API), or turn on the opt-in local scheduler (off unless `PUBLISHER_LOCAL_MATERIALIZATION_SCHEDULER` is set) to fire the package's `schedule` cron. Refresh is a re-run or that cron; `freshness` is not a refresh trigger here, so a freshness-only standalone package builds once and is not auto-refreshed. Two flags to know: `--force-refresh` builds every source even when its content address is unchanged (which is what every scheduler fire does), and `--reseed` is the only thing that rebuilds an incremental source from scratch. `--wait` gives up after **120 s by default** (`--timeout <s>`) and exits non-zero while the build keeps running; `malloy-pub get materialization <id>` then shows where it got to.\n- **Hosted (control-plane) deployment:** the build runs automatically on publish, best-effort - a build failure does **not** fail the publish (which is why a broken persist can look like a silent no-op), and the control plane drives refresh to meet the `freshness` objective.\n\nTwo mechanics either way. **One build at a time per package**: a second run requested while one is active is rejected with a 409 conflict rather than queued, and the scheduler skips a fire while a run is active. **A build can be partial**: `sourceNames` on the request builds only the sources it names and leaves the others exactly as they were (live if never built), which is how to add one source to a package without rebuilding the rest.\n\nEither way, a successful publish alone does not prove a table exists - confirm the build separately.\n\n## Confirming it worked\n\nA green run is not proof, and neither is a fast query (on small data a live recompute is fast too). Check what the server says it serves:\n\n1. **The run lists your source, and did not lose it.** A run's detail (`malloy-pub get materialization <id> --environment <env> --package <pkg>`) carries `manifest.entries`, a map keyed by `sourceEntityId` whose values name each built or reused source (`sourceName`) and its physical table. A run can finish `MANIFEST_FILE_READY` having built nothing (every source skipped for a missing flag, or carried forward unchanged) **or having lost a source**: a source that failed is absent from `entries` and present in `manifest.failures` with its error, and a source the eligibility gate refused is in `metadata.refusedSources`, while the run still reads ready. `metadata.sourcesBuilt` / `sourcesReused` / `sourcesFailed` / `sourcesRefused` are the counts. For a source built over another stored source, the entry's `upstreamReuse` says whether it read the parent's table (`reused`) or recomputed it (`recomputed`, with `upstreamRecomputeReason`) - see `reference/chaining.md`.\n2. **The package is bound to those tables.** On a standalone Publisher the package's serving state, `GET /api/v0/environments/{env}/packages/{pkg}/status`, reports `manifestBindingStatus` and `manifestEntryCount` (an older server: its entry in `GET /api/v0/status`, or the package's details). The count covers tables built in the source's own warehouse only: it reads `bound` with a nonzero count when such a table is bound and `unbound` otherwise. A `storage=` table never counts there - it appears under the package's `storageServeBindings`, so a package whose only persist sources are `storage=` reads `unbound` while serving from the store. `live_fallback` is a hosted-only status: a configured `manifestLocation` could not be fetched or bound, and the previously bound manifest (if any) stays in force.\n3. **The query names the table.** A query's full result (the REST query response without `compactJson`) carries the SQL it ran. Served from the table, its `FROM` names the physical table; computed live, it carries the source's own SQL instead. This is the per-query proof.\n4. **A reload unbinds them.** Reloading the package - including the automatic reload when a watched file is saved - drops the binding, and queries compute live until the next materialization run, which reuses unchanged tables and binds them again. (A server *restart* re-establishes the bindings from its store; a reload does not.) After editing a model, run a build before you trust a timing.\n\nA query response's `servedFrom` field names the tier that answered: `database` for a table built in the source's own connection, `storage` for a `storage=` table, `live_fallback` when a `storage=` read failed and live answered, and empty when no table answered. The path report's `servedBy.tier` names the same tier.\n\n## Debugging a no-op build\n\nSymptom: no table was built and the source still recomputes on every query. Check, in order:\n\n0. **Did a build actually run?** On a standalone Publisher, publish/load does **not** build - run `malloy-pub materialize` (or enable the scheduler). \"Publishes fine, no table\" is the *expected* standalone state, not a model bug. On a hosted deployment the build is automatic but best-effort, so a failure is silent - look for a `FAILED` run, and for a ready run with `failures`.\n1. **Did the run fail, or lose this source?** A `FAILED` run's `error` names what stopped it. A ready run's `manifest.failures` names each source that did not build, and `metadata.refusedSources` each one the gate refused, with the reason to act on. The package flags some of these before any run: an unbuildable persist source appears in its warnings, and `GET …/packages/{pkg}/build-plan` lists the sources a run will build, the ones it will refuse, and under `omittedSources` any the planner itself failed on (a code per source, or under `omittedFiles` a file whose sources it could not name; the server log has the error). A `#@ persist` on a non-persistable source fails every run that covers it, naming the source.\n2. **The declaring model is missing the persistence flag** and nothing flagged imports it: skipped without any warning, the run succeeds, the source is simply absent from what was built. Add the flag to the declaring file.\n3. **An unquoted persist name** - a bare `name=foo` **always** stops the load with `persist annotation name must be quoted`. (If you got *no* error at all, it isn't this.)\n4. **The package was reloaded** after the build (a saved file under watch mode counts). The tables exist and the run reads ready; the binding is gone. Run a build. And if a watched edit failed to compile, the server keeps serving the **old** model and its binding, and records the error under `staleCompileErrors` on `/status` - so \"still bound\" after an edit can mean the edit never took.\n5. **A `storage=` source serves live while the store is switched off.** With `PERSIST_STORAGE_MODE=off` a `storage=` source is skipped by the build and served live, with no error; it is never built into the warehouse instead. See `reference/storage.md`.\n\n**Isolation test** - add a trivial, self-contained persist source in its own file and rebuild:\n```malloy\n##! experimental.persistence\nsource: smoke_raw is my_conn.table('some_dataset.some_table')\n#@ persist name=\"scratch_dataset.persist_smoke_test\"\nsource: persist_smoke is smoke_raw -> { aggregate: n is count() }\n```\nIf **even this** doesn't build after a real run, the problem is package-wide: read the run's error (a non-persistable source anywhere fails the whole run and names it), then check that the connection can write the target dataset. If the smoke source builds and your real one doesn't, your real source is the problem: its file's flag, or its entry in `failures` / `refusedSources`. Delete the smoke file, delete its run (`malloy-pub delete materialization <id>`, record-only), and drop its table (`DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}`, which refuses a table still in use).\n\n## Gotchas\n\n- **Flag every file that declares a persist source** - a flagless model nothing flagged imports is skipped without a warning.\n- **A `#@ persist` on a plain `extend` over `conn.table(...)` fails the run** - every run that covers it, naming the source.\n- **A tag doesn't build** - only an explicit run, the standalone scheduler, or a hosted control plane does.\n- **Quote the name, once** - bare stops the load, and so does a name with quotes inside it; Publisher quotes each segment for you.\n- **A ready run can still have lost a source** - read `manifest.failures` and `metadata.refusedSources`.\n- **A reload unbinds; a restart rebinds** - run a build before trusting a timing.\n- **Reuse is by content address, not by name** - `--force-refresh` and every scheduler fire defeat it.\n- **Removing a persist source does not drop its table** - and neither does `delete materialization`, which is record-only. Drop the table once no remaining ready run, of any version (list runs per version with `versionId`), names a table with that name in any place: `DELETE …/connections/{connectionName}/materializedTables/{physicalTableName}` checks that itself and answers 409 `TABLE_IN_USE` otherwise; serving reverts to live in place.\n- **A given inside the persisted query is refused; in the source's own `extend` block it is applied per caller; inherited from a base it is refused and the source answers live** - `reference/storage.md`.\n- **A join to a non-persisted source, or a nested column, serves live for the queries that touch it** - the source's own fields still serve from the table.\n- **A `#(access_filter)`-gated source freezes its gating column when persisted** - `#@ preaggregate` refuses it outright; a `storage=` table holds every caller's rows, ungated, in the destination; `reference/access-filter.md`.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-materialization/<name>` instead.\n\nAvailable: access-filter, annotation, chaining, policy, refresh, storage, tuning."
|
|
208280
208565
|
},
|
|
208281
208566
|
{
|
|
208282
208567
|
name: "malloy-materialization/access-filter",
|
|
@@ -209065,7 +209350,7 @@ When you've been doing analysis, writing queries, building views, creating repor
|
|
|
209065
209350
|
|
|
209066
209351
|
## Step 1: IDENTIFY, what belongs in a model?
|
|
209067
209352
|
|
|
209068
|
-
Scan your analysis \`.malloy\` files and reports (any \`.malloy\` with an \`## artifact\` tag, wherever it sits
|
|
209353
|
+
Scan your analysis \`.malloy\` files and reports (any \`.malloy\` with an \`## artifact\` tag, wherever it sits). A report (a \`tiles=[…]\` layout, of either layout) is not a model file to restructure: lift its reusable definitions into a model and leave the report to import them. For each dimension, measure, join, or calculation, ask: **is this a reusable building block?**
|
|
209069
209354
|
|
|
209070
209355
|
A measure or dimension belongs in a model if it meets ANY of these criteria:
|
|
209071
209356
|
|
|
@@ -209279,7 +209564,7 @@ source: first_touch is conn.table('events') -> {
|
|
|
209279
209564
|
{
|
|
209280
209565
|
name: "malloy-modeling",
|
|
209281
209566
|
description: "Build semantic models with Malloy for the Malloy Publisher. Read this skill whenever the user asks about modeling data or specifically mentions Malloy.",
|
|
209282
|
-
body: "# STOP - READ BEFORE WRITING ANY MALLOY CODE\n\n> **AI AGENTS: You MUST review this file before writing Malloy code.** Cross-skill references below use logical `skill:` names; load the referenced skill before acting. Before writing code, also read the gotcha skills: `skill:malloy-gotchas-modeling`, `skill:malloy-queries`, and `skill:malloy-charts`.\n\n## Pre-Flight Checklist\n\n1. **Discover first**: ground yourself before writing ANY code, with the tool that matches what you are modelling.\n - Modelling data **already in a package**: `get_context` returns that package's sources, views, and fields (with their docs).\n - Modelling **a database with no package yet**: `get_context` has nothing to return, so use `search_database_schema` instead. It walks the connection's schemas and tables, ranks them against a plain-English description, and gives you each table's columns plus the `source:` line to start from. Take those names verbatim into step 5.\n Never guess field names either way.\n2. **Search docs proactively**: call `search_malloy_docs` BEFORE writing unfamiliar patterns (window functions, query-based sources, pipelines). Don't guess. Malloy syntax is specific and SQL intuition is often wrong.\n3. **Search by topic name.** `search_malloy_docs` takes plain topics such as \"window functions\", \"comparing timeframes\", \"cohort analysis\", \"percent of total\", \"histogram\", \"nesting\", \"rendering\".\n4. **Check diagnostics** after writing: fix the FIRST error first, errors cascade.\n5. **Read the gotcha skills**: `skill:malloy-gotchas-modeling`, `skill:malloy-queries`, and `skill:malloy-charts` prevent the most common mistakes.\n\n**Quick syntax reminders:**\n1. **Backtick reserved words:** `` `Date` ``, `` `Hour` ``, `` `Timestamp` ``, `` `Type` ``, `` `number` ``, `` `source` ``\n2. **Use `having:` for aggregate filters**: not `where:` on measures\n3. **Alias joined fields in `group_by`** if using them in `order_by`\n4. **`count()` counts rows; `count(x)` counts distinct values of `x`**: `count(distinct x)` is deprecated, write `count(x)`\n5. **One tag per line**: `# label=\"Revenue\"` and `# currency` on separate lines\n6. **No fixed scale on measures**: use `# currency` not `# currency=usd0m`\n7. **Cast strings for aggregates:** `avg(score::number)` not `avg(score)`\n8. **Boolean columns:** use `= true` not `= 'true'` (no quotes!)\n9. **Read data files in place:** `.csv`, `.parquet`, `.json`, `.ndjson`, and `.xlsx` all work as-is through `duckdb.table('data/file.ext')`. Never convert a file to another format first, and never read one with python or jq to \"have a look\" first: query it. For `.xlsx`, check the row count before trusting it: a workbook with a title row or a blank spacer reads short and reports no error. (Per-format quirks: `skill:malloy-gotchas-modeling`)\n\n## Planning and `modeling-notes.md`\n\nIf the IDE has a native plan mode, use it for the high-level approach: do data exploration during planning, then present a concrete plan for user approval before writing any files.\n\n`modeling-notes.md` is an expected output of the workflow, not an optional extra. Start it at step 2 (Propose Scope) and grow it as you work: it persists alongside the model, and its value is as the thing the user argues with at step 3, before source files exist; written after the build it can only document decisions already baked in. Record findings and problems as they are found during discovery (`skill:malloy-discover`), and every unconfirmed decision as an open item. Only when there is no writable workspace do the notes live in the conversation instead.\n\nKeep it compact, with these sections:\n\n```markdown\n# Modeling notes - <package>\n## Scope what was confirmed, what the model is FOR, skip list with reasons\n## Grain and keys proven by query, not by column name\n## Coverage coverage cliffs; columns excluded for nullity\n## Decisions each with its evidence\n## Open decisions ASSUMPTIONS, NOT CONFIRMED: every threshold or definition the user\n has not settled, one entry each, mirrored by a hedge in its #(doc)\n## Validation reconciliation checks performed, and their results\n```\n\n## 8-Step Modeling Workflow\n\nThe agent orchestrates all steps. Steps marked **(user)** pause for input. Each step has a dedicated skill with full instructions. Read each step's skill **before starting that step**, including the decision skills for steps 1–4 (`skill:malloy-discover`, `skill:malloy-define`). They govern what the model says; skipping them to reach the build skills is how unreviewed business logic ships.\n\n**A field is not complete until it has its definition, `#(doc)` tag, and rendering tags, and any threshold or business convention in it is user-confirmed, distribution-derived, or explicitly flagged in its `#(doc)`** (see `skill:malloy-document` § Mark conventions as conventions). Documentation is part of defining a field, not a separate activity. Read `skill:malloy-document` for full documentation standards (doc string writing, tag ordering).\n\n```\nDISCOVER → SCOPE → SOURCES → DEFINITIONS → BUILD BASE → BUILD JOINED → REVIEW → CURATE\n (silent) (user) (user) (user) (agent) (agent) (user) (user)\n```\n\n| Step | Skill | What Happens |\n|------|-------|-------------|\n| 1. Discover | `skill:malloy-discover` | Read the model and data; scan sources, fields, distributions; detect prior art. With no package yet, start from `search_database_schema` to find the tables in the connection |\n| 2. Propose Scope | `skill:malloy-define` (Propose the analytical scope) | Present findings, user selects focus |\n| 3. Propose Sources | `skill:malloy-define` | Propose source plan, user confirms architecture |\n| 4. Propose Definitions | `skill:malloy-define` | Propose fields per base source, user confirms logic |\n| 5. Build Base Sources | `skill:malloy-model` | Write fully documented base source files (one per table), check diagnostics. Read `skill:malloy-document` for doc standards. |\n| 6. Build Joined Sources | `skill:malloy-model` | Write fully documented joined source files, validate. Read `skill:malloy-document` for doc standards. |\n| 7. Review | (none) | Present the review checklist below; user confirms or corrects |\n| 8. Curate | `skill:malloy-model` | Propose the published surface (an `index.malloy` with `export { ... }`) and access controls (gates, `private:` fields; `internal:` is curation only); always propose, the user decides whether to apply |\n\n### The pauses are the point\n\nThese are governed semantic models: the business decisions in them must be confirmed by a human subject-matter expert, and the **(user)** steps exist to collect that confirmation. They are real stops, not progress reports. A model can be complete, compiling, and fully documented and still be wrong everywhere it guessed; a capable agent can build the whole thing without pausing once, which is exactly the failure mode this workflow exists to prevent.\n\nWhen a decision goes unanswered (the user explicitly declines to decide, or nobody is there to ask), do not silently proceed as if it were settled. Take your best-supported position, label it an assumption in the field's own `#(doc)` (see `skill:malloy-document` § Mark conventions as conventions), record it under \"Open decisions\" in `modeling-notes.md`, and raise it again at Review. An unlabeled assumption is indistinguishable from a confirmed fact, and misleads everyone downstream.\n\n### Step 7 Review is a checklist, not a summary\n\nPresent these to the user, with answers:\n\n- **Which definitions did the user actually confirm?** List them; everything else is an assumption.\n- **Which thresholds and bucket boundaries did you choose?** For each: the evidence (distribution query, metadata, prior art) and the `#(doc)` hedge that marks it.\n- **Which questions were left unanswered?** Each must already carry a labeled assumption and an \"Open decisions\" entry.\n- **Does the headline metric have more than one defensible definition?** If yes, that is a blocking question: put the candidate definitions to the user with their counts side by side, not in a footnote.\n\nThe user confirming this checklist is what makes the model governed. A summary of what you built is not a checkpoint.\n\nPublishing is out of scope for open-source v1. Self-hosters move a finished model into a served package via git and the host's publish path; see `skill:malloy-publish` for the local-to-served handoff.\n\n**Two paths to a model: both produce the same fully documented result:**\n- **Schema-first:** \"Model my data\" → 8-step workflow above using the relevant skills\n- **Analysis-first:** a data question arrives before any model exists → `skill:malloy-model-as-you-go`. It answers the question with `skill:malloy-analysis`, then codifies what the answer assumed into the model, one question at a time, confirming binding decisions first. The model exists by the end; there is no separate formalize step.\n- **Open-ended exploration** with no intent to keep anything: `skill:malloy-analysis` (its \"no specific question\" branch). If it turns into something worth keeping, formalize via `skill:malloy-model` (`reference/analysis-to-model.md`).\n\n## Agent Behavior\n\n**Research before asking.** Present proposals with evidence. Never ask open-ended questions: propose with data and let the user confirm.\n\n**Use business language.** Say \"I simplified the column name\" not \"reserved word replaced.\" Don't expose Malloy internals unless the user asks.\n\n**Describe what you're doing, not which step you're on.** The user doesn't have the skill files open. Say \"I'll propose which tables to include and how they relate\" not \"Steps 3 and 4.\" Say \"Now I'll write the source files\" not \"Moving to Step 5.\" Explain the purpose of each phase in plain language before doing it.\n\n**Present choices as A/B/C.** When asking the user to choose, use lettered options with one-line descriptions. Mark your recommendation.\n\n**Complete all workflow steps.** Once modeling begins, complete through Review and propose Curate. A field without documentation is not finished. If you lose track, re-read the model and your notes. **Every source you write gets a source-level `#(doc)` description and a stated grain (`primary_key:` or \"one row per ...\"), including intermediate steps such as a de-duplication or clean-up source. Or fold the clean-up into the one source it feeds, so there is nothing undescribed left in the package.** Build a report (a dashboard or a notebook) only when the user asks for one.\n\n## Route by Intent\n\n| User says... | Route to |\n|-------------|----------|\n| \"Model my data\", \"create a model\" | 8-step workflow (`skill:malloy-discover`) |\n| \"Model from LookML\" | 8-step with prior art via `skill:malloy-lookml-review` |\n| \"Model from Power BI\" | 8-step with prior art via `skill:malloy-powerbi-review` |\n| \"Model from an Excel workbook\" (formulas or pivots) | 8-step with prior art via `skill:malloy-excel-review` |\n| \"Explore this data\", \"what's interesting?\", \"show me the top X\" | `skill:malloy-analysis` (no specific question) |\n| \"Build a dashboard\", \"build a notebook\", \"create views\" on existing model | `skill:malloy-reports` for a saved report (`layout=grid` for a dashboard, `layout=linear` for a notebook), written at the package root; `skill:malloy-charts` for views in the model |\n| \"Build a model but not sure what metrics\" | `skill:malloy-model-as-you-go`: answer their first real question, codify what it assumed, repeat |\n\n**If the user's first message is a data question** (not \"build me a model\"), route to `skill:malloy-model-as-you-go`. It answers with `skill:malloy-analysis` and grows the model from what each answer assumed, so there is nothing to formalize afterwards.\n\n## Additional Support Skills\n\nThese supplemental skills may also be loaded as needed:\n\n- **`skill:malloy-getting-started`**: routing guide to the other Malloy skills\n- **`skill:malloy-gotchas-modeling`**: also the place to fix compile errors and read diagnostics\n\n## Publisher MCP Tools\n\nModeling needs these tools, or their REST equivalents when you run unattended; `skill:malloy-getting-started` section 0 covers both cases. No server yet? `skill:malloy-getting-started` covers setup, including the one-command scaffolder (`npm create @malloy-publisher/malloy-package@latest <name>`) and why local authoring needs `--watch-env <env>`: start the server without it and your saved edits are never read.\n\n| Tool | Purpose |\n|------|---------|\n| `get_context` | Ground yourself in a package: its sources, views, and fields |\n| `execute_query` | Run ad-hoc queries for validation |\n| `compile_model` | Compile-check a change and get diagnostics back without running a query |\n| `reload_package` | Recompile a package from disk so a saved edit becomes queryable by name |\n| `search_malloy_docs` | Search Malloy docs (call BEFORE unfamiliar patterns) |\n| `search_database_schema` | Find the tables in a database connection by plain-English description, when modelling data that is not in a package yet. Returns each table's columns and the `source:` line to start from. Names and types only: no row value is returned |\n\nNever guess field names. Ground yourself with `get_context` to see the sources and fields a package defines.\n\n### The edit-and-run loop\n\nPublisher 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 you reload the package. The loop is:\n\n1. **Validate** the change with `compile_model`, picking the scope that matches what you are doing:\n - Adding a new definition or query: the default (`scope: \"append\"`) compiles your text in the model's namespace. Note its diagnostic positions land in the model-plus-your-text concatenation. Append checks your text against what the model already publishes, so it refuses text that declares its own data root -- `import`, `connection.table(...)` and `connection.sql(...)` are rejected. A `source:` line handed to you by `search_database_schema` is exactly that shape, so validate it at `file` or `package` scope instead.\n - **Editing an existing definition: `scope: \"file\"`**, with the whole edited file as `source`. It compiles your text AS the file (append would collide with \"Cannot redefine\"), and diagnostics land at the true line numbers of your text.\n - Before saving a change other files import: `scope: \"package\"` with the edited file as `source` runs reload's worker compiler over every `.malloy` and `.malloynb` file against your edit, so a rename that breaks an importer surfaces now instead of at reload. Each diagnostic carries `model`, the file it points at; files hidden from discovery can appear. If `modelPath` does not exactly match an existing file, a warning says the source was treated as new.\n2. **Save** it to the package's model file.\n3. **Reload** with `reload_package`.\n4. **Run** the new view with `execute_query`.\n\nA reload that fails to compile is safe: your files are left alone and the previously compiled model keeps serving, with the compile errors returned to you. Compile first anyway for faster feedback, and a `scope: \"package\"` dry-run with no `source` uses reload's compiler and file selection (imports across files, every `.malloy` and `.malloynb` file as saved) without touching the served model. Keep the source of truth outside `publisher_data/`, which is not version-controlled and is wiped by a `--init` restart. If these tools are missing, the Publisher you are connected to predates them; fall back to validating with a throwaway `execute_query`. An older Publisher that has `compile_model` but rejects `scope` supports only the append behavior.\n\n## SQL-to-Malloy Quick Reference\n\n| SQL | Malloy |\n|-----|--------|\n| `COUNT(*)` | `count()` |\n| `COUNT(DISTINCT x)` | `count(x)` |\n| `NOW()` | `now` |\n| `CASE WHEN...END` | `pick...when...else` |\n| `col IN ('a','b')` | `col ? 'a' \\| 'b'` |\n| `COALESCE(a,b)` | `a ?? b` |\n| `CAST(x AS type)` | `x::type` |\n| `DATEDIFF(day, a, b)` | `days(a to b)` |\n| `CONCAT(a, b)` or `a \\|\\| b` | `concat(a, b)` |\n| `TIMESTAMP_DIFF(a, b, SECOND)` | `seconds(b to a)` |\n\n## Critical Rules\n\n1. **All keywords require colons**: `source:`, `dimension:`, `measure:`, `view:`\n2. **Use `is` not `as`**: `dimension: name is expression`\n3. **Arrow operator required**: `run: source -> { operations }`\n4. **Specify join type**: `join_one:`, `join_many:`, `join_cross:`\n5. **Safe division**: `revenue / nullif(count, 0)`\n6. **Group definitions under one keyword**: `measure:` then indent fields beneath\n\n## Common Anti-Patterns\n\n```\nWRONG: source flights is ... RIGHT: source: flights is ...\nWRONG: dimension: x as y RIGHT: dimension: y is x\nWRONG: count(*) RIGHT: count()\nWRONG: count(distinct x) RIGHT: count(x)\nWRONG: revenue / order_count RIGHT: revenue / nullif(order_count, 0)\nWRONG: run: src { ... } RIGHT: run: src -> { ... }\n```\n\n## Reserved Words: Scan Schema First\n\n**Malloy has many reserved words. When in doubt, backtick it.** Most likely to appear as column names:\n\n```\ndate, time, day, month, year, quarter, week, hour, minute, second,\nnumber, string, boolean, type, table, source, index, count, sum, avg, min, max,\ntrue, false, null, is, on, with, all, from, by, in, to, for, select, order_by,\ntop, bottom, desc, asc, row, range, current, window, rank\n```\n\n- `number`: only the bare word needs backticking; `account_number` is fine\n- `source`: reserved; use a different alias like `traffic_source`\n- `string`, `boolean`, `true`, `false`: backtick any column with these exact names\n\n## Gotcha Skills: Read Before Writing Code\n\nThe following skills contain detailed WRONG/RIGHT patterns that prevent the most common Malloy errors. **Read them before writing code:**\n\n- **`skill:malloy-gotchas-modeling`**: Reserved words, NULL checks, date functions, type casts, rename pitfalls, query-based source gotchas, `conn.sql()` anti-pattern\n- **`skill:malloy-queries`**: Syntax and the common compile errors: chart constraints, aggregate filters, joined field aliasing, method syntax, time truncation vs extraction\n- **`skill:malloy-charts`**: Chart selection, tag syntax, scale rules, sparkline setup, big_value patterns"
|
|
209567
|
+
body: "# STOP - READ BEFORE WRITING ANY MALLOY CODE\n\n> **AI AGENTS: You MUST review this file before writing Malloy code.** Cross-skill references below use logical `skill:` names; load the referenced skill before acting. Before writing code, also read the gotcha skills: `skill:malloy-gotchas-modeling`, `skill:malloy-queries`, and `skill:malloy-charts`.\n\n## Pre-Flight Checklist\n\n1. **Discover first**: ground yourself before writing ANY code, with the tool that matches what you are modelling.\n - Modelling data **already in a package**: `get_context` returns that package's sources, views, and fields (with their docs).\n - Modelling **a database with no package yet**: `get_context` has nothing to return, so use `search_database_schema` instead. It walks the connection's schemas and tables, ranks them against a plain-English description, and gives you each table's columns plus the `source:` line to start from. Take those names verbatim into step 5.\n Never guess field names either way.\n2. **Search docs proactively**: call `search_malloy_docs` BEFORE writing unfamiliar patterns (window functions, query-based sources, pipelines). Don't guess. Malloy syntax is specific and SQL intuition is often wrong.\n3. **Search by topic name.** `search_malloy_docs` takes plain topics such as \"window functions\", \"comparing timeframes\", \"cohort analysis\", \"percent of total\", \"histogram\", \"nesting\", \"rendering\".\n4. **Check diagnostics** after writing: fix the FIRST error first, errors cascade.\n5. **Read the gotcha skills**: `skill:malloy-gotchas-modeling`, `skill:malloy-queries`, and `skill:malloy-charts` prevent the most common mistakes.\n\n**Quick syntax reminders:**\n1. **Backtick reserved words:** `` `Date` ``, `` `Hour` ``, `` `Timestamp` ``, `` `Type` ``, `` `number` ``, `` `source` ``\n2. **Use `having:` for aggregate filters**: not `where:` on measures\n3. **Alias joined fields in `group_by`** if using them in `order_by`\n4. **`count()` counts rows; `count(x)` counts distinct values of `x`**: `count(distinct x)` is deprecated, write `count(x)`\n5. **One tag per line**: `# label=\"Revenue\"` and `# currency` on separate lines\n6. **No fixed scale on measures**: use `# currency` not `# currency=usd0m`\n7. **Cast strings for aggregates:** `avg(score::number)` not `avg(score)`\n8. **Boolean columns:** use `= true` not `= 'true'` (no quotes!)\n9. **Read data files in place:** `.csv`, `.parquet`, `.json`, `.ndjson`, and `.xlsx` all work as-is through `duckdb.table('data/file.ext')`. Never convert a file to another format first, and never read one with python or jq to \"have a look\" first: query it. For `.xlsx`, check the row count before trusting it: a workbook with a title row or a blank spacer reads short and reports no error. (Per-format quirks: `skill:malloy-gotchas-modeling`)\n\n## Planning and `modeling-notes.md`\n\nIf the IDE has a native plan mode, use it for the high-level approach: do data exploration during planning, then present a concrete plan for user approval before writing any files.\n\n`modeling-notes.md` is an expected output of the workflow, not an optional extra. Start it at step 2 (Propose Scope) and grow it as you work: it persists alongside the model, and its value is as the thing the user argues with at step 3, before source files exist; written after the build it can only document decisions already baked in. Record findings and problems as they are found during discovery (`skill:malloy-discover`), and every unconfirmed decision as an open item. Only when there is no writable workspace do the notes live in the conversation instead.\n\nKeep it compact, with these sections:\n\n```markdown\n# Modeling notes - <package>\n## Scope what was confirmed, what the model is FOR, skip list with reasons\n## Grain and keys proven by query, not by column name\n## Coverage coverage cliffs; columns excluded for nullity\n## Decisions each with its evidence\n## Open decisions ASSUMPTIONS, NOT CONFIRMED: every threshold or definition the user\n has not settled, one entry each, mirrored by a hedge in its #(doc)\n## Validation reconciliation checks performed, and their results\n```\n\n## 8-Step Modeling Workflow\n\nThe agent orchestrates all steps. Steps marked **(user)** pause for input. Each step has a dedicated skill with full instructions. Read each step's skill **before starting that step**, including the decision skills for steps 1–4 (`skill:malloy-discover`, `skill:malloy-define`). They govern what the model says; skipping them to reach the build skills is how unreviewed business logic ships.\n\n**A field is not complete until it has its definition, `#(doc)` tag, and rendering tags, and any threshold or business convention in it is user-confirmed, distribution-derived, or explicitly flagged in its `#(doc)`** (see `skill:malloy-document` § Mark conventions as conventions). Documentation is part of defining a field, not a separate activity. Read `skill:malloy-document` for full documentation standards (doc string writing, tag ordering).\n\n```\nDISCOVER → SCOPE → SOURCES → DEFINITIONS → BUILD BASE → BUILD JOINED → REVIEW → CURATE\n (silent) (user) (user) (user) (agent) (agent) (user) (user)\n```\n\n| Step | Skill | What Happens |\n|------|-------|-------------|\n| 1. Discover | `skill:malloy-discover` | Read the model and data; scan sources, fields, distributions; detect prior art. With no package yet, start from `search_database_schema` to find the tables in the connection |\n| 2. Propose Scope | `skill:malloy-define` (Propose the analytical scope) | Present findings, user selects focus |\n| 3. Propose Sources | `skill:malloy-define` | Propose source plan, user confirms architecture |\n| 4. Propose Definitions | `skill:malloy-define` | Propose fields per base source, user confirms logic |\n| 5. Build Base Sources | `skill:malloy-model` | Write fully documented base source files (one per table), check diagnostics. Read `skill:malloy-document` for doc standards. |\n| 6. Build Joined Sources | `skill:malloy-model` | Write fully documented joined source files, validate. Read `skill:malloy-document` for doc standards. |\n| 7. Review | (none) | Present the review checklist below; user confirms or corrects |\n| 8. Curate | `skill:malloy-model` | Propose the published surface (an `index.malloy` with `export { ... }`) and access controls (gates, `private:` fields; `internal:` is curation only); always propose, the user decides whether to apply |\n\n### The pauses are the point\n\nThese are governed semantic models: the business decisions in them must be confirmed by a human subject-matter expert, and the **(user)** steps exist to collect that confirmation. They are real stops, not progress reports. A model can be complete, compiling, and fully documented and still be wrong everywhere it guessed; a capable agent can build the whole thing without pausing once, which is exactly the failure mode this workflow exists to prevent.\n\nWhen a decision goes unanswered (the user explicitly declines to decide, or nobody is there to ask), do not silently proceed as if it were settled. Take your best-supported position, label it an assumption in the field's own `#(doc)` (see `skill:malloy-document` § Mark conventions as conventions), record it under \"Open decisions\" in `modeling-notes.md`, and raise it again at Review. An unlabeled assumption is indistinguishable from a confirmed fact, and misleads everyone downstream.\n\n### Step 7 Review is a checklist, not a summary\n\nPresent these to the user, with answers:\n\n- **Which definitions did the user actually confirm?** List them; everything else is an assumption.\n- **Which thresholds and bucket boundaries did you choose?** For each: the evidence (distribution query, metadata, prior art) and the `#(doc)` hedge that marks it.\n- **Which questions were left unanswered?** Each must already carry a labeled assumption and an \"Open decisions\" entry.\n- **Does the headline metric have more than one defensible definition?** If yes, that is a blocking question: put the candidate definitions to the user with their counts side by side, not in a footnote.\n\nThe user confirming this checklist is what makes the model governed. A summary of what you built is not a checkpoint.\n\nPublishing is out of scope for open-source v1. Self-hosters move a finished model into a served package via git and the host's publish path; see `skill:malloy-publish` for the local-to-served handoff.\n\n**Two paths to a model: both produce the same fully documented result:**\n- **Schema-first:** \"Model my data\" → 8-step workflow above using the relevant skills\n- **Analysis-first:** a data question arrives before any model exists → `skill:malloy-model-as-you-go`. It answers the question with `skill:malloy-analysis`, then codifies what the answer assumed into the model, one question at a time, confirming binding decisions first. The model exists by the end; there is no separate formalize step.\n- **Open-ended exploration** with no intent to keep anything: `skill:malloy-analysis` (its \"no specific question\" branch). If it turns into something worth keeping, formalize via `skill:malloy-model` (`reference/analysis-to-model.md`).\n\n## Agent Behavior\n\n**Research before asking.** Present proposals with evidence. Never ask open-ended questions: propose with data and let the user confirm.\n\n**Use business language.** Say \"I simplified the column name\" not \"reserved word replaced.\" Don't expose Malloy internals unless the user asks.\n\n**Describe what you're doing, not which step you're on.** The user doesn't have the skill files open. Say \"I'll propose which tables to include and how they relate\" not \"Steps 3 and 4.\" Say \"Now I'll write the source files\" not \"Moving to Step 5.\" Explain the purpose of each phase in plain language before doing it.\n\n**Present choices as A/B/C.** When asking the user to choose, use lettered options with one-line descriptions. Mark your recommendation.\n\n**Complete all workflow steps.** Once modeling begins, complete through Review and propose Curate. A field without documentation is not finished. If you lose track, re-read the model and your notes. **Every source you write gets a source-level `#(doc)` description and a stated grain (`primary_key:` or \"one row per ...\"), including intermediate steps such as a de-duplication or clean-up source. Or fold the clean-up into the one source it feeds, so there is nothing undescribed left in the package.** Build a report (a dashboard or a notebook) only when the user asks for one.\n\n## Route by Intent\n\n| User says... | Route to |\n|-------------|----------|\n| \"Model my data\", \"create a model\" | 8-step workflow (`skill:malloy-discover`) |\n| \"Model from LookML\" | 8-step with prior art via `skill:malloy-lookml-review` |\n| \"Model from Power BI\" | 8-step with prior art via `skill:malloy-powerbi-review` |\n| \"Model from an Excel workbook\" (formulas or pivots) | 8-step with prior art via `skill:malloy-excel-review` |\n| \"Explore this data\", \"what's interesting?\", \"show me the top X\" | `skill:malloy-analysis` (no specific question) |\n| \"Build a dashboard\", \"build a notebook\", \"create views\" on existing model | `skill:malloy-reports` for a saved report (`layout=grid` for a dashboard, `layout=linear` for a notebook), written at the package root; `skill:malloy-charts` for views in the model |\n| \"Build a model but not sure what metrics\" | `skill:malloy-model-as-you-go`: answer their first real question, codify what it assumed, repeat |\n\n**If the user's first message is a data question** (not \"build me a model\"), route to `skill:malloy-model-as-you-go`. It answers with `skill:malloy-analysis` and grows the model from what each answer assumed, so there is nothing to formalize afterwards.\n\n## Additional Support Skills\n\nThese supplemental skills may also be loaded as needed:\n\n- **`skill:malloy-getting-started`**: routing guide to the other Malloy skills\n- **`skill:malloy-gotchas-modeling`**: also the place to fix compile errors and read diagnostics\n\n## Publisher MCP Tools\n\nModeling needs these tools, or their REST equivalents when you run unattended; `skill:malloy-getting-started` section 0 covers both cases. No server yet? `skill:malloy-getting-started` covers setup, including the one-command scaffolder (`npm create @malloy-publisher/malloy-package@latest <name>`) and why local authoring needs `--watch-env <env>`: start the server without it and your saved edits are never read.\n\n| Tool | Purpose |\n|------|---------|\n| `get_context` | Ground yourself in a package: its sources, views, and fields |\n| `execute_query` | Run ad-hoc queries for validation |\n| `compile_model` | Compile-check a change and get diagnostics back without running a query |\n| `reload_package` | Recompile a package from disk so a saved edit becomes queryable by name |\n| `search_malloy_docs` | Search Malloy docs (call BEFORE unfamiliar patterns) |\n| `search_database_schema` | Find the tables in a database connection by plain-English description, when modelling data that is not in a package yet. Returns each table's columns and the `source:` line to start from. Names and types only: no row value is returned |\n\nNever guess field names. Ground yourself with `get_context` to see the sources and fields a package defines.\n\n### The edit-and-run loop\n\nPublisher 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 you reload the package. The loop is:\n\n1. **Validate** the change with `compile_model`, picking the scope that matches what you are doing:\n - Adding a new definition or query: the default (`scope: \"append\"`) compiles your text in the model's namespace. Note its diagnostic positions land in the model-plus-your-text concatenation. Append checks your text against what the model already publishes, so it refuses text that declares its own data root -- `import`, `connection.table(...)` and `connection.sql(...)` are rejected. A `source:` line handed to you by `search_database_schema` is exactly that shape, so validate it at `file` or `package` scope instead.\n - **Editing an existing definition: `scope: \"file\"`**, with the whole edited file as `source`. It compiles your text AS the file (append would collide with \"Cannot redefine\"), and diagnostics land at the true line numbers of your text.\n - Before saving a change other files import: `scope: \"package\"` with the edited file as `source` runs reload's worker compiler over every `.malloy` file against your edit, so a rename that breaks an importer surfaces now instead of at reload. Each diagnostic carries `model`, the file it points at; files hidden from discovery can appear. If `modelPath` does not exactly match an existing file, a warning says the source was treated as new.\n2. **Save** it to the package's model file.\n3. **Reload** with `reload_package`.\n4. **Run** the new view with `execute_query`.\n\nA reload that fails to compile is safe: your files are left alone and the previously compiled model keeps serving, with the compile errors returned to you. Compile first anyway for faster feedback, and a `scope: \"package\"` dry-run with no `source` uses reload's compiler and file selection (imports across files, every `.malloy` file as saved) without touching the served model. Keep the source of truth outside `publisher_data/`, which is not version-controlled and is wiped by a `--init` restart. If these tools are missing, the Publisher you are connected to predates them; fall back to validating with a throwaway `execute_query`. An older Publisher that has `compile_model` but rejects `scope` supports only the append behavior.\n\n## SQL-to-Malloy Quick Reference\n\n| SQL | Malloy |\n|-----|--------|\n| `COUNT(*)` | `count()` |\n| `COUNT(DISTINCT x)` | `count(x)` |\n| `NOW()` | `now` |\n| `CASE WHEN...END` | `pick...when...else` |\n| `col IN ('a','b')` | `col ? 'a' \\| 'b'` |\n| `COALESCE(a,b)` | `a ?? b` |\n| `CAST(x AS type)` | `x::type` |\n| `DATEDIFF(day, a, b)` | `days(a to b)` |\n| `CONCAT(a, b)` or `a \\|\\| b` | `concat(a, b)` |\n| `TIMESTAMP_DIFF(a, b, SECOND)` | `seconds(b to a)` |\n\n## Critical Rules\n\n1. **All keywords require colons**: `source:`, `dimension:`, `measure:`, `view:`\n2. **Use `is` not `as`**: `dimension: name is expression`\n3. **Arrow operator required**: `run: source -> { operations }`\n4. **Specify join type**: `join_one:`, `join_many:`, `join_cross:`\n5. **Safe division**: `revenue / nullif(count, 0)`\n6. **Group definitions under one keyword**: `measure:` then indent fields beneath\n\n## Common Anti-Patterns\n\n```\nWRONG: source flights is ... RIGHT: source: flights is ...\nWRONG: dimension: x as y RIGHT: dimension: y is x\nWRONG: count(*) RIGHT: count()\nWRONG: count(distinct x) RIGHT: count(x)\nWRONG: revenue / order_count RIGHT: revenue / nullif(order_count, 0)\nWRONG: run: src { ... } RIGHT: run: src -> { ... }\n```\n\n## Reserved Words: Scan Schema First\n\n**Malloy has many reserved words. When in doubt, backtick it.** Most likely to appear as column names:\n\n```\ndate, time, day, month, year, quarter, week, hour, minute, second,\nnumber, string, boolean, type, table, source, index, count, sum, avg, min, max,\ntrue, false, null, is, on, with, all, from, by, in, to, for, select, order_by,\ntop, bottom, desc, asc, row, range, current, window, rank\n```\n\n- `number`: only the bare word needs backticking; `account_number` is fine\n- `source`: reserved; use a different alias like `traffic_source`\n- `string`, `boolean`, `true`, `false`: backtick any column with these exact names\n\n## Gotcha Skills: Read Before Writing Code\n\nThe following skills contain detailed WRONG/RIGHT patterns that prevent the most common Malloy errors. **Read them before writing code:**\n\n- **`skill:malloy-gotchas-modeling`**: Reserved words, NULL checks, date functions, type casts, rename pitfalls, query-based source gotchas, `conn.sql()` anti-pattern\n- **`skill:malloy-queries`**: Syntax and the common compile errors: chart constraints, aggregate filters, joined field aliasing, method syntax, time truncation vs extraction\n- **`skill:malloy-charts`**: Chart selection, tag syntax, scale rules, sparkline setup, big_value patterns"
|
|
209283
209568
|
},
|
|
209284
209569
|
{
|
|
209285
209570
|
name: "malloy-notebooks",
|
|
@@ -211484,7 +211769,7 @@ A flat layout at the package root is the simplest default, for models and report
|
|
|
211484
211769
|
|
|
211485
211770
|
Publishable contents:
|
|
211486
211771
|
- \`.malloy\` files - Semantic model definitions (base sources + joined sources)
|
|
211487
|
-
- Reports: \`.malloy\` files with an \`## artifact { layout=linear … }\` or \`## artifact { layout=grid … }\` tag, anywhere in the package (outside \`public/\`), written as tiles (see \`skill:malloy-reports\`). A linear tag with no tiles, the retired \`run:\`-cell form, is no report. The tag alone makes a file a report and sets its layout; the folder means nothing.
|
|
211772
|
+
- Reports: \`.malloy\` files with an \`## artifact { layout=linear … }\` or \`## artifact { layout=grid … }\` tag, anywhere in the package (outside \`public/\`), written as tiles (see \`skill:malloy-reports\`). A linear tag with no tiles, the retired \`run:\`-cell form, is no report. The tag alone makes a file a report and sets its layout; the folder means nothing.
|
|
211488
211773
|
- Data files (CSV/Parquet/XLSX) - Embedded data published with package
|
|
211489
211774
|
|
|
211490
211775
|
## Version Management
|
|
@@ -211874,8 +212159,8 @@ For anything not covered here, call \`search_malloy_docs\` with the topic (for e
|
|
|
211874
212159
|
},
|
|
211875
212160
|
{
|
|
211876
212161
|
name: "malloy-reports",
|
|
211877
|
-
description: "Build or modify a Malloy Publisher report: a .malloy file with an ## artifact tag, written at the package root unless asked otherwise, laid out as a grid (a dashboard, scanned at a glance) or linear (a notebook or data story, read top to bottom), with filter controls rendered from givens and # drill click-through. Use when the user asks for a dashboard, a notebook, a report, a data story, a filterable view, or drill-through between views, and no code is wanted.
|
|
211878
|
-
body: "# Publisher Reports\n\n> A `.malloy` file with an `## artifact { layout=… tiles=[…] }` tag **is** a report. It imports the model, names the views to show, binds the filtering on those views, and says how to lay them out. Publisher discovers it at package load, renders the filter controls from the givens its tiles reference, offers `# drill` click-through, and serves it at `/<env>/<pkg>/<path>`, its package path without `.malloy`. No code, no build step.\n\nWhat other tools call a dashboard and a notebook are both reports here. The **layout** is the only difference:\n\n- **`layout=grid`**: tiles across a grid behind one filter row, scanned at a glance (a dashboard). Read `reference/grid.md` before you lay one out.\n- **`layout=linear`**: tiles and prose top to bottom, read in order (a notebook, a data story). Read `reference/linear.md` before you write one.\n\nEverything else (filters, text tiles, drill, the builder, the lint, the write path) is the same for both, and switching layout later is a one-property edit.\n\n## Where the file goes\n\n- **Write a new report at the package root**, as `<slug>.malloy`, unless the author asks for another location. No directory is required, and none is a convention: a report can live anywhere in the package except `public/`, and the root `index.malloy` is never a report. Do not create a `dashboards/` or `notebooks/` directory for it.\n- **Always write `layout=grid` or `layout=linear`** in the tag. A tag without one is read by a fallback rule, and a linear report that lists tiles without `layout=linear` is read as a grid. `kind=` is no longer read: a tag that sets it makes no report (`report-kind-removed`), so replace it with `layout=`.\n- **The package path is the report's identity.** `sales/q3.malloy` is the report `sales/q3`: its URL, its `GET …/reports/{path}` address, and its `# drill` target. Two reports may share a basename in different directories.\n- **Imports are relative to the report's own location.** At the root: `import { order_items } from \"storefront.malloy\"`. In a subdirectory: `\"../storefront.malloy\"`.\n- **An untagged `.malloy` file is an ordinary model**, wherever it lives. Shared definitions several reports import go in one.\n\n## When this is the right tool\n\n| The user wants | Use |\n| ---------------------------------------------------- | ------------------------------------------------------------ |\n| A recurring, at-a-glance view behind shared filters | this skill, `layout=grid` |\n| A narrative, with prose between the numbers | this skill, `layout=linear` |\n| A quick write-up of queries you already ran | `skill:malloy-analysis-report`, which writes a linear report |\n| Custom design, branding, or interactions beyond tags | an HTML data app |\n| The model itself: sources, measures, joins | `malloy-model` |\n\nInteractivity is not the axis: both layouts get filter controls, URL-addressable state, Apply batching, and `# drill`. Pick on the shape of the document: scanned at a glance is grid, read top to bottom is linear. When in doubt, linear.\n\n## Build sequence\n\nTool names below are bare (`get_context`); match each against the tools you actually have, since a host may prefix or rename them. A host names its compile and reload tools its own way. Where you have none, use the REST endpoint named beside the step.\n\n1. **READ THE MODEL FIRST.** Get the real source, view, dimension, and given names from the package: `get_context` if you have it, otherwise the REST model endpoint for `index.malloy` (it answers 404 for a file off the surface) or the `.malloy` files. Never guess a name. A guessed field in a query fails the whole package load, not just that one report; a guessed tile or suggest source is quieter, and only shows up in the package warnings. If the package root holds an `index.malloy` (every scaffolded package does), a tile reads only the sources that file exports.\n2. **PICK THE LAYOUT AND THE TILES.** Which views, in what order, and on a grid how wide each sits. A query tile is a `view:` you declare in the report, named as `\"source -> view\"`.\n3. **DECLARE THE GIVENS** the report will filter by, in the report file itself, with their control tags (see \"Filter controls\"). A report holds its own filters: the builder edits the report file and nothing else, so a filter it can add, change or remove is a declaration in that file. A given the model already declares and reads is imported by name, never declared again; if it is only a reader's filter, move it into the report instead (see \"Givens that stay in the model\").\n4. **COMPOSE THE FILE** at its path (the package root unless asked otherwise), following the template below, but do not save it yet. Name the sources you need in the import. Each tile binds its controls with a refinement, `view: t is v + { where: category ~ $CATEGORY }`, one clause per given it answers to; a `filter<...>` binds with `~`, a plain `date` or `number` given is a value and binds with `>=`, `<=` or `=`. Only the givens some tile references become controls. Then import every source or query any referenced given names in a `suggest`; **a `suggest` naming a `query=` needs that query's own source imported as well**, because an import is not transitive.\n5. **COMPILE IT** with your compile tool (`POST …/models/<path>/compile` over REST) at the path the file will have, with **`\"scope\": \"file\"`**: a report opens with an `import`, which the default `append` scope refuses, and an existing file compiled at `append` collides with itself. **`\"scope\": \"file\"` does not check tiles, drills or suggest queries.** To see those before you save, compile the same text at `\"scope\": \"package\"` with `modelPath` set to the report's path: it runs the lint step 6 reads and returns its findings with code `dashboard-lint` (or `render-tag`). Editing an untagged model several reports import also wants `\"scope\": \"package\"`, which recompiles every file as saved.\n6. **SAVE IT, RELOAD, AND READ THE MANIFEST AND THE WARNINGS.** Save by writing the file, or with `PUT …/models/<path>` over REST (omit `expectedHash` to create; it creates at any new path and replaces only a file the package already serves as a report). Then your reload tool, or `GET …/packages/<pkg>?reload=true`. A 424 means the package did not load and your edit is not live. **This works only in a watched environment (`--watch-env`).** Everywhere else the package is, by default, a published version, which is immutable: the `PUT` answers 409 `PACKAGE_IS_VERSIONED`, and a reload answers `mode: unchanged` without reading your file. There, add the report to the package's source, bump `version` in its `publisher.json`, and publish it again. **The `warnings` key is absent when there are none.** Then read `GET …/packages/<pkg>/reports/<path>`: its `givens` are exactly the controls that will render, and its `layout` is the layout Publisher read. See \"Read the lint\".\n7. **OPEN IT AND LOOK.** Not optional; see \"What done means\".\n\n## The form\n\n```malloy\n##! experimental.givens\n##\" One line saying what this report is for.\n##| artifact { layout=grid title=\"Storefront overview\"\n tiles=[\n intro { kind=text colspan=12 },\n \"overview -> kpis\",\n \"overview -> revenue_trend\",\n \"overview -> revenue_by_state\"\n ]\n} dashboard { columns=12 }\n|##\nimport { order_items, products } from \"storefront.malloy\"\n\n# label=\"Category\" control=select suggest { source=products dimension=category }\ngiven: CATEGORY :: filter<string> is f''\n# label=\"Ordered since\"\ngiven: SINCE :: date is @2023-01-01\n\n##|(markdown) intro\nRevenue and margin for the selected category.\n|##\n\nsource: overview is order_items extend {\n # colspan=12\n # label=\"Key figures\"\n # big_value\n view: kpis is key_figures + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n\n # colspan=8\n # break\n # label=\"Revenue by month\"\n view: revenue_trend is sales_by_month + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n\n # colspan=4\n # label=\"Revenue by state\"\n view: revenue_by_state is sales_by_state + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n}\n```\n\nThe same file with `layout=linear` and no `dashboard { … }` or `colspan` is a linear report.\n\n- **The tag is model-level**, one line (`## artifact { … }`) or a `##|` … `|##` block with the same text inside, the form to use once the list is long: one tile per line, `}` on its own line, `|##` closing at the opener's column. A one-line `##` tag must stay on one line: wrapping it is a compile error, or worse, compiles clean and quietly stops being a report.\n- **The header** above the tag holds only `##!` flags, `//` comments and the unnamed `\"` notes that are the report's description. Keep statements and `#` tags below `## artifact`: nothing refuses one above it, but the header is where readers and the builder look.\n- **Quote every query entry.** `\"overview -> kpis\"` is a string; unquoted, the tag does not parse (`notebook-artifact-unparsed`). A bare quoted name (`\"top_products\"`) names a model-level `query:` in the file.\n- **A query tile is a thin `view:` on an extension the report declares** (`source: overview is order_items extend { … }`): the modelled view keeps its chart tag, the wrapper carries the tile's `# label` and its binding. On a grid its width, row break and height can go on its entry instead, `\"overview -> kpis\" { colspan=12 rowspan=2 }`, which wins over the view's tags; `rowspan=N` is rows of 80px, and `row=N col=N` place the tile at a grid cell (a report with any `row` is placed: fixed rows, tiles where they say, empty cells allowed).\n- **A text tile is a `##|(markdown) name` block** listed as `name { kind=text }`. The name is one bare word on the opener line, the body starts on the next line (a heading goes inside the block), and `|##` closes it at the opener's column. A bare `intro` without `{ kind=text }` is the query-tile form for a `query:`, so the block is not shown. On a grid the entry also takes `colspan`, `break` and `rowspan`, and nothing else.\n- **File order:** header, imports and givens, the prose blocks in tile order, then the extension that defines the tile views. That is the order the builder writes.\n- **A `run:` in a report that lists `tiles` is never shown** (`notebook-layout-run`). Define a view, list it, delete the `run:`.\n- **A tile expression is a string, so the compiler never checks it.** Rename a view and the file still compiles; the tile fails at package load, where the lint names it.\n- **Chart tags go on the view** (`# line_chart`, `# bar_chart`, `# big_value`, `# label=\"…\"`). `skill:malloy-charts` covers choosing them.\n\n## Filter controls\n\nControls come from the `given:` declarations the tiles reference. The tags on the declaration are the control contract:\n\n```malloy\n##! experimental.givens\n\n# label=\"Category\" control=select suggest { source=products dimension=category }\ngiven: CATEGORY :: filter<string> is f''\n\n# label=\"Brand\" control=multiselect suggest { query=brand_suggest dimension=brand }\ngiven: BRAND :: filter<string> is f''\n\n# label=\"Minimum line total\" range_min=0 range_max=250\ngiven: MIN_SALE :: filter<number> is f''\n\n# label=\"Ordered since\"\ngiven: SINCE :: date is @2023-01-01\n```\n\n`control=select`/`multiselect` with a `suggest` renders a picker filled from the data; `range_min`/`range_max` on a `filter<number>` renders a two-handled range slider; a `filter<date>` or `filter<timestamp>` renders a time-range control with preset windows and a custom day range; a bare `date` or `timestamp` renders a date picker; a `filter<string>` with no tag renders a text box taking filter syntax. Which controls appear is per report, decided by which givens its tiles reference.\n\n- `#(description=\"…\")` renders as helper text under the control and draws a cosmetic \"not a well-formed route\" compile diagnostic for a multi-word value; `# description=\"…\"` publishes to the API but the UI does not render it.\n- `dimension=` can name a field of a directly joined source, quoted: `suggest { source=sales dimension=\"products.department\" }`. On the `query=` form, `dimension` names a column of that query's output; match it to the query's `group_by`.\n- **A suggest's source or query has to resolve in the report file**, so import it there. Getting it wrong does not error: the control still looks like a picker and says \"Could not load the options for this control\"; the package warnings name it.\n- Two options on the artifact tag, either layout: `autorun=false` batches control changes behind an Apply button; `givens { CATEGORY=f'Outerwear' }` sets starting values (a URL parameter wins). A file-level `## autorun=false` does nothing on a `.malloy` report.\n\n### Binding, and givens that stay in the model\n\n**Binding is per declaration, not per name.** A report declaring its own `CATEGORY` over a source whose model-level `where:` reads the model's `CATEGORY` compiles, shows the control, and filters nothing. So bind on the tiles, with `+ { where: … }`. The other design, model-level scoping, still works: put a scoped source in an untagged model that imports the givens it reads, and import that model and those givens into the report. Do not mix the two on one given.\n\nA given stays in the model, declared once there, when a model source, view or measure, an `#(authorize)` or `#(access_filter)` gate, or an HTML data app reads it. The report imports it by name (`import { CATEGORY } from \"givens.malloy\"`) and never re-declares it:\n\n- **Import a name and also declare it: a compile error.** Drop the local declaration.\n- **Declare a name the model already reads, without importing it: no error at all.** The control renders and moves, and the model's own `where:` or gate never sees the value.\n\n**A model that already scopes a source by an optional filter given** (`where: Manufacturer ~ $manufacturer_filter` in the model) needs a decision:\n\n- **It is a reader's filter and you may change the model: move it.** Delete the given and its `where:` clause from the model, declare it in the report with its control tags, and bind it on each tile that should answer to it. A reader's filter is anything a person picks on the page; a given stays in the model only for the reasons `malloy-model` lists (a gate, a value every query must supply, a parameter a field is defined with, scoping meant for every consumer).\n- **The model can't change, or the given is semantic or governance: import it** as above. Say so plainly: the filter shows in the reader and in the builder, and can be set in both, but the builder cannot remove or reconfigure it. It is the model's.\n\nBefore, in the model:\n\n```malloy\n##! experimental.givens\ngiven:\n manufacturer_filter :: filter<string> is f''\n subject_filter :: filter<string> is f''\n major_recall_filter :: filter<boolean> is f''\n recall_date_filter :: filter<date> is f''\n\nsource: recalls is duckdb.table('data/auto_recalls.csv') extend {\n where:\n Manufacturer ~ $manufacturer_filter,\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n dimension: `Major Recall` is ifnull(`Potentially Affected`, 0) > 100000\n}\n```\n\nAfter: the model declares no givens and `recalls` has no `where:`; the report declares the four and binds each tile:\n\n```malloy\n##! experimental.givens\n##| artifact { layout=grid title=\"Recalls\"\n tiles=[\"recalls_tiles -> recalls_by_year\", \"recalls_tiles -> recalls_by_manufacturer\"]\n} dashboard { columns=12 }\n|##\nimport { recalls } from \"auto_recalls.malloy\"\n\n# label=\"Manufacturer\" control=multiselect suggest { source=recalls dimension=Manufacturer }\ngiven: manufacturer_filter :: filter<string> is f''\n# label=\"Subject\"\ngiven: subject_filter :: filter<string> is f''\n# label=\"Major recalls only\"\ngiven: major_recall_filter :: filter<boolean> is f''\n# label=\"Filed\"\ngiven: recall_date_filter :: filter<date> is f''\n\nsource: recalls_tiles is recalls extend {\n # colspan=6\n view: recalls_by_year is by_year + {\n where:\n Manufacturer ~ $manufacturer_filter,\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n }\n # colspan=6\n view: recalls_by_manufacturer is by_manufacturer + {\n where:\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n }\n}\n```\n\nA tile view takes a name of its own: `view: by_year is by_year + { … }` is \"Cannot redefine 'by_year'\". Each tile binds only the givens it should answer to: `recalls_by_manufacturer` leaves the manufacturer filter off, since it is the breakdown by manufacturer. Every given here is a `filter<…>`, so each binds with `~`; a plain `date` or `number` given binds with `>=`, `<=` or `=` (step 4).\n\nA given has to be in the report file's own scope to be bindable: declared there or imported. Never add a `#(filter)` annotation: it is deprecated, a report renders no control for it, and every use has a `given:` form (`malloy-model` covers the migration). `malloy-model` and `docs/givens.md` cover givens themselves.\n\n## Drill\n\n`# drill` goes on a model **dimension**, never on a report:\n\n```malloy\n# drill { to=[\"category\", \"self\"] given=CATEGORY }\ndimension: category is products.category\n\n# drill { to=\"regions/west\" given=REGION }\ndimension: region is regions.region\n```\n\n- **`to=<path>`** navigates to a report, of either layout, by its package path without `.malloy`, read from the package root: `to=category` is `category.malloy` at the root, `to=\"regions/west\"` is `regions/west.malloy`. Quote a path with a `/`. **Always write the path from the package root**: a bare name is a root file, never a report of that name elsewhere.\n- **`to=self`** filters in place.\n- **A click always opens a menu that says what it will do**, even with one entry, each entry naming the field (as its column header reads) and value: `Filter to Region: EU` (`to=self`), `Open <report title> (Region: EU)` (each `to=<path>`; the file name when the report has no title), then `Show rows (Region: EU, Month: 2025-12)` (every value of the row). A tag adds entries; it never replaces the rows.\n- **Always write `given=`.** Without it the given is the dimension name verbatim, so `dimension: category` seeds `category`, not `CATEGORY`. `to=self` survives that (it folds case); `to=<path>` does not, and lands on an unfiltered page with nothing erroring.\n- **The destination needs a control for the given**, declared as `filter<T>`. No lint checks that half, so click it and look.\n- **Only table cells are marked drillable.** A report meant to be drilled wants at least one untagged (table) tile, grouped by the tagged dimension. A column whose rendered header another, non-drillable tile also shows loses its marking: give the two different `# label=`s.\n- **Every value offers `Show rows`**, tagged or not: the tile's source, filtered by the tile's own `where:` (its control bindings included) and every dimension of the clicked row. That works for every one-stage tile: `\"source -> view\"`, a refined view, a tile naming a `query:`, an inline query, a view grouped by a joined field, a null value. **A view of more than one stage (`{ … } -> { … }`) opens no rows**, and its cells are not marked: a later stage's dimension is an earlier output the source cannot be filtered by. Keep a table tile meant to show its rows to one stage, and put the second stage in its own tile. A source with parameters opens no rows either. Neither does an unnamed time truncation inside a view (`group_by: created_at.month`), because the result loses which truncation it was: name it (`group_by: order_month is created_at.month`) in a view meant to show its rows.\n\n## Read the lint\n\nPackage warnings after a reload are the report's test suite. Fix all of them, and read the text rather than the severity or the count. **\"Dashboard lint stopped early, so this list is incomplete\"** means the rest of the list is partial.\n\n| Finding | Fix |\n| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |\n| `# drill … targets \"x\", which is not a report in this package` | A dead click. Write the target's path |\n| `to=self, but no model in this package declares a given \"X\"` | The clicked value has nowhere to go. Declare the given, or fix `given=` |\n| `given \"X\" suggests options from source \"y\", which this file does not define` | Import `y` into the report |\n| `filters by given \"X\", which this file does not import` | No control is shown for it. Import the given |\n| A tile that does not resolve to a real view | Fix the view name, or declare the view |\n| `notebook-artifact-unparsed` | The tag does not parse, usually an unquoted `source -> view` entry |\n| `notebook-layout-run` | A `run:` beside `tiles`. Make it a view, list it, delete the `run:` |\n| `notebook-tile-layout-ignored` | `colspan` or `break` on a linear report. Remove them, or switch to `layout=grid` |\n| `report-kind-removed` | The tag sets `kind=`, which is no longer read, so the file is no report. Write the `layout=` the finding gives |\n| `report-cells-removed` | A linear tag with no `tiles`, the retired cell format, so the file is no report. List its tiles (`reference/linear.md`) |\n| `report-on-surface` | A model `index.malloy` imports (or `explores` lists) is tagged, so its sources left the surface. Untag it, or move the report out |\n| `index-is-not-a-report` | The root `index.malloy` carries a tag. Remove it; put the report in its own file |\n| `Tile … reads <source>, which index.malloy doesn't export` | Add the source to the `export { ... }` in `index.malloy`. Never add an `explores` to `publisher.json` |\n| A grid's `columns`, `colspan`, or `dashboard_columns=` findings | `reference/grid.md` |\n| Prose the reader cannot place (`notebook-markdown-attached-nowhere`, `notebook-markdown-block-unnamed`) | `reference/linear.md` |\n\n**Read the status the reload itself returns, not the listing.** One report that fails to compile fails the whole package load (424), and a package already serving keeps its previous version, so the listing still looks healthy. `GET /api/v0/status` still knows: a package serving an older model than its files appears in `loadErrors` with `stale: true`. If the reload is 200 and your report is not listed, first check that the package is not a published version: a version (its resource carries a `versionId`; the reload tool says `mode: unchanged`) answers a reload with 200 and never reads your file. Otherwise discovery skipped it: usually a missing or misspelled artifact tag, or a file under `public/`.\n\n**A clean reload is not proof the tags are right.** The parse warning is syntax only and carries no position. That is why the last step is opening the page.\n\n## Template\n\n```malloy\n##! experimental.givens\n##\" [One-line description of the report.]\n##| artifact { layout=linear title=\"[Title]\"\n tiles=[\n intro { kind=text },\n \"main_source_tiles -> broad_tile\",\n \"main_source_tiles -> drill_tile\"\n ]\n}\n|##\nimport { main_source } from \"model.malloy\"\n\n##|(markdown) intro\n[Framing question: what are we trying to understand?]\n|##\n\nsource: main_source_tiles is main_source extend {\n view: broad_tile is [broad view]\n view: drill_tile is [drill view]\n}\n```\n\nFor a grid, write `layout=grid`, add `dashboard { columns=12 }` after the tag's closing `}`, and give every tile view a `# colspan` (`reference/grid.md`).\n\n## Editing in the Console\n\nA person can open any report in the Console's builder (**Edit** on the report page; **+ Report** on the package page writes `<slug>.malloy` at the package root). The builder splices the file rather than regenerating it, so comments and anything it does not model survive; it never rewrites `layout=`, so the layout is set in the file. A file written as `run:` cells, the retired linear form, is no report and does not open (`reference/linear.md`). A save whose text declares a real `#(authorize)` or `#(access_filter)` gate outside prose is refused with a 400: gates live in a model file the report imports.\n\n## What \"done\" means\n\n- The file is at the package root (or where the author asked), and its tag says `layout=`.\n- Every source, view, and field name came from the model you read in step 1.\n- The reload returned **200**, not 424, with **zero** report warnings, and your report is in `GET …/reports`.\n- You opened the page and every tile shows real numbers: not stuck loading, not an error, not an empty state you did not intend.\n- Each control renders as the widget you intended, and changing one changes the numbers.\n- If you added a `# drill`, its `to=` is a path, and you clicked it and landed where you meant to, with the given seeded.\n- On a grid: every tile carries a colspan, each row sums to `columns`, rows end flush, nothing is clipped, and no legend or card label ends in `…`.\n\n## Reference\n\n- `reference/grid.md`: the grid recipe, its traps, and one query as the whole page.\n- `reference/linear.md`: linear reports, rewriting a retired `run:`-cell file, legacy `.malloynb`, style, and common mistakes.\n- `docs/reports.md`: the full guide this skill condenses.\n- `docs/givens.md`: the givens the controls are generated from.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-reports/<name>` instead.\n\nAvailable: grid, linear."
|
|
212162
|
+
description: "Build or modify a Malloy Publisher report: a .malloy file with an ## artifact tag, written at the package root unless asked otherwise, laid out as a grid (a dashboard, scanned at a glance) or linear (a notebook or data story, read top to bottom), with filter controls rendered from givens and # drill click-through. Use when the user asks for a dashboard, a notebook, a report, a data story, a filterable view, or drill-through between views, and no code is wanted.",
|
|
212163
|
+
body: "# Publisher Reports\n\n> A `.malloy` file with an `## artifact { layout=… tiles=[…] }` tag **is** a report. It imports the model, names the views to show, binds the filtering on those views, and says how to lay them out. Publisher discovers it at package load, renders the filter controls from the givens its tiles reference, offers `# drill` click-through, and serves it at `/<env>/<pkg>/<path>`, its package path without `.malloy`. No code, no build step.\n\nWhat other tools call a dashboard and a notebook are both reports here. The **layout** is the only difference:\n\n- **`layout=grid`**: tiles across a grid behind one filter row, scanned at a glance (a dashboard). Read `reference/grid.md` before you lay one out.\n- **`layout=linear`**: tiles and prose top to bottom, read in order (a notebook, a data story). Read `reference/linear.md` before you write one.\n\nEverything else (filters, text tiles, drill, the builder, the lint, the write path) is the same for both, and switching layout later is a one-property edit.\n\n## Where the file goes\n\n- **Write a new report at the package root**, as `<slug>.malloy`, unless the author asks for another location. No directory is required, and none is a convention: a report can live anywhere in the package except `public/`, and the root `index.malloy` is never a report. Do not create a `dashboards/` or `notebooks/` directory for it.\n- **Always write `layout=grid` or `layout=linear`** in the tag. A tag without one is read by a fallback rule, and a linear report that lists tiles without `layout=linear` is read as a grid. `kind=` is no longer read: a tag that sets it makes no report (`report-kind-removed`), so replace it with `layout=`.\n- **The package path is the report's identity.** `sales/q3.malloy` is the report `sales/q3`: its URL, its `GET …/reports/{path}` address, and its `# drill` target. Two reports may share a basename in different directories.\n- **Imports are relative to the report's own location.** At the root: `import { order_items } from \"storefront.malloy\"`. In a subdirectory: `\"../storefront.malloy\"`.\n- **An untagged `.malloy` file is an ordinary model**, wherever it lives. Shared definitions several reports import go in one.\n\n## When this is the right tool\n\n| The user wants | Use |\n| ---------------------------------------------------- | ------------------------------------------------------------ |\n| A recurring, at-a-glance view behind shared filters | this skill, `layout=grid` |\n| A narrative, with prose between the numbers | this skill, `layout=linear` |\n| A quick write-up of queries you already ran | `skill:malloy-analysis-report`, which writes a linear report |\n| Custom design, branding, or interactions beyond tags | an HTML data app |\n| The model itself: sources, measures, joins | `malloy-model` |\n\nInteractivity is not the axis: both layouts get filter controls, URL-addressable state, Apply batching, and `# drill`. Pick on the shape of the document: scanned at a glance is grid, read top to bottom is linear. When in doubt, linear.\n\n## Build sequence\n\nTool names below are bare (`get_context`); match each against the tools you actually have, since a host may prefix or rename them. A host names its compile and reload tools its own way. Where you have none, use the REST endpoint named beside the step.\n\n1. **READ THE MODEL FIRST.** Get the real source, view, dimension, and given names from the package: `get_context` if you have it, otherwise the REST model endpoint for `index.malloy` (it answers 404 for a file off the surface) or the `.malloy` files. Never guess a name. A guessed field in a query fails the whole package load, not just that one report; a guessed tile or suggest source is quieter, and only shows up in the package warnings. If the package root holds an `index.malloy` (every scaffolded package does), a tile reads only the sources that file exports.\n2. **PICK THE LAYOUT AND THE TILES.** Which views, in what order, and on a grid how wide each sits. A query tile is a `view:` you declare in the report, named as `\"source -> view\"`.\n3. **DECLARE THE GIVENS** the report will filter by, in the report file itself, with their control tags (see \"Filter controls\"). A report holds its own filters: the builder edits the report file and nothing else, so a filter it can add, change or remove is a declaration in that file. A given the model already declares and reads is imported by name, never declared again; if it is only a reader's filter, move it into the report instead (see \"Givens that stay in the model\").\n4. **COMPOSE THE FILE** at its path (the package root unless asked otherwise), following the template below, but do not save it yet. Name the sources you need in the import. Each tile binds its controls with a refinement, `view: t is v + { where: category ~ $CATEGORY }`, one clause per given it answers to; a `filter<...>` binds with `~`, a plain `date` or `number` given is a value and binds with `>=`, `<=` or `=`. Only the givens some tile references become controls. Then import every source or query any referenced given names in a `suggest`; **a `suggest` naming a `query=` needs that query's own source imported as well**, because an import is not transitive.\n5. **COMPILE IT** with your compile tool (`POST …/models/<path>/compile` over REST) at the path the file will have, with **`\"scope\": \"file\"`**: a report opens with an `import`, which the default `append` scope refuses, and an existing file compiled at `append` collides with itself. **`\"scope\": \"file\"` does not check tiles, drills or suggest queries.** To see those before you save, compile the same text at `\"scope\": \"package\"` with `modelPath` set to the report's path: it runs the lint step 6 reads and returns its findings with code `dashboard-lint` (or `render-tag`). Editing an untagged model several reports import also wants `\"scope\": \"package\"`, which recompiles every file as saved.\n6. **SAVE IT, RELOAD, AND READ THE MANIFEST AND THE WARNINGS.** Save by writing the file, or with `PUT …/models/<path>` over REST (omit `expectedHash` to create; it creates at any new path and replaces only a file the package already serves as a report). Then your reload tool, or `GET …/packages/<pkg>?reload=true`. A 424 means the package did not load and your edit is not live. **This works only in a watched environment (`--watch-env`).** Everywhere else the package is, by default, a published version, which is immutable: the `PUT` answers 409 `PACKAGE_IS_VERSIONED`, and a reload answers `mode: unchanged` without reading your file. There, add the report to the package's source, bump `version` in its `publisher.json`, and publish it again. **The `warnings` key is absent when there are none.** Then read `GET …/packages/<pkg>/reports/<path>`: its `givens` are exactly the controls that will render, and its `layout` is the layout Publisher read. See \"Read the lint\".\n7. **OPEN IT AND LOOK.** Not optional; see \"What done means\".\n\n## The form\n\n```malloy\n##! experimental.givens\n##\" One line saying what this report is for.\n##| artifact { layout=grid title=\"Storefront overview\"\n tiles=[\n intro { kind=text colspan=12 },\n \"overview -> kpis\",\n \"overview -> revenue_trend\",\n \"overview -> revenue_by_state\"\n ]\n} dashboard { columns=12 }\n|##\nimport { order_items, products } from \"storefront.malloy\"\n\n# label=\"Category\" control=select suggest { source=products dimension=category }\ngiven: CATEGORY :: filter<string> is f''\n# label=\"Ordered since\"\ngiven: SINCE :: date is @2023-01-01\n\n##|(markdown) intro\nRevenue and margin for the selected category.\n|##\n\nsource: overview is order_items extend {\n # colspan=12\n # label=\"Key figures\"\n # big_value\n view: kpis is key_figures + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n\n # colspan=8\n # break\n # label=\"Revenue by month\"\n view: revenue_trend is sales_by_month + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n\n # colspan=4\n # label=\"Revenue by state\"\n view: revenue_by_state is sales_by_state + { where: category ~ $CATEGORY, where: created_at >= $SINCE }\n}\n```\n\nThe same file with `layout=linear` and no `dashboard { … }` or `colspan` is a linear report.\n\n- **The tag is model-level**, one line (`## artifact { … }`) or a `##|` … `|##` block with the same text inside, the form to use once the list is long: one tile per line, `}` on its own line, `|##` closing at the opener's column. A one-line `##` tag must stay on one line: wrapping it is a compile error, or worse, compiles clean and quietly stops being a report.\n- **The header** above the tag holds only `##!` flags, `//` comments and the unnamed `\"` notes that are the report's description. Keep statements and `#` tags below `## artifact`: nothing refuses one above it, but the header is where readers and the builder look.\n- **Quote every query entry.** `\"overview -> kpis\"` is a string; unquoted, the tag does not parse (`notebook-artifact-unparsed`). A bare quoted name (`\"top_products\"`) names a model-level `query:` in the file.\n- **A query tile is a thin `view:` on an extension the report declares** (`source: overview is order_items extend { … }`): the modelled view keeps its chart tag, the wrapper carries the tile's `# label` and its binding. On a grid its width, row break and height can go on its entry instead, `\"overview -> kpis\" { colspan=12 rowspan=2 }`, which wins over the view's tags; `rowspan=N` is rows of 80px, and `row=N col=N` place the tile at a grid cell (a report with any `row` is placed: fixed rows, tiles where they say, empty cells allowed).\n- **A text tile is a `##|(markdown) name` block** listed as `name { kind=text }`. The name is one bare word on the opener line, the body starts on the next line (a heading goes inside the block), and `|##` closes it at the opener's column. A bare `intro` without `{ kind=text }` is the query-tile form for a `query:`, so the block is not shown. On a grid the entry also takes `colspan`, `break` and `rowspan`, and nothing else.\n- **File order:** header, imports and givens, the prose blocks in tile order, then the extension that defines the tile views. That is the order the builder writes.\n- **A `run:` in a report that lists `tiles` is never shown** (`notebook-layout-run`). Define a view, list it, delete the `run:`.\n- **A tile expression is a string, so the compiler never checks it.** Rename a view and the file still compiles; the tile fails at package load, where the lint names it.\n- **Chart tags go on the view** (`# line_chart`, `# bar_chart`, `# big_value`, `# label=\"…\"`). `skill:malloy-charts` covers choosing them.\n\n## Filter controls\n\nControls come from the `given:` declarations the tiles reference. The tags on the declaration are the control contract:\n\n```malloy\n##! experimental.givens\n\n# label=\"Category\" control=select suggest { source=products dimension=category }\ngiven: CATEGORY :: filter<string> is f''\n\n# label=\"Brand\" control=multiselect suggest { query=brand_suggest dimension=brand }\ngiven: BRAND :: filter<string> is f''\n\n# label=\"Minimum line total\" range_min=0 range_max=250\ngiven: MIN_SALE :: filter<number> is f''\n\n# label=\"Ordered since\"\ngiven: SINCE :: date is @2023-01-01\n```\n\n`control=select`/`multiselect` with a `suggest` renders a picker filled from the data; `range_min`/`range_max` on a `filter<number>` renders a two-handled range slider; a `filter<date>` or `filter<timestamp>` renders a time-range control with preset windows and a custom day range; a bare `date` or `timestamp` renders a date picker; a `filter<string>` with no tag renders a text box taking filter syntax. Which controls appear is per report, decided by which givens its tiles reference.\n\n- `#(description=\"…\")` renders as helper text under the control and draws a cosmetic \"not a well-formed route\" compile diagnostic for a multi-word value; `# description=\"…\"` publishes to the API but the UI does not render it.\n- `dimension=` can name a field of a directly joined source, quoted: `suggest { source=sales dimension=\"products.department\" }`. On the `query=` form, `dimension` names a column of that query's output; match it to the query's `group_by`.\n- **A suggest's source or query has to resolve in the report file**, so import it there. Getting it wrong does not error: the control still looks like a picker and says \"Could not load the options for this control\"; the package warnings name it.\n- Two options on the artifact tag, either layout: `autorun=false` batches control changes behind an Apply button; `givens { CATEGORY=f'Outerwear' }` sets starting values (a URL parameter wins). A file-level `## autorun=false` does nothing on a `.malloy` report.\n\n### Binding, and givens that stay in the model\n\n**Binding is per declaration, not per name.** A report declaring its own `CATEGORY` over a source whose model-level `where:` reads the model's `CATEGORY` compiles, shows the control, and filters nothing. So bind on the tiles, with `+ { where: … }`. The other design, model-level scoping, still works: put a scoped source in an untagged model that imports the givens it reads, and import that model and those givens into the report. Do not mix the two on one given.\n\nA given stays in the model, declared once there, when a model source, view or measure, an `#(authorize)` or `#(access_filter)` gate, or an HTML data app reads it. The report imports it by name (`import { CATEGORY } from \"givens.malloy\"`) and never re-declares it:\n\n- **Import a name and also declare it: a compile error.** Drop the local declaration.\n- **Declare a name the model already reads, without importing it: no error at all.** The control renders and moves, and the model's own `where:` or gate never sees the value.\n\n**A model that already scopes a source by an optional filter given** (`where: Manufacturer ~ $manufacturer_filter` in the model) needs a decision:\n\n- **It is a reader's filter and you may change the model: move it.** Delete the given and its `where:` clause from the model, declare it in the report with its control tags, and bind it on each tile that should answer to it. A reader's filter is anything a person picks on the page; a given stays in the model only for the reasons `malloy-model` lists (a gate, a value every query must supply, a parameter a field is defined with, scoping meant for every consumer).\n- **The model can't change, or the given is semantic or governance: import it** as above. Say so plainly: the filter shows in the reader and in the builder, and can be set in both, but the builder cannot remove or reconfigure it. It is the model's.\n\nBefore, in the model:\n\n```malloy\n##! experimental.givens\ngiven:\n manufacturer_filter :: filter<string> is f''\n subject_filter :: filter<string> is f''\n major_recall_filter :: filter<boolean> is f''\n recall_date_filter :: filter<date> is f''\n\nsource: recalls is duckdb.table('data/auto_recalls.csv') extend {\n where:\n Manufacturer ~ $manufacturer_filter,\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n dimension: `Major Recall` is ifnull(`Potentially Affected`, 0) > 100000\n}\n```\n\nAfter: the model declares no givens and `recalls` has no `where:`; the report declares the four and binds each tile:\n\n```malloy\n##! experimental.givens\n##| artifact { layout=grid title=\"Recalls\"\n tiles=[\"recalls_tiles -> recalls_by_year\", \"recalls_tiles -> recalls_by_manufacturer\"]\n} dashboard { columns=12 }\n|##\nimport { recalls } from \"auto_recalls.malloy\"\n\n# label=\"Manufacturer\" control=multiselect suggest { source=recalls dimension=Manufacturer }\ngiven: manufacturer_filter :: filter<string> is f''\n# label=\"Subject\"\ngiven: subject_filter :: filter<string> is f''\n# label=\"Major recalls only\"\ngiven: major_recall_filter :: filter<boolean> is f''\n# label=\"Filed\"\ngiven: recall_date_filter :: filter<date> is f''\n\nsource: recalls_tiles is recalls extend {\n # colspan=6\n view: recalls_by_year is by_year + {\n where:\n Manufacturer ~ $manufacturer_filter,\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n }\n # colspan=6\n view: recalls_by_manufacturer is by_manufacturer + {\n where:\n Subject ~ $subject_filter,\n `Major Recall` ~ $major_recall_filter,\n `Report Received Date` ~ $recall_date_filter\n }\n}\n```\n\nA tile view takes a name of its own: `view: by_year is by_year + { … }` is \"Cannot redefine 'by_year'\". Each tile binds only the givens it should answer to: `recalls_by_manufacturer` leaves the manufacturer filter off, since it is the breakdown by manufacturer. Every given here is a `filter<…>`, so each binds with `~`; a plain `date` or `number` given binds with `>=`, `<=` or `=` (step 4).\n\nA given has to be in the report file's own scope to be bindable: declared there or imported. Never add a `#(filter)` annotation: it is deprecated, a report renders no control for it, and every use has a `given:` form (`malloy-model` covers the migration). `malloy-model` and `docs/givens.md` cover givens themselves.\n\n## Drill\n\n`# drill` goes on a model **dimension**, never on a report:\n\n```malloy\n# drill { to=[\"category\", \"self\"] given=CATEGORY }\ndimension: category is products.category\n\n# drill { to=\"regions/west\" given=REGION }\ndimension: region is regions.region\n```\n\n- **`to=<path>`** navigates to a report, of either layout, by its package path without `.malloy`, read from the package root: `to=category` is `category.malloy` at the root, `to=\"regions/west\"` is `regions/west.malloy`. Quote a path with a `/`. **Always write the path from the package root**: a bare name is a root file, never a report of that name elsewhere.\n- **`to=self`** filters in place.\n- **A click always opens a menu that says what it will do**, even with one entry, each entry naming the field (as its column header reads) and value: `Filter to Region: EU` (`to=self`), `Open <report title> (Region: EU)` (each `to=<path>`; the file name when the report has no title), then `Show rows (Region: EU, Month: 2025-12)` (every value of the row). A tag adds entries; it never replaces the rows.\n- **Always write `given=`.** Without it the given is the dimension name verbatim, so `dimension: category` seeds `category`, not `CATEGORY`. `to=self` survives that (it folds case); `to=<path>` does not, and lands on an unfiltered page with nothing erroring.\n- **The destination needs a control for the given**, declared as `filter<T>`. No lint checks that half, so click it and look.\n- **Only table cells are marked drillable.** A report meant to be drilled wants at least one untagged (table) tile, grouped by the tagged dimension. A column whose rendered header another, non-drillable tile also shows loses its marking: give the two different `# label=`s.\n- **Every value offers `Show rows`**, tagged or not: the tile's source, filtered by the tile's own `where:` (its control bindings included) and every dimension of the clicked row. That works for every one-stage tile: `\"source -> view\"`, a refined view, a tile naming a `query:`, an inline query, a view grouped by a joined field, a null value. **A view of more than one stage (`{ … } -> { … }`) opens no rows**, and its cells are not marked: a later stage's dimension is an earlier output the source cannot be filtered by. Keep a table tile meant to show its rows to one stage, and put the second stage in its own tile. A source with parameters opens no rows either. Neither does an unnamed time truncation inside a view (`group_by: created_at.month`), because the result loses which truncation it was: name it (`group_by: order_month is created_at.month`) in a view meant to show its rows.\n\n## Read the lint\n\nPackage warnings after a reload are the report's test suite. Fix all of them, and read the text rather than the severity or the count. **\"Dashboard lint stopped early, so this list is incomplete\"** means the rest of the list is partial.\n\n| Finding | Fix |\n| ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |\n| `# drill … targets \"x\", which is not a report in this package` | A dead click. Write the target's path |\n| `to=self, but no model in this package declares a given \"X\"` | The clicked value has nowhere to go. Declare the given, or fix `given=` |\n| `given \"X\" suggests options from source \"y\", which this file does not define` | Import `y` into the report |\n| `filters by given \"X\", which this file does not import` | No control is shown for it. Import the given |\n| A tile that does not resolve to a real view | Fix the view name, or declare the view |\n| `notebook-artifact-unparsed` | The tag does not parse, usually an unquoted `source -> view` entry |\n| `notebook-layout-run` | A `run:` beside `tiles`. Make it a view, list it, delete the `run:` |\n| `notebook-tile-layout-ignored` | `colspan` or `break` on a linear report. Remove them, or switch to `layout=grid` |\n| `report-kind-removed` | The tag sets `kind=`, which is no longer read, so the file is no report. Write the `layout=` the finding gives |\n| `report-cells-removed` | A linear tag with no `tiles`, the retired cell format, so the file is no report. List its tiles (`reference/linear.md`) |\n| `report-on-surface` | A model `index.malloy` imports (or `explores` lists) is tagged, so its sources left the surface. Untag it, or move the report out |\n| `index-is-not-a-report` | The root `index.malloy` carries a tag. Remove it; put the report in its own file |\n| `Tile … reads <source>, which index.malloy doesn't export` | Add the source to the `export { ... }` in `index.malloy`. Never add an `explores` to `publisher.json` |\n| A grid's `columns`, `colspan`, or `dashboard_columns=` findings | `reference/grid.md` |\n| Prose the reader cannot place (`notebook-markdown-attached-nowhere`, `notebook-markdown-block-unnamed`) | `reference/linear.md` |\n\n**Read the status the reload itself returns, not the listing.** One report that fails to compile fails the whole package load (424), and a package already serving keeps its previous version, so the listing still looks healthy. `GET /api/v0/status` still knows: a package serving an older model than its files appears in `loadErrors` with `stale: true`. If the reload is 200 and your report is not listed, first check that the package is not a published version: a version (its resource carries a `versionId`; the reload tool says `mode: unchanged`) answers a reload with 200 and never reads your file. Otherwise discovery skipped it: usually a missing or misspelled artifact tag, or a file under `public/`.\n\n**A clean reload is not proof the tags are right.** The parse warning is syntax only and carries no position. That is why the last step is opening the page.\n\n## Template\n\n```malloy\n##! experimental.givens\n##\" [One-line description of the report.]\n##| artifact { layout=linear title=\"[Title]\"\n tiles=[\n intro { kind=text },\n \"main_source_tiles -> broad_tile\",\n \"main_source_tiles -> drill_tile\"\n ]\n}\n|##\nimport { main_source } from \"model.malloy\"\n\n##|(markdown) intro\n[Framing question: what are we trying to understand?]\n|##\n\nsource: main_source_tiles is main_source extend {\n view: broad_tile is [broad view]\n view: drill_tile is [drill view]\n}\n```\n\nFor a grid, write `layout=grid`, add `dashboard { columns=12 }` after the tag's closing `}`, and give every tile view a `# colspan` (`reference/grid.md`).\n\n## Editing in the Console\n\nA person can open any report in the Console's builder (**Edit** on the report page; **+ Report** on the package page writes `<slug>.malloy` at the package root). The builder splices the file rather than regenerating it, so comments and anything it does not model survive; it never rewrites `layout=`, so the layout is set in the file. A file written as `run:` cells, the retired linear form, is no report and does not open (`reference/linear.md`). A save whose text declares a real `#(authorize)` or `#(access_filter)` gate outside prose is refused with a 400: gates live in a model file the report imports.\n\n## What \"done\" means\n\n- The file is at the package root (or where the author asked), and its tag says `layout=`.\n- Every source, view, and field name came from the model you read in step 1.\n- The reload returned **200**, not 424, with **zero** report warnings, and your report is in `GET …/reports`.\n- You opened the page and every tile shows real numbers: not stuck loading, not an error, not an empty state you did not intend.\n- Each control renders as the widget you intended, and changing one changes the numbers.\n- If you added a `# drill`, its `to=` is a path, and you clicked it and landed where you meant to, with the given seeded.\n- On a grid: every tile carries a colspan, each row sums to `columns`, rows end flush, nothing is clipped, and no legend or card label ends in `…`.\n\n## Reference\n\n- `reference/grid.md`: the grid recipe, its traps, and one query as the whole page.\n- `reference/linear.md`: linear reports, rewriting a retired `run:`-cell file or a `.malloynb`, style, and common mistakes.\n- `docs/reports.md`: the full guide this skill condenses.\n- `docs/givens.md`: the givens the controls are generated from.\n\n## Reference files over MCP\n\nThis skill's `reference/` files are served as separate prompts, one per file, fetched only when you ask for them. Where the text above says to read `reference/<name>.md`, get the prompt named `malloy-reports/<name>` instead.\n\nAvailable: grid, linear."
|
|
211879
212164
|
},
|
|
211880
212165
|
{
|
|
211881
212166
|
name: "malloy-reports/grid",
|
|
@@ -211968,9 +212253,7 @@ One query per tile, and remember a chart renders only the **first** aggregate in
|
|
|
211968
212253
|
|
|
211969
212254
|
## Existing \`.malloynb\` files
|
|
211970
212255
|
|
|
211971
|
-
A \`.malloynb\` (cells delimited by \`>>>markdown\` and \`>>>malloy\`) is a deprecated format
|
|
211972
|
-
|
|
211973
|
-
Each code cell runs its \`run:\` statement as query text on the notebook's path, over REST with \`POST …/models/{path}/query\` and in the \`show_report\` panel. MCP \`execute_query\` does not take a \`.malloynb\` path and answers that the model is not found, so to check a cell's query there, run it against the \`model_path\` that \`get_context\` returns, which is \`index.malloy\` when the package has one; a model file the surface does not publish answers not found. The \`run:\` runs in restricted mode: it may not call a \`sql_*\` function or read a table directly, such as \`duckdb.table(…)\`; put either in a source in a cell and run that source. A join written in the \`run:\` is the caller's join, so a gate on the joined source applies to it. On a package with an \`index.malloy\`, a source the cells declare is not queryable, even over a published source; declare it in a model file and export it from \`index.malloy\`.
|
|
212256
|
+
A \`.malloynb\` (cells delimited by \`>>>markdown\` and \`>>>malloy\`) is a deprecated format. **Do not create one.** To change one, rewrite it as a \`.malloy\` linear report beside it: each query cell a query tile, each markdown cell a text tile.
|
|
211974
212257
|
|
|
211975
212258
|
## Common mistakes
|
|
211976
212259
|
|
|
@@ -212191,7 +212474,7 @@ This review covers 10,173 lines across 47 files. Only ~1,500 lines were deep-rev
|
|
|
212191
212474
|
{
|
|
212192
212475
|
name: "malloy-review/rubric-structure",
|
|
212193
212476
|
description: "Rubric: Structure. Reference detail for the malloy-review skill.",
|
|
212194
|
-
body: "# Rubric: Structure\n\n**Dimension:** `structure`\n**Rules:** 5\n\nApplies to the organization of `.malloy` files within a package. Skip a file for structural review if it's a report (a `.malloy` file anywhere in the package whose model-level notes carry an `## artifact` tag, of either layout, `layout=grid` or `layout=linear` or the deprecated `kind=`, written as `tiles=[…]`; a legacy query-level `# artifact` on a `query
|
|
212477
|
+
body: "# Rubric: Structure\n\n**Dimension:** `structure`\n**Rules:** 5\n\nApplies to the organization of `.malloy` files within a package. Skip a file for structural review if it's a report (a `.malloy` file anywhere in the package whose model-level notes carry an `## artifact` tag, of either layout, `layout=grid` or `layout=linear` or the deprecated `kind=`, written as `tiles=[…]`; or a legacy query-level `# artifact` on a `query:`), which has its own conventions (the `malloy-reports` skill), or a one-off sandbox script. Do not flag a report for where it sits: no directory is required for one, and the package root is the default.\n\nFor every rule, the linked instruction-skill section is the canonical source for rationale and examples.\n\n---\n\n## S-01: Base vs joined source separation\n\n- **Severity:** major (non-blocking) · **Category:** structure · LLM-judgment\n- **Detection:** LLM heuristic, a source named after a base table (`customers`, `orders`) that includes cross-table joins, or a file with multiple sources where one clearly joins the others, is a candidate for splitting\n- **Fix:** move the joined source into its own file; leave the base source clean\n- **See:** `skill:malloy-model` § Base vs Joined Sources · `skill:malloy-model` § Joined Source File Template\n\n---\n\n## S-02: Sources should declare `primary_key:` when one exists\n\n- **Severity:** minor (non-blocking) · **Category:** structure · machine-checkable\n- **Why this isn't a correctness rule.** The Malloy compiler auto-synthesizes a UUID-based `__distinct_key` for any `join_one:` target without a declared PK (`packages/malloy/src/model/field_instance.ts:644-670`, `query_query.ts:946-951`), so symmetric aggregation is correct either way, see the C-07 entry in `rubric-correctness.md`'s \"Rules we dropped\" section. The `with` shortcut, which DOES require a declared PK, errors at compile time and surfaces as a diagnostic. The actual silent-correctness hazard (\"declared PK isn't actually unique in the data\") is `rubric-correctness.md` § C-12.\n- **What this rule catches.** A discoverability / hygiene gap: when a source has a natural primary key, declaring it lets downstream code use the `with` shortcut, makes grain explicit in the model, and gives tooling a stable identifier per row. Treat as a recommendation, not a merge gate.\n- **Detection:** for every `source:` declaration, check whether its body contains a `primary_key:` clause. Skip flagging when:\n - The source is a query-based / computed source (`source: x is t -> {...}` or `source: x is (t -> {...}) extend {...}`) where grain is determined by the `group_by` columns, declaring a `primary_key:` on the result is fine but not required.\n - The source represents an event/log table or a denormalized analytical source where no natural PK exists. Both situations are legitimate; the LLM should recognize them and skip the finding.\n- **Fix (when the source does have a natural PK):** declare it, `primary_key: <col>` inside `extend {}`. When there isn't a natural PK, leave it undeclared; if the absence is non-obvious, a one-line `#(doc)` on the source explaining the grain helps future readers.\n- **See:** `skill:malloy-model` § Key Rules · `rubric-correctness.md` § C-12 (the related correctness rule that checks whether a declared PK is actually unique in the data) · `rubric-style.md` § Y-03 (`join_one:` style consistency, which is the other consequence of declared-vs-undeclared PKs)\n\n---\n\n## S-03: Joined tables defined before the source that references them\n\n- **Severity:** blocker (blocking) · **Category:** structure · machine-checkable\n- **Detection:** AST, within a single file, for each source reference inside a `join_*:` or `source is <name>`, verify the target source is declared earlier\n- **Fix:** reorder source declarations so dependencies come first. If two sources reference each other, split into separate files with explicit `import` (cross-file declarations don't have this ordering constraint).\n- **See:** `skill:malloy-gotchas-modeling` § Source Order, Define Joined Tables First\n\n---\n\n## S-04: Base sources curate their column surface\n\n- **Severity:** major (non-blocking) · **Category:** structure · machine-checkable\n- **Detection:** AST, for each `source: ... is conn.table(...)` declaration (a direct-table base source), check whether the source uses **any** of the three column-curation mechanisms below. The finding fires only when the source uses none of them, every column from the underlying table is implicitly public. Query-based sources and sources derived from other sources are exempt.\n- **Fix:** pick whichever option matches the source's needs. Curation options, lightest to heaviest:\n 1. `extend { except: a, b, c }`, drop a small named set of columns. Compatible with `rename:`. No experimental flag.\n 2. `extend { accept: a, b, c }`, keep only a small named set. Compatible with `rename:`. No experimental flag.\n 3. `##! experimental.access_modifiers` + `include { public: …, internal: …, private: … }`, full per-column visibility tiers. **Composes with `rename:` in one order only** (the `extend { rename: }` before the `include {}`, which then names the field by its new name) and disallows measures/dimensions whose names shadow `internal:` columns. Use only when the visibility distinction matters (e.g., shared sources joined into multiple consumers).\n\n Most files only need option 1 or 2, for the small set of columns that shouldn't be public, prefer `except:` over the heavier `include {}` machinery. Reach for `include {}` only when per-column tiers are genuinely worth the constraints.\n- **See:** `skill:malloy-gotchas-modeling` § Field Management: `extend {}` and `include {}`, in that order · `skill:malloy-model` § Base Source Templates · `malloy-model/reference/access-modifiers.md`\n\n---\n\n## S-05: One file per table (base) / one per analytical domain (joined)\n\n- **Severity:** minor (non-blocking) · **Category:** structure · machine-checkable\n- **Detection:** count `source: X is conn.table(...)` base-source declarations per file. More than one → flag.\n- **Fix:** split each base source into its own file named after the source\n- **See:** `skill:malloy-model` § Base Source Templates (file convention is implicit; weak counterpart)\n\n---\n\n## Cross-cutting note\n\nWhen a file violates both S-01 (base+joined mixed) and S-05 (multiple base sources), surface the combined observation as a **Cross-Cutting Theme** in the review output: \"File layout suggests a restructure, see S-series findings for suggested splits.\""
|
|
212195
212478
|
},
|
|
212196
212479
|
{
|
|
212197
212480
|
name: "malloy-review/rubric-style",
|
|
@@ -212594,7 +212877,7 @@ function compareText(a, b) {
|
|
|
212594
212877
|
// src/service/package_revision.ts
|
|
212595
212878
|
import { createHash as createHash13, randomUUID as randomUUID4 } from "crypto";
|
|
212596
212879
|
import fs14 from "fs";
|
|
212597
|
-
import
|
|
212880
|
+
import path32 from "path";
|
|
212598
212881
|
import { pathToFileURL as pathToFileURL14 } from "url";
|
|
212599
212882
|
function computeSourceContentSha(packagePath, contentPaths, extra, contentShas) {
|
|
212600
212883
|
const hash = createHash13("sha256");
|
|
@@ -212605,7 +212888,7 @@ function computeSourceContentSha(packagePath, contentPaths, extra, contentShas)
|
|
|
212605
212888
|
if (precomputed !== undefined) {
|
|
212606
212889
|
hash.update(`\x00sha256\x00${precomputed}`);
|
|
212607
212890
|
} else {
|
|
212608
|
-
const absolute =
|
|
212891
|
+
const absolute = path32.join(packagePath, relativePath);
|
|
212609
212892
|
try {
|
|
212610
212893
|
hash.update(fs14.readFileSync(confinedPackagePathSync(packagePath, pathToFileURL14(absolute))));
|
|
212611
212894
|
} catch {
|
|
@@ -212645,7 +212928,7 @@ var init_package_revision = __esm(() => {
|
|
|
212645
212928
|
// src/service/skills/package_skills.ts
|
|
212646
212929
|
import { createHash as createHash14 } from "crypto";
|
|
212647
212930
|
import * as fs15 from "fs";
|
|
212648
|
-
import * as
|
|
212931
|
+
import * as path33 from "path";
|
|
212649
212932
|
import { pathToFileURL as pathToFileURL15 } from "url";
|
|
212650
212933
|
function insidePackage(packageRoot, p) {
|
|
212651
212934
|
try {
|
|
@@ -212714,7 +212997,7 @@ function readFileInside(packageRoot, file, maxBytes, asset = false) {
|
|
|
212714
212997
|
}
|
|
212715
212998
|
function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
212716
212999
|
try {
|
|
212717
|
-
if (insidePackage(packageRoot,
|
|
213000
|
+
if (insidePackage(packageRoot, path33.join(skillDir, "reference")) === undefined) {
|
|
212718
213001
|
warnings.push(`Package skill reference directory '${rel}/reference' resolves outside the package through a link, so it is not served. Fix: copy the files into the package.`);
|
|
212719
213002
|
return [];
|
|
212720
213003
|
}
|
|
@@ -212727,7 +213010,7 @@ function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
|
212727
213010
|
}
|
|
212728
213011
|
}
|
|
212729
213012
|
function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
212730
|
-
const root =
|
|
213013
|
+
const root = path33.join(packagePath, dirRel);
|
|
212731
213014
|
const skills = [];
|
|
212732
213015
|
const files = [];
|
|
212733
213016
|
const warnings = [];
|
|
@@ -212741,7 +213024,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212741
213024
|
let escapes;
|
|
212742
213025
|
try {
|
|
212743
213026
|
fs15.realpathSync(packagePath);
|
|
212744
|
-
packageRoot =
|
|
213027
|
+
packageRoot = path33.resolve(packagePath);
|
|
212745
213028
|
const inside = insidePackage(packageRoot, root);
|
|
212746
213029
|
escapes = inside === undefined;
|
|
212747
213030
|
if (inside !== undefined) {
|
|
@@ -212762,7 +213045,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212762
213045
|
for (const entry of [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
|
|
212763
213046
|
if (entry.name.startsWith("."))
|
|
212764
213047
|
continue;
|
|
212765
|
-
const skillDir =
|
|
213048
|
+
const skillDir = path33.join(root, entry.name);
|
|
212766
213049
|
const skillInside = insidePackage(packageRoot, skillDir);
|
|
212767
213050
|
if (skillInside !== undefined) {
|
|
212768
213051
|
try {
|
|
@@ -212773,7 +213056,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212773
213056
|
}
|
|
212774
213057
|
}
|
|
212775
213058
|
const rel = `${dirRel}/${entry.name}`;
|
|
212776
|
-
const read = readFileInside(packageRoot,
|
|
213059
|
+
const read = readFileInside(packageRoot, path33.join(skillDir, "SKILL.md"), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212777
213060
|
if ("problem" in read) {
|
|
212778
213061
|
unserved(`Package skill '${rel}/SKILL.md' ${read.problem}, so it is not served. Fix: add a readable SKILL.md inside the package, or remove the directory.`);
|
|
212779
213062
|
continue;
|
|
@@ -212791,7 +213074,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212791
213074
|
const served = [];
|
|
212792
213075
|
for (const file of referenceFilesInside(packageRoot, skillDir, rel, warnings)) {
|
|
212793
213076
|
const relative = `${rel}/reference/${file}`;
|
|
212794
|
-
const ref = readFileInside(packageRoot,
|
|
213077
|
+
const ref = readFileInside(packageRoot, path33.join(skillDir, "reference", file), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212795
213078
|
if ("problem" in ref) {
|
|
212796
213079
|
warnings.push(`Package skill reference '${relative}' ${ref.problem}, so it is not served.`);
|
|
212797
213080
|
continue;
|
|
@@ -212814,13 +213097,13 @@ function agentPath(value, what) {
|
|
|
212814
213097
|
if (typeof value !== "string" || value === "" || value.includes("\x00")) {
|
|
212815
213098
|
throw new AgentProblem(`${what} must be a non-empty package-relative path`);
|
|
212816
213099
|
}
|
|
212817
|
-
if (
|
|
213100
|
+
if (path33.posix.isAbsolute(value) || path33.win32.isAbsolute(value)) {
|
|
212818
213101
|
throw new AgentProblem(`${what} '${value}' is an absolute path`);
|
|
212819
213102
|
}
|
|
212820
213103
|
if (value.includes("\\")) {
|
|
212821
213104
|
throw new AgentProblem(`${what} '${value}' contains a backslash; write it with forward slashes`);
|
|
212822
213105
|
}
|
|
212823
|
-
const normalized =
|
|
213106
|
+
const normalized = path33.posix.normalize(value).replace(/\/+$/, "");
|
|
212824
213107
|
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
212825
213108
|
throw new AgentProblem(`${what} '${value}' is outside the package`);
|
|
212826
213109
|
}
|
|
@@ -212843,7 +213126,7 @@ function servedTreeHoldsManifest(packageRoot, root) {
|
|
|
212843
213126
|
const inside = insidePackage(packageRoot, root);
|
|
212844
213127
|
if (inside === undefined)
|
|
212845
213128
|
return false;
|
|
212846
|
-
return fs15.readdirSync(inside, { withFileTypes: true }).some((e) => (e.isDirectory() || e.isSymbolicLink()) && (holdsManifest(packageRoot,
|
|
213129
|
+
return fs15.readdirSync(inside, { withFileTypes: true }).some((e) => (e.isDirectory() || e.isSymbolicLink()) && (holdsManifest(packageRoot, path33.join(root, e.name)) || holdsManifest(packageRoot, path33.join(root, e.name, "reference"))));
|
|
212847
213130
|
} catch {
|
|
212848
213131
|
return false;
|
|
212849
213132
|
}
|
|
@@ -212853,12 +213136,12 @@ function readAgentText(packagePath, packageRoot, value, what) {
|
|
|
212853
213136
|
if (!rel.toLowerCase().endsWith(".md")) {
|
|
212854
213137
|
throw new AgentProblem(`${what} '${rel}' is not a .md file`);
|
|
212855
213138
|
}
|
|
212856
|
-
for (let dir =
|
|
212857
|
-
if (holdsManifest(packageRoot,
|
|
213139
|
+
for (let dir = path33.posix.dirname(rel);dir !== "."; dir = path33.posix.dirname(dir)) {
|
|
213140
|
+
if (holdsManifest(packageRoot, path33.join(packagePath, dir))) {
|
|
212858
213141
|
throw new AgentProblem(`${what} '${rel}' sits under a nested publisher.json at '${dir}'`);
|
|
212859
213142
|
}
|
|
212860
213143
|
}
|
|
212861
|
-
const read = readFileInside(packageRoot,
|
|
213144
|
+
const read = readFileInside(packageRoot, path33.join(packagePath, rel), PACKAGE_AGENT_TEXT_MAX_BYTES);
|
|
212862
213145
|
if ("problem" in read) {
|
|
212863
213146
|
throw new AgentProblem(`${what} '${rel}' ${read.problem}`);
|
|
212864
213147
|
}
|
|
@@ -212917,7 +213200,7 @@ function readAgentBudget(raw) {
|
|
|
212917
213200
|
return Object.keys(budget).length > 0 ? budget : undefined;
|
|
212918
213201
|
}
|
|
212919
213202
|
function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
212920
|
-
const assetsDir =
|
|
213203
|
+
const assetsDir = path33.join(skillDir, "assets");
|
|
212921
213204
|
const realSkillDir = insidePackage(packageRoot, skillDir);
|
|
212922
213205
|
if (realSkillDir === undefined) {
|
|
212923
213206
|
throw new AgentProblem(`'${skillRel}' resolves outside the package`);
|
|
@@ -212926,13 +213209,13 @@ function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
|
212926
213209
|
throw new AgentProblem(`'${skillRel}/assets' is a link; replace it with a real directory`);
|
|
212927
213210
|
}
|
|
212928
213211
|
const real = fs15.realpathSync(assetsDir);
|
|
212929
|
-
if (real !==
|
|
213212
|
+
if (real !== path33.join(realSkillDir, "assets")) {
|
|
212930
213213
|
throw new AgentProblem(`'${skillRel}/assets' resolves outside the skill's own directory`);
|
|
212931
213214
|
}
|
|
212932
213215
|
return assetsDir;
|
|
212933
213216
|
}
|
|
212934
213217
|
function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk) {
|
|
212935
|
-
const assetsDir =
|
|
213218
|
+
const assetsDir = path33.join(skillDir, "assets");
|
|
212936
213219
|
let link;
|
|
212937
213220
|
try {
|
|
212938
213221
|
link = fs15.lstatSync(assetsDir);
|
|
@@ -212996,7 +213279,7 @@ function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk)
|
|
|
212996
213279
|
skip(shown, `its path is over ${ASSET_PATH_MAX_CHARS} characters`);
|
|
212997
213280
|
continue;
|
|
212998
213281
|
}
|
|
212999
|
-
const absolute =
|
|
213282
|
+
const absolute = path33.join(dir, entry.name);
|
|
213000
213283
|
if (entry.isDirectory()) {
|
|
213001
213284
|
if (depth >= ASSET_MAX_DEPTH) {
|
|
213002
213285
|
skip(shown, `it is nested deeper than ${ASSET_MAX_DEPTH} levels`);
|
|
@@ -213068,8 +213351,8 @@ function readAgentAsset(packagePath, agent, relativeFilepath) {
|
|
|
213068
213351
|
if (skillRel === undefined || !listing)
|
|
213069
213352
|
return;
|
|
213070
213353
|
try {
|
|
213071
|
-
const skillDir =
|
|
213072
|
-
const read = readFileInside(realAssetsDir(packagePath, skillDir, skillRel),
|
|
213354
|
+
const skillDir = path33.join(packagePath, skillRel);
|
|
213355
|
+
const read = readFileInside(realAssetsDir(packagePath, skillDir, skillRel), path33.join(skillDir, relativeFilepath.slice(skill.length)), PACKAGE_ASSET_FILE_MAX_BYTES - 1, true);
|
|
213073
213356
|
if (!("text" in read))
|
|
213074
213357
|
return;
|
|
213075
213358
|
return createHash14("sha256").update(read.text).digest("hex") === listing.sha256 ? read.text : undefined;
|
|
@@ -213098,7 +213381,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213098
213381
|
};
|
|
213099
213382
|
let bytes = 0;
|
|
213100
213383
|
for (const root of roots) {
|
|
213101
|
-
const rootInside = insidePackage(packageRoot,
|
|
213384
|
+
const rootInside = insidePackage(packageRoot, path33.join(packagePath, root));
|
|
213102
213385
|
if (rootInside === undefined) {
|
|
213103
213386
|
throw new AgentProblem(`skills directory '${root}' resolves outside the package`);
|
|
213104
213387
|
}
|
|
@@ -213109,8 +213392,8 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213109
213392
|
} catch {
|
|
213110
213393
|
throw new AgentProblem(`skills directory '${root}' does not exist`);
|
|
213111
213394
|
}
|
|
213112
|
-
for (let dir = root;dir !== "."; dir =
|
|
213113
|
-
const holds = dir === root ? servedTreeHoldsManifest(packageRoot,
|
|
213395
|
+
for (let dir = root;dir !== "."; dir = path33.posix.dirname(dir)) {
|
|
213396
|
+
const holds = dir === root ? servedTreeHoldsManifest(packageRoot, path33.join(packagePath, dir)) : holdsManifest(packageRoot, path33.join(packagePath, dir));
|
|
213114
213397
|
if (holds) {
|
|
213115
213398
|
throw new AgentProblem(`skills directory '${root}' contains a nested publisher.json`);
|
|
213116
213399
|
}
|
|
@@ -213149,7 +213432,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213149
213432
|
}
|
|
213150
213433
|
for (const skill of skillNames) {
|
|
213151
213434
|
const skillRel = `${root}/${skill}`;
|
|
213152
|
-
const listed = assetFilesInside(packageRoot,
|
|
213435
|
+
const listed = assetFilesInside(packageRoot, path33.join(packagePath, skillRel), skillRel, skill, assetBudget, walk);
|
|
213153
213436
|
for (const asset of listed) {
|
|
213154
213437
|
assets.set(asset.relative_filepath, asset);
|
|
213155
213438
|
assetRoots.set(skill, skillRel);
|
|
@@ -213263,7 +213546,7 @@ function readPackageAgents(packagePath, raw) {
|
|
|
213263
213546
|
let packageRoot;
|
|
213264
213547
|
try {
|
|
213265
213548
|
fs15.realpathSync(packagePath);
|
|
213266
|
-
packageRoot =
|
|
213549
|
+
packageRoot = path33.resolve(packagePath);
|
|
213267
213550
|
} catch {
|
|
213268
213551
|
return result;
|
|
213269
213552
|
}
|
|
@@ -215215,7 +215498,7 @@ var init_esm2 = __esm(() => {
|
|
|
215215
215498
|
// src/service/configured_publish_retry.ts
|
|
215216
215499
|
import { createHash as createHash15 } from "crypto";
|
|
215217
215500
|
import * as fs16 from "fs";
|
|
215218
|
-
import * as
|
|
215501
|
+
import * as path34 from "path";
|
|
215219
215502
|
function backoffAfter(failures) {
|
|
215220
215503
|
if (failures <= 0)
|
|
215221
215504
|
return 0;
|
|
@@ -215226,13 +215509,13 @@ async function localPackageFingerprint(root) {
|
|
|
215226
215509
|
const walk = async (dir) => {
|
|
215227
215510
|
const entries = await fs16.promises.readdir(dir, { withFileTypes: true });
|
|
215228
215511
|
for (const entry of entries) {
|
|
215229
|
-
const full =
|
|
215512
|
+
const full = path34.join(dir, entry.name);
|
|
215230
215513
|
if (entry.isDirectory()) {
|
|
215231
215514
|
if (!SKIPPED_DIRS.has(entry.name))
|
|
215232
215515
|
await walk(full);
|
|
215233
215516
|
} else if (entry.isFile() && FINGERPRINTED.test(entry.name)) {
|
|
215234
215517
|
const stat = await fs16.promises.stat(full);
|
|
215235
|
-
lines.push(`${
|
|
215518
|
+
lines.push(`${path34.relative(root, full)}\x00${stat.size}\x00${stat.mtimeMs}`);
|
|
215236
215519
|
}
|
|
215237
215520
|
}
|
|
215238
215521
|
};
|
|
@@ -368692,8 +368975,12 @@ var init_dim_index_entity_id = __esm(() => {
|
|
|
368692
368975
|
});
|
|
368693
368976
|
|
|
368694
368977
|
// src/service/entities/source_extraction.ts
|
|
368695
|
-
import
|
|
368978
|
+
import path35 from "path";
|
|
368696
368979
|
import { fileURLToPath as fileURLToPath14 } from "url";
|
|
368980
|
+
import {
|
|
368981
|
+
isJoined as isJoined7,
|
|
368982
|
+
isJoinedSource
|
|
368983
|
+
} from "@malloydata/malloy";
|
|
368697
368984
|
function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
368698
368985
|
const sourceToModelPath = new Map;
|
|
368699
368986
|
for (const explore of explores) {
|
|
@@ -368707,7 +368994,7 @@ function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
|
368707
368994
|
if (fullPath.startsWith(packageRoot)) {
|
|
368708
368995
|
modelPath = fullPath.slice(packageRoot.length).replace(/^[/\\]/, "");
|
|
368709
368996
|
} else {
|
|
368710
|
-
modelPath =
|
|
368997
|
+
modelPath = path35.basename(fullPath);
|
|
368711
368998
|
}
|
|
368712
368999
|
} else {
|
|
368713
369000
|
modelPath = url;
|
|
@@ -368739,6 +369026,17 @@ function parseJoinCode(joinCode, fieldName, sourceToModelPath) {
|
|
|
368739
369026
|
is_nested_index: isNestedIndex
|
|
368740
369027
|
};
|
|
368741
369028
|
}
|
|
369029
|
+
function joinMetadataOf(field, docString, sourceToModelPath) {
|
|
369030
|
+
const structDef = field.structDef;
|
|
369031
|
+
const metadata = isJoinedSource(structDef) ? parseJoinCode(extractCodeFromEntity(field, docString), field.name, sourceToModelPath) : {
|
|
369032
|
+
original_source_name: null,
|
|
369033
|
+
original_source_path: null,
|
|
369034
|
+
is_nested_index: true
|
|
369035
|
+
};
|
|
369036
|
+
if (isJoined7(structDef))
|
|
369037
|
+
metadata.relationship = structDef.join;
|
|
369038
|
+
return metadata;
|
|
369039
|
+
}
|
|
368742
369040
|
function descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary) {
|
|
368743
369041
|
const targetName = joinMetadata.original_source_name;
|
|
368744
369042
|
const targetIsAtTopLevel = targetName != null && topLevelExploreNames.has(targetName);
|
|
@@ -368749,7 +369047,7 @@ function descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, bo
|
|
|
368749
369047
|
function joinDescent(explores, relativePath, packageRoot, docString, boundary) {
|
|
368750
369048
|
const sourceToModelPath = buildSourceToModelPathMap(explores, relativePath, packageRoot);
|
|
368751
369049
|
const topLevelExploreNames = new Set(explores.map((e) => e.name));
|
|
368752
|
-
return (join, parentSourceName) => descendsIntoJoin(
|
|
369050
|
+
return (join, parentSourceName) => descendsIntoJoin(joinMetadataOf(join, docString, sourceToModelPath), parentSourceName.split(".")[0], topLevelExploreNames, boundary);
|
|
368753
369051
|
}
|
|
368754
369052
|
function getEntitiesFromExplore(explore, docString, relativePath, parentPath, sourceToModelPath, dimIndexFingerprints, topLevelExploreNames, boundary, guard) {
|
|
368755
369053
|
const entities = [];
|
|
@@ -368761,8 +369059,7 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
|
|
|
368761
369059
|
}
|
|
368762
369060
|
let joinMetadata = null;
|
|
368763
369061
|
if (field.isExploreField()) {
|
|
368764
|
-
|
|
368765
|
-
joinMetadata = parseJoinCode(joinCode, field.name, sourceToModelPath);
|
|
369062
|
+
joinMetadata = joinMetadataOf(field, docString, sourceToModelPath);
|
|
368766
369063
|
const descent = descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary);
|
|
368767
369064
|
if (descent !== false) {
|
|
368768
369065
|
const nestedEntities = getEntitiesFromExplore(field, docString, relativePath, sourceName, sourceToModelPath, dimIndexFingerprints, topLevelExploreNames, boundary, descent === true ? guard : guardDescent(guard, rootSourceName, descent.unlessQueryable));
|
|
@@ -368798,8 +369095,7 @@ function planJoinAuthorizeMetadata(explore, docString, relativePath, parentPath,
|
|
|
368798
369095
|
}
|
|
368799
369096
|
if (getAccessModifier(field) !== "public" /* Public */)
|
|
368800
369097
|
continue;
|
|
368801
|
-
const
|
|
368802
|
-
const joinMetadata = parseJoinCode(joinCode, field.name, sourceToModelPath);
|
|
369098
|
+
const joinMetadata = joinMetadataOf(field, docString, sourceToModelPath);
|
|
368803
369099
|
const targetName = joinMetadata.original_source_name;
|
|
368804
369100
|
const descent = descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary);
|
|
368805
369101
|
const joinedExplore = field;
|
|
@@ -369536,7 +369832,8 @@ function toApiField(entity) {
|
|
|
369536
369832
|
},
|
|
369537
369833
|
...join.original_source_path != null && {
|
|
369538
369834
|
sourcePath: join.original_source_path
|
|
369539
|
-
}
|
|
369835
|
+
},
|
|
369836
|
+
...join.relationship && { relationship: join.relationship }
|
|
369540
369837
|
};
|
|
369541
369838
|
}
|
|
369542
369839
|
if (entity.dim_index_fingerprint) {
|
|
@@ -369791,6 +370088,9 @@ function checkLoadPackageResult(raw) {
|
|
|
369791
370088
|
if (raw.refreshedSchemaKeys !== undefined && !(Array.isArray(raw.refreshedSchemaKeys) && raw.refreshedSchemaKeys.every((key) => typeof key === "string"))) {
|
|
369792
370089
|
throw new PackageLoadProtocolError(`a load-package-result has refreshedSchemaKeys that are not strings`);
|
|
369793
370090
|
}
|
|
370091
|
+
if (raw.fileDigests !== undefined && !(isRecord2(raw.fileDigests) && Object.values(raw.fileDigests).every((d) => typeof d === "string"))) {
|
|
370092
|
+
throw new PackageLoadProtocolError(`a load-package-result has fileDigests that are not strings`);
|
|
370093
|
+
}
|
|
369794
370094
|
for (const model of raw.models)
|
|
369795
370095
|
decodeSerializedModel(model);
|
|
369796
370096
|
return raw;
|
|
@@ -370634,7 +370934,8 @@ function adaptResult(result) {
|
|
|
370634
370934
|
})),
|
|
370635
370935
|
loadDurationMs: result.loadDurationMs,
|
|
370636
370936
|
timings: result.timings,
|
|
370637
|
-
buildPlan: result.buildPlan
|
|
370937
|
+
buildPlan: result.buildPlan,
|
|
370938
|
+
...result.fileDigests ? { fileDigests: result.fileDigests } : {}
|
|
370638
370939
|
};
|
|
370639
370940
|
}
|
|
370640
370941
|
function currentPackageLoadPool() {
|
|
@@ -370670,11 +370971,221 @@ var init_package_load_pool = __esm(() => {
|
|
|
370670
370971
|
};
|
|
370671
370972
|
});
|
|
370672
370973
|
|
|
370673
|
-
// src/
|
|
370974
|
+
// src/package_load/job_files.ts
|
|
370975
|
+
import {
|
|
370976
|
+
CacheManager,
|
|
370977
|
+
InMemoryModelCache
|
|
370978
|
+
} from "@malloydata/malloy";
|
|
370674
370979
|
import { createHash as createHash17 } from "crypto";
|
|
370980
|
+
import * as path36 from "path";
|
|
370981
|
+
import { fileURLToPath as fileURLToPath16, pathToFileURL as pathToFileURL18 } from "url";
|
|
370982
|
+
function jobFiles(inner) {
|
|
370983
|
+
const texts = new Map;
|
|
370984
|
+
const stylesByUrl = new Map;
|
|
370985
|
+
const reads = new Map;
|
|
370986
|
+
const reader = {
|
|
370987
|
+
readURL: (url) => {
|
|
370988
|
+
const key = url.toString();
|
|
370989
|
+
let read = reads.get(key);
|
|
370990
|
+
if (!read) {
|
|
370991
|
+
read = (async () => {
|
|
370992
|
+
const contents = await inner.readURL(url);
|
|
370993
|
+
texts.set(key, contents);
|
|
370994
|
+
stylesByUrl.set(key, await dataStylesForFile(key, contents, inner));
|
|
370995
|
+
return contents;
|
|
370996
|
+
})();
|
|
370997
|
+
reads.set(key, read);
|
|
370998
|
+
read.catch(() => reads.delete(key));
|
|
370999
|
+
}
|
|
371000
|
+
return read;
|
|
371001
|
+
}
|
|
371002
|
+
};
|
|
371003
|
+
return {
|
|
371004
|
+
reader,
|
|
371005
|
+
texts,
|
|
371006
|
+
stylesByUrl,
|
|
371007
|
+
models: new Map,
|
|
371008
|
+
imported: new Set,
|
|
371009
|
+
stats: { stored: 0, reused: 0 }
|
|
371010
|
+
};
|
|
371011
|
+
}
|
|
371012
|
+
function urlKey(url) {
|
|
371013
|
+
try {
|
|
371014
|
+
return new URL(url).href;
|
|
371015
|
+
} catch {
|
|
371016
|
+
return url;
|
|
371017
|
+
}
|
|
371018
|
+
}
|
|
371019
|
+
function decodedUrl(url) {
|
|
371020
|
+
try {
|
|
371021
|
+
return decodeURI(url);
|
|
371022
|
+
} catch {
|
|
371023
|
+
return url;
|
|
371024
|
+
}
|
|
371025
|
+
}
|
|
371026
|
+
function modelFileTexts(files, modelUrl, dependencies) {
|
|
371027
|
+
const byPath = new Map;
|
|
371028
|
+
for (const url of [modelUrl, ...importReadOrder(dependencies)]) {
|
|
371029
|
+
const key = urlKey(url);
|
|
371030
|
+
const text = files.texts.get(key);
|
|
371031
|
+
if (text !== undefined && key.startsWith("file:")) {
|
|
371032
|
+
byPath.set(fileURLToPath16(key), text);
|
|
371033
|
+
}
|
|
371034
|
+
}
|
|
371035
|
+
return byPath;
|
|
371036
|
+
}
|
|
371037
|
+
function fileTextDigests(files) {
|
|
371038
|
+
const digests = {};
|
|
371039
|
+
for (const [url, text] of files.texts) {
|
|
371040
|
+
const key = urlKey(url);
|
|
371041
|
+
if (!key.startsWith("file:"))
|
|
371042
|
+
continue;
|
|
371043
|
+
digests[key] = createHash17("sha256").update(text).digest("hex");
|
|
371044
|
+
}
|
|
371045
|
+
return digests;
|
|
371046
|
+
}
|
|
371047
|
+
function modelReadKeys(modelUrl, dependencies) {
|
|
371048
|
+
return [modelUrl, ...importReadOrder(dependencies)].map(urlKey);
|
|
371049
|
+
}
|
|
371050
|
+
function dataStylesForModel(files, modelUrl, dependencies) {
|
|
371051
|
+
let styles = {};
|
|
371052
|
+
for (const url of [modelUrl, ...importReadOrder(dependencies)]) {
|
|
371053
|
+
styles = { ...styles, ...files.stylesByUrl.get(urlKey(url)) ?? {} };
|
|
371054
|
+
}
|
|
371055
|
+
return styles;
|
|
371056
|
+
}
|
|
371057
|
+
function importReadOrder(tree) {
|
|
371058
|
+
const order = [];
|
|
371059
|
+
const seen = new Set;
|
|
371060
|
+
const descended = new Set;
|
|
371061
|
+
const visit = (node) => {
|
|
371062
|
+
if (!node || typeof node !== "object")
|
|
371063
|
+
return;
|
|
371064
|
+
const entries = Object.entries(node);
|
|
371065
|
+
for (const [url] of entries) {
|
|
371066
|
+
if (!seen.has(url)) {
|
|
371067
|
+
seen.add(url);
|
|
371068
|
+
order.push(url);
|
|
371069
|
+
}
|
|
371070
|
+
}
|
|
371071
|
+
for (const [url, sub] of entries) {
|
|
371072
|
+
if (descended.has(url))
|
|
371073
|
+
continue;
|
|
371074
|
+
descended.add(url);
|
|
371075
|
+
visit(sub);
|
|
371076
|
+
}
|
|
371077
|
+
};
|
|
371078
|
+
visit(tree);
|
|
371079
|
+
return order;
|
|
371080
|
+
}
|
|
371081
|
+
async function compileOrder(packagePath, modelPaths, reader, imported = new Set) {
|
|
371082
|
+
const malloy = modelPaths.filter((p) => p.endsWith(MODEL_FILE_SUFFIX));
|
|
371083
|
+
const inPackage = new Set(malloy);
|
|
371084
|
+
const imports = new Map;
|
|
371085
|
+
for (const modelPath of malloy) {
|
|
371086
|
+
const url = pathToFileURL18(path36.join(packagePath, modelPath));
|
|
371087
|
+
let text = "";
|
|
371088
|
+
try {
|
|
371089
|
+
text = await reader.readURL(url);
|
|
371090
|
+
} catch {}
|
|
371091
|
+
const deps = [];
|
|
371092
|
+
for (const match of text.matchAll(IMPORT_RE)) {
|
|
371093
|
+
const target = match[1] ?? match[2];
|
|
371094
|
+
if (!target)
|
|
371095
|
+
continue;
|
|
371096
|
+
try {
|
|
371097
|
+
const resolved = new URL(target, url);
|
|
371098
|
+
if (resolved.protocol !== "file:")
|
|
371099
|
+
continue;
|
|
371100
|
+
const rel = path36.relative(packagePath, fileURLToPath16(resolved)).replace(/\\/g, "/");
|
|
371101
|
+
if (inPackage.has(rel)) {
|
|
371102
|
+
deps.push(rel);
|
|
371103
|
+
imported.add(urlKey(resolved.href));
|
|
371104
|
+
}
|
|
371105
|
+
} catch {}
|
|
371106
|
+
}
|
|
371107
|
+
imports.set(modelPath, deps);
|
|
371108
|
+
}
|
|
371109
|
+
const level = new Map;
|
|
371110
|
+
const visiting = new Set;
|
|
371111
|
+
const levelOf = (modelPath) => {
|
|
371112
|
+
const known = level.get(modelPath);
|
|
371113
|
+
if (known !== undefined)
|
|
371114
|
+
return known;
|
|
371115
|
+
if (visiting.has(modelPath))
|
|
371116
|
+
return 0;
|
|
371117
|
+
visiting.add(modelPath);
|
|
371118
|
+
let mine = 0;
|
|
371119
|
+
for (const dep of imports.get(modelPath) ?? []) {
|
|
371120
|
+
mine = Math.max(mine, levelOf(dep) + 1);
|
|
371121
|
+
}
|
|
371122
|
+
visiting.delete(modelPath);
|
|
371123
|
+
level.set(modelPath, mine);
|
|
371124
|
+
return mine;
|
|
371125
|
+
};
|
|
371126
|
+
const levels = [];
|
|
371127
|
+
const waitsOn = new Map;
|
|
371128
|
+
for (const modelPath of malloy) {
|
|
371129
|
+
const mine = levelOf(modelPath);
|
|
371130
|
+
(levels[mine] ??= []).push(modelPath);
|
|
371131
|
+
waitsOn.set(modelPath, (imports.get(modelPath) ?? []).filter((dep) => levelOf(dep) < mine));
|
|
371132
|
+
}
|
|
371133
|
+
const rest = modelPaths.filter((p) => !p.endsWith(MODEL_FILE_SUFFIX));
|
|
371134
|
+
for (const modelPath of rest)
|
|
371135
|
+
waitsOn.set(modelPath, []);
|
|
371136
|
+
return {
|
|
371137
|
+
waitsOn,
|
|
371138
|
+
levels: [
|
|
371139
|
+
...levels.filter((l) => l !== undefined && l.length > 0),
|
|
371140
|
+
...rest.length > 0 ? [rest] : []
|
|
371141
|
+
]
|
|
371142
|
+
};
|
|
371143
|
+
}
|
|
371144
|
+
var sameUrl = (a, b) => a === b || urlKey(a) === urlKey(b), ModelCacheView, IMPORT_RE;
|
|
371145
|
+
var init_job_files = __esm(() => {
|
|
371146
|
+
init_constants();
|
|
371147
|
+
init_data_styles();
|
|
371148
|
+
ModelCacheView = class ModelCacheView extends CacheManager {
|
|
371149
|
+
files;
|
|
371150
|
+
ownUrl;
|
|
371151
|
+
constructor(files, ownUrl) {
|
|
371152
|
+
super(new InMemoryModelCache);
|
|
371153
|
+
this.files = files;
|
|
371154
|
+
this.ownUrl = ownUrl;
|
|
371155
|
+
}
|
|
371156
|
+
async getCachedModelDef(...[, url]) {
|
|
371157
|
+
if (sameUrl(url, this.ownUrl))
|
|
371158
|
+
return;
|
|
371159
|
+
const hit = this.files.models.get(url);
|
|
371160
|
+
if (!hit)
|
|
371161
|
+
return;
|
|
371162
|
+
this.files.stats.reused++;
|
|
371163
|
+
return {
|
|
371164
|
+
modelDef: structuredClone(hit.modelDef),
|
|
371165
|
+
invalidationKeys: { ...hit.invalidationKeys }
|
|
371166
|
+
};
|
|
371167
|
+
}
|
|
371168
|
+
async setCachedModelDef(...[url, cached]) {
|
|
371169
|
+
if (!this.files.imported.has(urlKey(url)))
|
|
371170
|
+
return false;
|
|
371171
|
+
if (sameUrl(url, this.ownUrl) && decodedUrl(url) !== url)
|
|
371172
|
+
return false;
|
|
371173
|
+
this.files.models.set(url, {
|
|
371174
|
+
modelDef: structuredClone(cached.modelDef),
|
|
371175
|
+
invalidationKeys: { ...cached.invalidationKeys }
|
|
371176
|
+
});
|
|
371177
|
+
this.files.stats.stored++;
|
|
371178
|
+
return true;
|
|
371179
|
+
}
|
|
371180
|
+
};
|
|
371181
|
+
IMPORT_RE = /^\s*import\s+(?:\{[^}]*\}\s+from\s+)?(?:"([^"]+)"|'([^']+)')/gim;
|
|
371182
|
+
});
|
|
371183
|
+
|
|
371184
|
+
// src/service/package_retrieval_settings.ts
|
|
371185
|
+
import { createHash as createHash18 } from "crypto";
|
|
370675
371186
|
import * as fs19 from "fs";
|
|
370676
|
-
import * as
|
|
370677
|
-
import { pathToFileURL as
|
|
371187
|
+
import * as path37 from "path";
|
|
371188
|
+
import { pathToFileURL as pathToFileURL19 } from "url";
|
|
370678
371189
|
function alsoLikelyOn(settings) {
|
|
370679
371190
|
return settings.alsoLikely === "auto" ? settings.connect === "list" : settings.alsoLikely;
|
|
370680
371191
|
}
|
|
@@ -370693,12 +371204,12 @@ function describe3(value) {
|
|
|
370693
371204
|
function resolvePromptPath(packageRoot, rel, promptKey = "judge") {
|
|
370694
371205
|
const key = `retrieval.prompts.${promptKey}`;
|
|
370695
371206
|
const fix = `Fix: use a path inside the package, e.g. "prompts/${promptKey}.md".`;
|
|
370696
|
-
if (rel.includes("\x00") ||
|
|
371207
|
+
if (rel.includes("\x00") || path37.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel) || rel.startsWith("\\")) {
|
|
370697
371208
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} is an absolute path. ${fix}`);
|
|
370698
371209
|
}
|
|
370699
|
-
const root =
|
|
370700
|
-
const resolved =
|
|
370701
|
-
const within =
|
|
371210
|
+
const root = path37.resolve(packageRoot);
|
|
371211
|
+
const resolved = path37.resolve(root, rel);
|
|
371212
|
+
const within = path37.relative(root, resolved);
|
|
370702
371213
|
if (within === "" || stepsOutside(within)) {
|
|
370703
371214
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} resolves outside the package directory. ${fix}`);
|
|
370704
371215
|
}
|
|
@@ -370893,7 +371404,7 @@ async function readPromptFile(packageRoot, key, rel) {
|
|
|
370893
371404
|
try {
|
|
370894
371405
|
let realFile;
|
|
370895
371406
|
try {
|
|
370896
|
-
realFile = await confinedPackagePath(packageRoot,
|
|
371407
|
+
realFile = await confinedPackagePath(packageRoot, pathToFileURL19(file));
|
|
370897
371408
|
} catch (error) {
|
|
370898
371409
|
if (!(error instanceof ImportOutsidePackageError))
|
|
370899
371410
|
throw error;
|
|
@@ -370911,7 +371422,7 @@ async function readPromptFile(packageRoot, key, rel) {
|
|
|
370911
371422
|
return {
|
|
370912
371423
|
path: rel,
|
|
370913
371424
|
text,
|
|
370914
|
-
hash:
|
|
371425
|
+
hash: createHash18("sha256").update(text).digest("hex")
|
|
370915
371426
|
};
|
|
370916
371427
|
}
|
|
370917
371428
|
async function readPackageRetrieval(packageRoot, raw) {
|
|
@@ -372113,11 +372624,11 @@ class VariantCompileCache {
|
|
|
372113
372624
|
var DEFAULT_LIMIT = 500;
|
|
372114
372625
|
|
|
372115
372626
|
// src/service/materialization/serve/author_imports.ts
|
|
372116
|
-
import * as
|
|
372117
|
-
import { fileURLToPath as
|
|
372627
|
+
import * as path38 from "path";
|
|
372628
|
+
import { fileURLToPath as fileURLToPath17 } from "url";
|
|
372118
372629
|
function relativeImport(from, url) {
|
|
372119
372630
|
try {
|
|
372120
|
-
return
|
|
372631
|
+
return path38.relative(path38.dirname(fileURLToPath17(from)), fileURLToPath17(url)).split(path38.sep).join("/");
|
|
372121
372632
|
} catch {
|
|
372122
372633
|
return;
|
|
372123
372634
|
}
|
|
@@ -372170,15 +372681,15 @@ var init_author_imports = __esm(() => {
|
|
|
372170
372681
|
});
|
|
372171
372682
|
|
|
372172
372683
|
// src/service/materialization/serve/declaring_file_variant.ts
|
|
372173
|
-
import * as
|
|
372174
|
-
import { fileURLToPath as
|
|
372684
|
+
import * as path39 from "path";
|
|
372685
|
+
import { fileURLToPath as fileURLToPath18, pathToFileURL as pathToFileURL20 } from "url";
|
|
372175
372686
|
async function compileDeclaringFileVariant(args) {
|
|
372176
372687
|
const { packagePath, modelPath, packageConfig, modelDef } = args;
|
|
372177
372688
|
const declared = args.sourceID !== undefined ? declaringFileOf2(args.sourceID, args.copySuffix) : args.declaringURL !== undefined ? declaringFileAt("", args.declaringURL, args.copySuffix) : { error: "no declaring file" };
|
|
372178
372689
|
if ("error" in declared)
|
|
372179
372690
|
return declared;
|
|
372180
372691
|
const { declaringURL, copyURL, copyName } = declared;
|
|
372181
|
-
const modelFile =
|
|
372692
|
+
const modelFile = path39.join(packagePath, modelPath);
|
|
372182
372693
|
const authorFiles = packageFiles(packagePath, modelPath, args.basis ? args.config : packageConfig);
|
|
372183
372694
|
const blanked = args.basis ? new Map(args.basis.files) : await authorFiles.blanked(modelDef);
|
|
372184
372695
|
if (!blanked)
|
|
@@ -372208,7 +372719,7 @@ async function compileDeclaringFileVariant(args) {
|
|
|
372208
372719
|
...args.alsoRedeclared ?? []
|
|
372209
372720
|
]);
|
|
372210
372721
|
const exported = new Set(namesModel.exports ?? []);
|
|
372211
|
-
const modelHref = overlayKey(
|
|
372722
|
+
const modelHref = overlayKey(pathToFileURL20(modelFile));
|
|
372212
372723
|
for (const importer of importersOf(namesModel, declaringURL)) {
|
|
372213
372724
|
if (overlayKey(importer) === modelHref && [...redeclared].some((n) => exported.has(n))) {
|
|
372214
372725
|
continue;
|
|
@@ -372244,7 +372755,7 @@ async function compileDeclaringFileVariant(args) {
|
|
|
372244
372755
|
${importOthers}
|
|
372245
372756
|
${declaration}
|
|
372246
372757
|
${exportAll}`);
|
|
372247
|
-
const imports = authorNameImports(namesModel, args.queryModelURL,
|
|
372758
|
+
const imports = authorNameImports(namesModel, args.queryModelURL, pathToFileURL20(modelFile).href, {
|
|
372248
372759
|
skip: new Set(args.alsoExported ?? []),
|
|
372249
372760
|
redirect: {
|
|
372250
372761
|
from: overlayKey(declaringURL),
|
|
@@ -372273,13 +372784,13 @@ function declaringFileOf2(sourceID, copySuffix) {
|
|
|
372273
372784
|
function declaringFileAt(name, url, copySuffix) {
|
|
372274
372785
|
let declaringFile;
|
|
372275
372786
|
try {
|
|
372276
|
-
declaringFile =
|
|
372787
|
+
declaringFile = fileURLToPath18(url);
|
|
372277
372788
|
} catch {
|
|
372278
372789
|
return { error: "not a local file" };
|
|
372279
372790
|
}
|
|
372280
|
-
const declaringURL =
|
|
372281
|
-
const copyURL =
|
|
372282
|
-
const copyName =
|
|
372791
|
+
const declaringURL = pathToFileURL20(declaringFile);
|
|
372792
|
+
const copyURL = pathToFileURL20(`${declaringFile}${copySuffix}`);
|
|
372793
|
+
const copyName = path39.basename(fileURLToPath18(copyURL));
|
|
372283
372794
|
return { name, declaringURL, copyURL, copyName };
|
|
372284
372795
|
}
|
|
372285
372796
|
async function namesDeclaredIn(files, overlay, url) {
|
|
@@ -372409,8 +372920,8 @@ var init_stored_typed_source = __esm(() => {
|
|
|
372409
372920
|
});
|
|
372410
372921
|
|
|
372411
372922
|
// src/service/materialization/serve/view_variants.ts
|
|
372412
|
-
import * as
|
|
372413
|
-
import { fileURLToPath as
|
|
372923
|
+
import * as path40 from "path";
|
|
372924
|
+
import { fileURLToPath as fileURLToPath19, pathToFileURL as pathToFileURL21 } from "url";
|
|
372414
372925
|
|
|
372415
372926
|
class PersistedViewServe {
|
|
372416
372927
|
host;
|
|
@@ -372693,7 +373204,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372693
373204
|
return { refusal: read.refusal };
|
|
372694
373205
|
const sourceTimezone = shape.sourceTimezone ? `
|
|
372695
373206
|
timezone: ${stringLiteral(shape.sourceTimezone)}` : "";
|
|
372696
|
-
const modelFile =
|
|
373207
|
+
const modelFile = path40.join(packagePath, args.modelPath);
|
|
372697
373208
|
const config = table.binding && !isDatabase(table.binding) && args.destinations ? servedCopyConfig(packageConfig, args.destinations(), new Set([table.binding.destinationName])) : packageConfig;
|
|
372698
373209
|
return compileDeclaringFileVariant({
|
|
372699
373210
|
packagePath,
|
|
@@ -372703,7 +373214,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372703
373214
|
modelDef: args.modelDef,
|
|
372704
373215
|
...args.redeclare,
|
|
372705
373216
|
copySuffix: ".view-author.malloy",
|
|
372706
|
-
queryModelURL:
|
|
373217
|
+
queryModelURL: pathToFileURL21(`${modelFile}.view.malloy`),
|
|
372707
373218
|
flags: VARIANT_FLAGS,
|
|
372708
373219
|
declare: ({ gates, sourceName, copyName, declaringURL, addFile }) => {
|
|
372709
373220
|
if (table.binding) {
|
|
@@ -372736,7 +373247,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372736
373247
|
sourceTimezone,
|
|
372737
373248
|
stored: {
|
|
372738
373249
|
name,
|
|
372739
|
-
importLine: `import { ${identifier(name)} is ${identifier(plan.buildSourceName)} } from ${doubleQuotedString(
|
|
373250
|
+
importLine: `import { ${identifier(name)} is ${identifier(plan.buildSourceName)} } from ${doubleQuotedString(path40.basename(fileURLToPath19(companion)))}`
|
|
372740
373251
|
}
|
|
372741
373252
|
});
|
|
372742
373253
|
}
|
|
@@ -378647,8 +379158,8 @@ var init_join_rollup = __esm(() => {
|
|
|
378647
379158
|
});
|
|
378648
379159
|
|
|
378649
379160
|
// src/service/materialization/serve/rollup_variants.ts
|
|
378650
|
-
import * as
|
|
378651
|
-
import { fileURLToPath as
|
|
379161
|
+
import * as path41 from "path";
|
|
379162
|
+
import { fileURLToPath as fileURLToPath20, pathToFileURL as pathToFileURL22 } from "url";
|
|
378652
379163
|
import { EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST4 } from "@malloydata/malloy";
|
|
378653
379164
|
|
|
378654
379165
|
class RollupVariantServe {
|
|
@@ -379452,8 +379963,8 @@ class RollupVariantServe {
|
|
|
379452
379963
|
if (!packagePath || !packageConfig)
|
|
379453
379964
|
return { error: "no context" };
|
|
379454
379965
|
const modelPath = this.host.modelPath();
|
|
379455
|
-
const modelFile =
|
|
379456
|
-
const queryModelURL =
|
|
379966
|
+
const modelFile = path41.join(packagePath, modelPath);
|
|
379967
|
+
const queryModelURL = pathToFileURL22(`${modelFile}.rollup.malloy`);
|
|
379457
379968
|
const reads = table.binding ? storedRollupReads(plan, table.binding, this.host.modelDef(), declaredRollupColumns(this.host.catalog(), table.binding)) : undefined;
|
|
379458
379969
|
const destinations = this.host.serveDestinationConfig();
|
|
379459
379970
|
const config = table.binding && !isDatabase(table.binding) && destinations ? servedCopyConfig(packageConfig, destinations(), new Set([table.binding.destinationName])) : packageConfig;
|
|
@@ -379496,11 +380007,11 @@ class RollupVariantServe {
|
|
|
379496
380007
|
const companion = declared ? rollupCompanionURLOf(declared.url) : undefined;
|
|
379497
380008
|
let declaringFile;
|
|
379498
380009
|
try {
|
|
379499
|
-
declaringFile = declared ?
|
|
380010
|
+
declaringFile = declared ? fileURLToPath20(declared.url) : undefined;
|
|
379500
380011
|
} catch {
|
|
379501
380012
|
declaringFile = undefined;
|
|
379502
380013
|
}
|
|
379503
|
-
const text = companion && declaringFile ? generateRollupBuildFile([plan],
|
|
380014
|
+
const text = companion && declaringFile ? generateRollupBuildFile([plan], path41.basename(declaringFile)) : undefined;
|
|
379504
380015
|
if (!companion || !text || !declaringFile) {
|
|
379505
380016
|
return { error: "no companion" };
|
|
379506
380017
|
}
|
|
@@ -379511,16 +380022,16 @@ class RollupVariantServe {
|
|
|
379511
380022
|
for (const [url, file] of blanked)
|
|
379512
380023
|
overlay.set(url, file);
|
|
379513
380024
|
if (readsBuildCopy(plan)) {
|
|
379514
|
-
const baseURL =
|
|
380025
|
+
const baseURL = pathToFileURL22(declaringFile);
|
|
379515
380026
|
const made = rollupBuildCopyText(blanked.get(overlayKey(baseURL)) ?? await authorFiles.readIfAny(baseURL.href) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379516
380027
|
if (!("copy" in made))
|
|
379517
380028
|
return { error: made.reason };
|
|
379518
|
-
overlay.set(
|
|
380029
|
+
overlay.set(pathToFileURL22(path41.join(path41.dirname(declaringFile), rollupBuildCopyName(path41.basename(declaringFile), plan.baseDeclaredName))).href, made.copy);
|
|
379519
380030
|
}
|
|
379520
380031
|
const read = withoutLeftOut(plan, this.host.modelDef(), table.leftOut);
|
|
379521
380032
|
const declaration = `${databaseRollupSource(read.plan, this.host.modelDef(), servedName, relativeImport(queryModelURL, companion.href), read.dropped)}
|
|
379522
380033
|
${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
379523
|
-
const modelText = queryModelText(this.host.modelDef(), queryModelURL,
|
|
380034
|
+
const modelText = queryModelText(this.host.modelDef(), queryModelURL, pathToFileURL22(modelFile).href, { alias: new Map([[localName, parentAlias(plan)]]) }, declaration);
|
|
379524
380035
|
overlay.set(queryModelURL.href, modelText);
|
|
379525
380036
|
const { materializer, model, runtime } = await packageFiles(packagePath, modelPath, config).compile(queryModelURL, overlay);
|
|
379526
380037
|
return {
|
|
@@ -379536,7 +380047,7 @@ ${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
|
379536
380047
|
const read = withoutLeftOut(plan, modelDef, reads.leftOut);
|
|
379537
380048
|
const declaration = `${storedRollupDeclaration(read.plan, binding, reads, servedName, modelDef, read.dropped)}
|
|
379538
380049
|
${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
379539
|
-
const imports = authorNameImports(basis.modelDef, ctx.queryModelURL,
|
|
380050
|
+
const imports = authorNameImports(basis.modelDef, ctx.queryModelURL, pathToFileURL22(ctx.modelFile).href, { alias: new Map([[use.localName, parentAlias(plan)]]) });
|
|
379540
380051
|
const overlay = new Map(basis.files);
|
|
379541
380052
|
overlay.set(ctx.queryModelURL.href, `${flagLine(modelDef)}
|
|
379542
380053
|
${imports}
|
|
@@ -379635,23 +380146,23 @@ ${gates}${over}`;
|
|
|
379635
380146
|
}
|
|
379636
380147
|
let baseFile;
|
|
379637
380148
|
try {
|
|
379638
|
-
baseFile = base ?
|
|
380149
|
+
baseFile = base ? fileURLToPath20(base.url) : undefined;
|
|
379639
380150
|
} catch {
|
|
379640
380151
|
baseFile = undefined;
|
|
379641
380152
|
}
|
|
379642
380153
|
if (!companion || !baseFile)
|
|
379643
380154
|
return { error: "no companion" };
|
|
379644
|
-
const overlaid = overlayKey(
|
|
379645
|
-
const importPath = overlaid ? copyName :
|
|
380155
|
+
const overlaid = overlayKey(pathToFileURL22(baseFile)) === overlayKey(declaringURL);
|
|
380156
|
+
const importPath = overlaid ? copyName : path41.basename(baseFile);
|
|
379646
380157
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379647
380158
|
if (!text)
|
|
379648
380159
|
return { error: "no companion" };
|
|
379649
380160
|
addFile(companion, text);
|
|
379650
380161
|
if (readsBuildCopy(plan)) {
|
|
379651
|
-
const made = rollupBuildCopyText(await authorText(
|
|
380162
|
+
const made = rollupBuildCopyText(await authorText(pathToFileURL22(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379652
380163
|
if (!("copy" in made))
|
|
379653
380164
|
return { error: made.reason };
|
|
379654
|
-
addFile(
|
|
380165
|
+
addFile(pathToFileURL22(path41.join(path41.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379655
380166
|
}
|
|
379656
380167
|
return `${databaseRollupSource(read.plan, modelDef, servedName, relativeImport(declaringURL, companion.href), read.dropped)}
|
|
379657
380168
|
${gates}${over}`;
|
|
@@ -379683,23 +380194,23 @@ async function databaseRollupInOverlay(plan, read, modelDef, ctx) {
|
|
|
379683
380194
|
const companion = base ? rollupCompanionURLOf(base.url) : undefined;
|
|
379684
380195
|
let baseFile;
|
|
379685
380196
|
try {
|
|
379686
|
-
baseFile = base ?
|
|
380197
|
+
baseFile = base ? fileURLToPath20(base.url) : undefined;
|
|
379687
380198
|
} catch {
|
|
379688
380199
|
baseFile = undefined;
|
|
379689
380200
|
}
|
|
379690
380201
|
if (!companion || !baseFile)
|
|
379691
380202
|
return { error: "no companion" };
|
|
379692
|
-
const overlaid = overlayKey(
|
|
379693
|
-
const importPath = overlaid ? copyName :
|
|
380203
|
+
const overlaid = overlayKey(pathToFileURL22(baseFile)) === overlayKey(declaringURL);
|
|
380204
|
+
const importPath = overlaid ? copyName : path41.basename(baseFile);
|
|
379694
380205
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379695
380206
|
if (!text)
|
|
379696
380207
|
return { error: "no companion" };
|
|
379697
380208
|
addFile(companion, text);
|
|
379698
380209
|
if (readsBuildCopy(plan)) {
|
|
379699
|
-
const made = rollupBuildCopyText(await authorText(
|
|
380210
|
+
const made = rollupBuildCopyText(await authorText(pathToFileURL22(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379700
380211
|
if (!("copy" in made))
|
|
379701
380212
|
return { error: made.reason };
|
|
379702
|
-
addFile(
|
|
380213
|
+
addFile(pathToFileURL22(path41.join(path41.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379703
380214
|
}
|
|
379704
380215
|
return databaseRollupSource(read.plan, modelDef, ctx.servedName, relativeImport(declaringURL, companion.href), read.dropped);
|
|
379705
380216
|
}
|
|
@@ -380407,18 +380918,30 @@ class PackageModelPolicy {
|
|
|
380407
380918
|
boundaries;
|
|
380408
380919
|
siblingResolver;
|
|
380409
380920
|
serving;
|
|
380921
|
+
successor;
|
|
380410
380922
|
forModel(modelPath) {
|
|
380923
|
+
const live = () => this.current();
|
|
380411
380924
|
return Object.freeze({
|
|
380412
380925
|
origin: "package",
|
|
380413
|
-
discoveryCurationEnabled: () =>
|
|
380414
|
-
queryBoundary: () =>
|
|
380415
|
-
siblingModelDefResolver: () =>
|
|
380416
|
-
snapshot: () =>
|
|
380417
|
-
preaggregateEntityIds: () =>
|
|
380418
|
-
materializedTables: () =>
|
|
380419
|
-
reportIncompatible: (handles) =>
|
|
380926
|
+
discoveryCurationEnabled: () => live().discoveryCuration,
|
|
380927
|
+
queryBoundary: () => live().boundaries?.get(modelPath) ?? UNDECIDED_PACKAGE_BOUNDARY,
|
|
380928
|
+
siblingModelDefResolver: () => live().siblingResolver,
|
|
380929
|
+
snapshot: () => live().serving?.snapshot(),
|
|
380930
|
+
preaggregateEntityIds: () => live().serving?.preaggregateEntityIds(),
|
|
380931
|
+
materializedTables: () => live().serving?.materializedTables?.(),
|
|
380932
|
+
reportIncompatible: (handles) => live().serving?.reportIncompatible?.(handles)
|
|
380420
380933
|
});
|
|
380421
380934
|
}
|
|
380935
|
+
handOffTo(next) {
|
|
380936
|
+
if (next !== this)
|
|
380937
|
+
this.successor = next;
|
|
380938
|
+
}
|
|
380939
|
+
current() {
|
|
380940
|
+
if (!this.successor)
|
|
380941
|
+
return this;
|
|
380942
|
+
this.successor = this.successor.current();
|
|
380943
|
+
return this.successor;
|
|
380944
|
+
}
|
|
380422
380945
|
setDiscoveryCuration(enabled) {
|
|
380423
380946
|
this.discoveryCuration = enabled;
|
|
380424
380947
|
}
|
|
@@ -380464,8 +380987,8 @@ import {
|
|
|
380464
380987
|
Annotations as Annotations11
|
|
380465
380988
|
} from "@malloydata/malloy";
|
|
380466
380989
|
import { createRequire as createRequire4 } from "module";
|
|
380467
|
-
import * as
|
|
380468
|
-
import { fileURLToPath as
|
|
380990
|
+
import * as path42 from "path";
|
|
380991
|
+
import { fileURLToPath as fileURLToPath21, pathToFileURL as pathToFileURL23 } from "url";
|
|
380469
380992
|
function placeholderGivens(givens) {
|
|
380470
380993
|
const out = {};
|
|
380471
380994
|
for (const given of givens ?? []) {
|
|
@@ -380706,7 +381229,7 @@ var init_model = __esm(() => {
|
|
|
380706
381229
|
if (this.modelFile === undefined)
|
|
380707
381230
|
return false;
|
|
380708
381231
|
try {
|
|
380709
|
-
return
|
|
381232
|
+
return path42.resolve(fileURLToPath21(url)) === this.modelFile;
|
|
380710
381233
|
} catch {
|
|
380711
381234
|
return false;
|
|
380712
381235
|
}
|
|
@@ -380815,7 +381338,7 @@ var init_model = __esm(() => {
|
|
|
380815
381338
|
modelType,
|
|
380816
381339
|
modelMaterializer,
|
|
380817
381340
|
modelDef,
|
|
380818
|
-
modelFile:
|
|
381341
|
+
modelFile: path42.resolve(packagePath, modelPath),
|
|
380819
381342
|
sources,
|
|
380820
381343
|
queries,
|
|
380821
381344
|
sourceInfos,
|
|
@@ -380896,7 +381419,7 @@ var init_model = __esm(() => {
|
|
|
380896
381419
|
modelType: data.modelType,
|
|
380897
381420
|
modelMaterializer,
|
|
380898
381421
|
modelDef,
|
|
380899
|
-
modelFile:
|
|
381422
|
+
modelFile: path42.resolve(packagePath, data.modelPath),
|
|
380900
381423
|
sources,
|
|
380901
381424
|
queries,
|
|
380902
381425
|
sourceInfos,
|
|
@@ -381770,6 +382293,7 @@ var init_model = __esm(() => {
|
|
|
381770
382293
|
givens
|
|
381771
382294
|
}));
|
|
381772
382295
|
},
|
|
382296
|
+
authorPreparedQuery: async (queryString) => this.modelMaterializer?.loadRestrictedQuery(queryString).getPreparedQuery(),
|
|
381773
382297
|
ensureSharedQueryModel: (materializer) => this.ensureSharedQueryModel(materializer),
|
|
381774
382298
|
modelPath: () => this.modelPath,
|
|
381775
382299
|
modelDef: () => this.modelDef,
|
|
@@ -382417,9 +382941,9 @@ var init_model = __esm(() => {
|
|
|
382417
382941
|
return createModelMaterializer(...args);
|
|
382418
382942
|
}
|
|
382419
382943
|
async getFileText(packagePath) {
|
|
382420
|
-
const fullPath =
|
|
382944
|
+
const fullPath = path42.join(packagePath, this.modelPath);
|
|
382421
382945
|
try {
|
|
382422
|
-
return await readPackageURL(packagePath,
|
|
382946
|
+
return await readPackageURL(packagePath, pathToFileURL23(fullPath));
|
|
382423
382947
|
} catch {
|
|
382424
382948
|
throw new ModelNotFoundError(`Model file not found: ${this.modelPath}`);
|
|
382425
382949
|
}
|
|
@@ -382548,8 +383072,8 @@ var init_package_load_gates = __esm(() => {
|
|
|
382548
383072
|
|
|
382549
383073
|
// src/service/package.ts
|
|
382550
383074
|
import * as fs20 from "fs/promises";
|
|
382551
|
-
import * as
|
|
382552
|
-
import { pathToFileURL as
|
|
383075
|
+
import * as path43 from "path";
|
|
383076
|
+
import { pathToFileURL as pathToFileURL24 } from "url";
|
|
382553
383077
|
import"@malloydata/db-duckdb/native";
|
|
382554
383078
|
import { DuckDBConnection as DuckDBConnection8 } from "@malloydata/db-duckdb";
|
|
382555
383079
|
import {
|
|
@@ -382561,6 +383085,22 @@ import {
|
|
|
382561
383085
|
MalloyError as MalloyError16,
|
|
382562
383086
|
Model as MalloyModel
|
|
382563
383087
|
} from "@malloydata/malloy";
|
|
383088
|
+
function recompileFailedWarning(kept, withdrawn) {
|
|
383089
|
+
const live = withdrawn.sources.filter((s) => kept.sources.includes(s));
|
|
383090
|
+
const parts = [
|
|
383091
|
+
`${kept.modelPath} did not recompile, so its sources ` + `(${kept.sources.join(", ") || "none"}) are served from the model ` + `it last compiled: ${kept.error}`
|
|
383092
|
+
];
|
|
383093
|
+
if (live.length > 0) {
|
|
383094
|
+
parts.push(`Upstream table ${withdrawn.tables.join(", ")} changed since the ` + `last build, so ${live.join(", ")} answer live until a reload ` + `compiles and a run rebuilds them.`);
|
|
383095
|
+
}
|
|
383096
|
+
return {
|
|
383097
|
+
code: MODEL_RECOMPILE_FAILED,
|
|
383098
|
+
model: kept.modelPath,
|
|
383099
|
+
reason: "compile_failed",
|
|
383100
|
+
message: parts.join(" "),
|
|
383101
|
+
severity: "warn"
|
|
383102
|
+
};
|
|
383103
|
+
}
|
|
382564
383104
|
function packageLoadFailureStatus(error) {
|
|
382565
383105
|
if (error instanceof ModelCompilationError || error instanceof MalloyError16) {
|
|
382566
383106
|
return "compilation_error";
|
|
@@ -382573,7 +383113,7 @@ function packageLoadFailureStatus(error) {
|
|
|
382573
383113
|
}
|
|
382574
383114
|
return "error";
|
|
382575
383115
|
}
|
|
382576
|
-
var COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
|
|
383116
|
+
var MODEL_RECOMPILE_FAILED = "model-recompile-failed", COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
|
|
382577
383117
|
var init_package2 = __esm(() => {
|
|
382578
383118
|
init_materialization();
|
|
382579
383119
|
init_malloy_text();
|
|
@@ -382587,6 +383127,7 @@ var init_package2 = __esm(() => {
|
|
|
382587
383127
|
init_access_gates();
|
|
382588
383128
|
init_explore_walk();
|
|
382589
383129
|
init_package_load_pool();
|
|
383130
|
+
init_job_files();
|
|
382590
383131
|
init_package_manifest();
|
|
382591
383132
|
init_package_retrieval_settings();
|
|
382592
383133
|
init_constants();
|
|
@@ -382686,6 +383227,9 @@ var init_package2 = __esm(() => {
|
|
|
382686
383227
|
this.mz.plan.databaseSourceEligibility = eligibility;
|
|
382687
383228
|
}
|
|
382688
383229
|
renderTagWarnings = [];
|
|
383230
|
+
recompileFailedWarnings = [];
|
|
383231
|
+
keptModelStaleness;
|
|
383232
|
+
compiledFrom = new Map;
|
|
382689
383233
|
reloadedFor;
|
|
382690
383234
|
connectionEdits = 0;
|
|
382691
383235
|
entitiesWarnings = [];
|
|
@@ -382921,7 +383465,7 @@ var init_package2 = __esm(() => {
|
|
|
382921
383465
|
applySiblingModelResolverToModels() {
|
|
382922
383466
|
const byUrl = new Map;
|
|
382923
383467
|
for (const [modelPath, model] of this.models) {
|
|
382924
|
-
byUrl.set(
|
|
383468
|
+
byUrl.set(pathToFileURL24(path43.join(this.packagePath, modelPath)).toString(), model);
|
|
382925
383469
|
}
|
|
382926
383470
|
this.modelPolicy.setSiblingModelDefResolver((url) => byUrl.get(url)?.getModelDef());
|
|
382927
383471
|
}
|
|
@@ -383222,7 +383766,7 @@ var init_package2 = __esm(() => {
|
|
|
383222
383766
|
buildManifest
|
|
383223
383767
|
}, "throw", async (sm) => {
|
|
383224
383768
|
if (sm.modelPath.endsWith(MODEL_FILE_SUFFIX)) {
|
|
383225
|
-
const modelSource = await readPackageURL(packagePath,
|
|
383769
|
+
const modelSource = await readPackageURL(packagePath, pathToFileURL24(path43.join(packagePath, sm.modelPath)));
|
|
383226
383770
|
nameProblems.push(...persistNameProblems(modelSource, sm.modelPath));
|
|
383227
383771
|
}
|
|
383228
383772
|
}));
|
|
@@ -383235,6 +383779,7 @@ var init_package2 = __esm(() => {
|
|
|
383235
383779
|
const executionTime = performance.now() - startTime;
|
|
383236
383780
|
const pkg = new Package(environmentName, packageName, packagePath, packageConfig, databases, models, malloyConfig, modelPolicy);
|
|
383237
383781
|
pkg.dryRun = dryRun;
|
|
383782
|
+
pkg.compiledFrom = pkg.compiledFromOf(models, outcome.fileDigests);
|
|
383238
383783
|
pkg.refreshesUpstreamSchemas = refreshSchemas;
|
|
383239
383784
|
pkg.persistNameProblems = nameProblems;
|
|
383240
383785
|
let reportTimings;
|
|
@@ -383519,7 +384064,7 @@ var init_package2 = __esm(() => {
|
|
|
383519
384064
|
for (const [modelPath, model] of this.models) {
|
|
383520
384065
|
if (!modelPath.endsWith(MODEL_FILE_SUFFIX))
|
|
383521
384066
|
continue;
|
|
383522
|
-
const absolutePath =
|
|
384067
|
+
const absolutePath = path43.join(this.packagePath, modelPath);
|
|
383523
384068
|
const modelDef = model.getModelDef();
|
|
383524
384069
|
const compilationError = model.getCompilationError();
|
|
383525
384070
|
if (compilationError !== undefined || modelDef === undefined) {
|
|
@@ -383534,7 +384079,7 @@ var init_package2 = __esm(() => {
|
|
|
383534
384079
|
relativePath: modelPath,
|
|
383535
384080
|
absolutePath,
|
|
383536
384081
|
model: new MalloyModel(modelDef, [], []),
|
|
383537
|
-
text: model.getCompiledSourceText() ?? await readPackageURL(this.packagePath,
|
|
384082
|
+
text: model.getCompiledSourceText() ?? await readPackageURL(this.packagePath, pathToFileURL24(absolutePath))
|
|
383538
384083
|
});
|
|
383539
384084
|
}
|
|
383540
384085
|
return modelFiles;
|
|
@@ -383603,6 +384148,7 @@ var init_package2 = __esm(() => {
|
|
|
383603
384148
|
}
|
|
383604
384149
|
const allWarnings = [
|
|
383605
384150
|
...this.renderTagWarnings,
|
|
384151
|
+
...this.recompileFailedWarnings,
|
|
383606
384152
|
...this.entitiesWarnings,
|
|
383607
384153
|
...this.readerWarnings,
|
|
383608
384154
|
...this.reportWarnings,
|
|
@@ -384090,11 +384636,33 @@ var init_package2 = __esm(() => {
|
|
|
384090
384636
|
buildManifest,
|
|
384091
384637
|
modelPolicy: nextModelPolicy
|
|
384092
384638
|
}, "placeholder");
|
|
384639
|
+
const kept = this.keepLastGoodModels(nextModels, outcome.fileDigests);
|
|
384640
|
+
const withdrawn = kept.length > 0 ? await this.withdrawChangedUpstreams().catch((error) => {
|
|
384641
|
+
logger.warn("Could not read the upstream tables of a model kept from before a failed recompile", {
|
|
384642
|
+
packageName: this.packageName,
|
|
384643
|
+
error: errMessage(error)
|
|
384644
|
+
});
|
|
384645
|
+
return { sources: [], tables: [] };
|
|
384646
|
+
}) : { sources: [], tables: [] };
|
|
384093
384647
|
const discoveryStarted = performance.now();
|
|
384094
384648
|
const discovery = await this.discoverReportsIn(nextModels, "reload");
|
|
384095
384649
|
const discoveryMs = performance.now() - discoveryStarted;
|
|
384096
384650
|
this.models = nextModels;
|
|
384651
|
+
this.modelPolicy.handOffTo(nextModelPolicy);
|
|
384097
384652
|
this.modelPolicy = nextModelPolicy;
|
|
384653
|
+
this.recompileFailedWarnings = kept.map((k) => recompileFailedWarning(k, withdrawn));
|
|
384654
|
+
this.mz.plan.holdWithdrawn(kept.length > 0);
|
|
384655
|
+
const compiledFrom = this.compiledFromOf(nextModels, outcome.fileDigests);
|
|
384656
|
+
for (const { modelPath } of kept) {
|
|
384657
|
+
const prior = this.compiledFrom.get(modelPath);
|
|
384658
|
+
if (prior)
|
|
384659
|
+
compiledFrom.set(modelPath, prior);
|
|
384660
|
+
}
|
|
384661
|
+
this.compiledFrom = compiledFrom;
|
|
384662
|
+
this.keptModelStaleness = kept.length > 0 ? {
|
|
384663
|
+
message: this.recompileFailedWarnings.map((w) => w.message).join(" "),
|
|
384664
|
+
failedAt: new Date().toISOString()
|
|
384665
|
+
} : undefined;
|
|
384098
384666
|
this.adoptOutcomeMetadata(outcome);
|
|
384099
384667
|
this.refreshServingIdentity();
|
|
384100
384668
|
const previousSurface = this.packageMetadata.explores;
|
|
@@ -384127,6 +384695,52 @@ var init_package2 = __esm(() => {
|
|
|
384127
384695
|
this.logEmptyDiscoveryWarnings();
|
|
384128
384696
|
return true;
|
|
384129
384697
|
}
|
|
384698
|
+
keepLastGoodModels(nextModels, digests) {
|
|
384699
|
+
const kept = [];
|
|
384700
|
+
for (const [modelPath, next] of nextModels) {
|
|
384701
|
+
const error = next.getCompilationError();
|
|
384702
|
+
const prior = this.models.get(modelPath);
|
|
384703
|
+
if (!error || !prior || prior.getCompilationError())
|
|
384704
|
+
continue;
|
|
384705
|
+
const compiledFrom = this.compiledFrom.get(modelPath);
|
|
384706
|
+
if (!compiledFrom || !digests || [...compiledFrom].some(([url, digest]) => digests[url] !== digest)) {
|
|
384707
|
+
continue;
|
|
384708
|
+
}
|
|
384709
|
+
nextModels.set(modelPath, prior);
|
|
384710
|
+
const sources = (prior.getSources() ?? []).map((s) => s.name).filter((name) => typeof name === "string").sort();
|
|
384711
|
+
kept.push({ modelPath, error: error.message, sources });
|
|
384712
|
+
logger.warn("A model did not recompile; serving its last good model", {
|
|
384713
|
+
packageName: this.packageName,
|
|
384714
|
+
modelPath,
|
|
384715
|
+
error: error.message
|
|
384716
|
+
});
|
|
384717
|
+
}
|
|
384718
|
+
return kept;
|
|
384719
|
+
}
|
|
384720
|
+
compiledFromOf(models, digests) {
|
|
384721
|
+
const compiledFrom = new Map;
|
|
384722
|
+
if (!digests)
|
|
384723
|
+
return compiledFrom;
|
|
384724
|
+
for (const [modelPath, model] of models) {
|
|
384725
|
+
const modelDef = model.getModelDef();
|
|
384726
|
+
if (model.getCompilationError() || !modelDef)
|
|
384727
|
+
continue;
|
|
384728
|
+
const urls = modelReadKeys(pathToFileURL24(path43.join(this.packagePath, modelPath)).href, modelDef.dependencies);
|
|
384729
|
+
const read = new Map;
|
|
384730
|
+
for (const url of urls) {
|
|
384731
|
+
const digest = digests[url];
|
|
384732
|
+
if (digest === undefined)
|
|
384733
|
+
break;
|
|
384734
|
+
read.set(url, digest);
|
|
384735
|
+
}
|
|
384736
|
+
if (read.size === urls.length)
|
|
384737
|
+
compiledFrom.set(modelPath, read);
|
|
384738
|
+
}
|
|
384739
|
+
return compiledFrom;
|
|
384740
|
+
}
|
|
384741
|
+
getKeptModelStaleness() {
|
|
384742
|
+
return this.keptModelStaleness;
|
|
384743
|
+
}
|
|
384130
384744
|
static compileKeyOf(entries) {
|
|
384131
384745
|
return JSON.stringify(Object.keys(entries).sort().map((id) => [
|
|
384132
384746
|
id,
|
|
@@ -384207,7 +384821,7 @@ var init_package2 = __esm(() => {
|
|
|
384207
384821
|
}
|
|
384208
384822
|
async readModelText(model, modelPath) {
|
|
384209
384823
|
try {
|
|
384210
|
-
return model.getCompiledSourceText() ?? await readPackageURL(this.packagePath,
|
|
384824
|
+
return model.getCompiledSourceText() ?? await readPackageURL(this.packagePath, pathToFileURL24(safeJoinUnderRoot(this.packagePath, modelPath)));
|
|
384211
384825
|
} catch {
|
|
384212
384826
|
return;
|
|
384213
384827
|
}
|
|
@@ -384215,7 +384829,7 @@ var init_package2 = __esm(() => {
|
|
|
384215
384829
|
modelPathsByImportUrl() {
|
|
384216
384830
|
const byUrl = new Map;
|
|
384217
384831
|
for (const modelPath of this.models.keys()) {
|
|
384218
|
-
byUrl.set(
|
|
384832
|
+
byUrl.set(pathToFileURL24(path43.join(this.packagePath, modelPath)).toString(), modelPath);
|
|
384219
384833
|
}
|
|
384220
384834
|
return byUrl;
|
|
384221
384835
|
}
|
|
@@ -384812,7 +385426,7 @@ var init_package2 = __esm(() => {
|
|
|
384812
385426
|
}
|
|
384813
385427
|
let real;
|
|
384814
385428
|
try {
|
|
384815
|
-
real = await confinedPackagePath(packagePath,
|
|
385429
|
+
real = await confinedPackagePath(packagePath, pathToFileURL24(packageConfigPath));
|
|
384816
385430
|
} catch {
|
|
384817
385431
|
throw notThere();
|
|
384818
385432
|
}
|
|
@@ -384861,9 +385475,9 @@ var init_package2 = __esm(() => {
|
|
|
384861
385475
|
static async getDatabasePaths(packagePath) {
|
|
384862
385476
|
const files = await listPackageTree(packagePath);
|
|
384863
385477
|
const candidates = files.map((fullPath) => {
|
|
384864
|
-
return
|
|
385478
|
+
return path43.relative(packagePath, fullPath).replace(/\\/g, "/");
|
|
384865
385479
|
}).filter((modelPath) => {
|
|
384866
|
-
if (
|
|
385480
|
+
if (path43.basename(modelPath).startsWith("~$")) {
|
|
384867
385481
|
return false;
|
|
384868
385482
|
}
|
|
384869
385483
|
return modelPath.endsWith(".parquet") || modelPath.endsWith(".csv") || modelPath.endsWith(".xlsx");
|
|
@@ -384871,7 +385485,7 @@ var init_package2 = __esm(() => {
|
|
|
384871
385485
|
const probed = [];
|
|
384872
385486
|
for (const relativePath of candidates) {
|
|
384873
385487
|
try {
|
|
384874
|
-
const real = await confinedPackagePath(packagePath,
|
|
385488
|
+
const real = await confinedPackagePath(packagePath, pathToFileURL24(path43.join(packagePath, relativePath)));
|
|
384875
385489
|
if ((await fs20.stat(real)).isFile())
|
|
384876
385490
|
probed.push(relativePath);
|
|
384877
385491
|
} catch {}
|
|
@@ -384879,7 +385493,7 @@ var init_package2 = __esm(() => {
|
|
|
384879
385493
|
return probed;
|
|
384880
385494
|
}
|
|
384881
385495
|
static async getDatabaseInfo(packagePath, databasePath, conn) {
|
|
384882
|
-
const fullPath =
|
|
385496
|
+
const fullPath = path43.join(packagePath, databasePath);
|
|
384883
385497
|
const runtime = new ConnectionRuntime({
|
|
384884
385498
|
urlReader: new EmptyURLReader,
|
|
384885
385499
|
connections: [conn]
|
|
@@ -385479,9 +386093,9 @@ var init_compile_document = __esm(() => {
|
|
|
385479
386093
|
// src/service/compile_source.ts
|
|
385480
386094
|
import { MalloyError as MalloyError18, Runtime as Runtime3 } from "@malloydata/malloy";
|
|
385481
386095
|
import * as fs21 from "fs";
|
|
385482
|
-
import * as
|
|
385483
|
-
import { fileURLToPath as
|
|
385484
|
-
function packageRelativeModelPath(packagePath, filePath, pathModule =
|
|
386096
|
+
import * as path44 from "path";
|
|
386097
|
+
import { fileURLToPath as fileURLToPath22, pathToFileURL as pathToFileURL25 } from "url";
|
|
386098
|
+
function packageRelativeModelPath(packagePath, filePath, pathModule = path44) {
|
|
385485
386099
|
const rel = pathModule.relative(packagePath, filePath);
|
|
385486
386100
|
if (rel === "" || rel.startsWith("..") || pathModule.isAbsolute(rel)) {
|
|
385487
386101
|
return;
|
|
@@ -385596,8 +386210,8 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385596
386210
|
const source = request.source ?? (scope === "file" ? overlaidText(overlay, modelName) : undefined);
|
|
385597
386211
|
const packagePath = versioned ? versioned.getPackagePath() : safeJoinUnderRoot(host.environmentPath, packageName);
|
|
385598
386212
|
const modelPath = safeJoinUnderRoot(packagePath, modelName);
|
|
385599
|
-
const modelDir =
|
|
385600
|
-
const virtualUrl = scope === "append" ?
|
|
386213
|
+
const modelDir = path44.dirname(modelPath);
|
|
386214
|
+
const virtualUrl = scope === "append" ? pathToFileURL25(path44.join(modelDir, "__compile_check.malloy")) : pathToFileURL25(modelPath);
|
|
385601
386215
|
const virtualUri = virtualUrl.toString();
|
|
385602
386216
|
const { fullSource, callerRegion } = scope === "append" ? await appendToSavedModel(packagePath, modelPath, source, virtualUri) : { fullSource: source ?? "", callerRegion: undefined };
|
|
385603
386217
|
const substitute = scope !== "package" || source !== undefined;
|
|
@@ -385637,7 +386251,7 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385637
386251
|
let model;
|
|
385638
386252
|
if (url && url.startsWith("file:")) {
|
|
385639
386253
|
try {
|
|
385640
|
-
model = packageRelativeModelPath(packagePath,
|
|
386254
|
+
model = packageRelativeModelPath(packagePath, fileURLToPath22(url));
|
|
385641
386255
|
} catch {}
|
|
385642
386256
|
}
|
|
385643
386257
|
if (scope === "append" && url === virtualUri) {
|
|
@@ -385668,7 +386282,7 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385668
386282
|
async function appendToSavedModel(packagePath, modelPath, source, virtualUri) {
|
|
385669
386283
|
let modelContent = "";
|
|
385670
386284
|
try {
|
|
385671
|
-
modelContent = await readPackageURL(packagePath,
|
|
386285
|
+
modelContent = await readPackageURL(packagePath, pathToFileURL25(modelPath));
|
|
385672
386286
|
} catch {}
|
|
385673
386287
|
const fullSource = modelContent ? `${modelContent}
|
|
385674
386288
|
${source}` : source ?? "";
|
|
@@ -385824,7 +386438,7 @@ async function compileAppend(ctx) {
|
|
|
385824
386438
|
async function loadAppendBase(ctx) {
|
|
385825
386439
|
const { runtime, modelPath, modelName, environmentName } = ctx;
|
|
385826
386440
|
try {
|
|
385827
|
-
const appendBase = runtime.loadModel(
|
|
386441
|
+
const appendBase = runtime.loadModel(pathToFileURL25(modelPath));
|
|
385828
386442
|
const baseModel = await appendBase.getModel();
|
|
385829
386443
|
return { appendBase, baseModel };
|
|
385830
386444
|
} catch (error) {
|
|
@@ -385986,7 +386600,7 @@ async function compilePackageDryRun(ctx) {
|
|
|
385986
386600
|
if (compiled.problems) {
|
|
385987
386601
|
collect(compiled.problems, compiled.modelPath);
|
|
385988
386602
|
}
|
|
385989
|
-
const readerProblem = compiled.modelDef && compiled.modelSourceText !== undefined ? notebookReaderProblem(compiled.modelPath, compiled.modelSourceText, compiled.modelDef,
|
|
386603
|
+
const readerProblem = compiled.modelDef && compiled.modelSourceText !== undefined ? notebookReaderProblem(compiled.modelPath, compiled.modelSourceText, compiled.modelDef, pathToFileURL25(path44.join(packagePath, compiled.modelPath)).toString()) : undefined;
|
|
385990
386604
|
if (readerProblem)
|
|
385991
386605
|
collect([readerProblem], compiled.modelPath);
|
|
385992
386606
|
if (compiled.compilationError) {
|
|
@@ -386002,11 +386616,11 @@ async function compilePackageDryRun(ctx) {
|
|
|
386002
386616
|
], compiled.modelPath);
|
|
386003
386617
|
}
|
|
386004
386618
|
}
|
|
386005
|
-
const lintText = !(compiled.modelPath.endsWith(".malloy") && isReportEligiblePath(compiled.modelPath)) ? undefined : compiled.modelSourceText ?? (compiled.modelPath === modelName && source !== undefined ? source : overlaidText(ctx.overlay, compiled.modelPath) ?? await readPackageURL(packagePath,
|
|
386619
|
+
const lintText = !(compiled.modelPath.endsWith(".malloy") && isReportEligiblePath(compiled.modelPath)) ? undefined : compiled.modelSourceText ?? (compiled.modelPath === modelName && source !== undefined ? source : overlaidText(ctx.overlay, compiled.modelPath) ?? await readPackageURL(packagePath, pathToFileURL25(path44.join(packagePath, compiled.modelPath))).catch(() => {
|
|
386006
386620
|
return;
|
|
386007
386621
|
}));
|
|
386008
386622
|
if (lintText !== undefined) {
|
|
386009
|
-
collect(notebookLintProblems(compiled.modelPath, lintText,
|
|
386623
|
+
collect(notebookLintProblems(compiled.modelPath, lintText, pathToFileURL25(path44.join(packagePath, compiled.modelPath)).toString()).filter((problem) => !reportedByDashboardLint(problem, compiled.modelPath, reportWarnings)), compiled.modelPath);
|
|
386010
386624
|
}
|
|
386011
386625
|
}
|
|
386012
386626
|
for (const warning of renderTagWarnings) {
|
|
@@ -386276,7 +386890,7 @@ var init_status_snapshot = __esm(() => {
|
|
|
386276
386890
|
// src/service/versions/package_content_hash.ts
|
|
386277
386891
|
import * as crypto4 from "crypto";
|
|
386278
386892
|
import * as fs22 from "fs";
|
|
386279
|
-
import * as
|
|
386893
|
+
import * as path45 from "path";
|
|
386280
386894
|
async function hashPackageTree(root) {
|
|
386281
386895
|
const hash = crypto4.createHash("sha256");
|
|
386282
386896
|
const entries = await listEntries(root, "");
|
|
@@ -386318,7 +386932,7 @@ async function hashPackageTree(root) {
|
|
|
386318
386932
|
return hash.digest("hex");
|
|
386319
386933
|
}
|
|
386320
386934
|
async function readEntry(root, entry) {
|
|
386321
|
-
const absolute =
|
|
386935
|
+
const absolute = path45.join(root, ...entry.relative.split("/"));
|
|
386322
386936
|
if (entry.kind === "dir")
|
|
386323
386937
|
return { kind: "dir" };
|
|
386324
386938
|
if (entry.kind === "link") {
|
|
@@ -386331,7 +386945,7 @@ async function readEntry(root, entry) {
|
|
|
386331
386945
|
return { kind: "file", absolute, size: bytes.length, bytes };
|
|
386332
386946
|
}
|
|
386333
386947
|
async function listEntries(root, prefix) {
|
|
386334
|
-
const directory = prefix === "" ? root :
|
|
386948
|
+
const directory = prefix === "" ? root : path45.join(root, ...prefix.split("/"));
|
|
386335
386949
|
const dirents = await fs22.promises.readdir(directory, {
|
|
386336
386950
|
withFileTypes: true
|
|
386337
386951
|
});
|
|
@@ -386360,8 +386974,8 @@ var init_package_content_hash = __esm(() => {
|
|
|
386360
386974
|
// src/service/versions/version_store.ts
|
|
386361
386975
|
import * as crypto5 from "crypto";
|
|
386362
386976
|
import * as fs23 from "fs";
|
|
386363
|
-
import * as
|
|
386364
|
-
import { pathToFileURL as
|
|
386977
|
+
import * as path46 from "path";
|
|
386978
|
+
import { pathToFileURL as pathToFileURL26 } from "url";
|
|
386365
386979
|
|
|
386366
386980
|
class VersionStore {
|
|
386367
386981
|
environmentPath;
|
|
@@ -386377,7 +386991,7 @@ class VersionStore {
|
|
|
386377
386991
|
async stage(packageName, downloader) {
|
|
386378
386992
|
assertSafePackageName(packageName);
|
|
386379
386993
|
const stagingPath = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
386380
|
-
await fs23.promises.mkdir(
|
|
386994
|
+
await fs23.promises.mkdir(path46.dirname(stagingPath), { recursive: true });
|
|
386381
386995
|
try {
|
|
386382
386996
|
await downloader(stagingPath);
|
|
386383
386997
|
const manifest = await readManifestVersion(stagingPath);
|
|
@@ -386399,8 +387013,8 @@ class VersionStore {
|
|
|
386399
387013
|
}
|
|
386400
387014
|
within(area, candidate) {
|
|
386401
387015
|
const root = safeJoinUnderRoot(this.environmentPath, area);
|
|
386402
|
-
const resolved =
|
|
386403
|
-
if (!resolved.startsWith(root +
|
|
387016
|
+
const resolved = path46.resolve(candidate);
|
|
387017
|
+
if (!resolved.startsWith(root + path46.sep)) {
|
|
386404
387018
|
throw new Error(`Not a path under ${area}: ${JSON.stringify(candidate)}`);
|
|
386405
387019
|
}
|
|
386406
387020
|
return resolved;
|
|
@@ -386411,7 +387025,7 @@ class VersionStore {
|
|
|
386411
387025
|
await this.discard(staged);
|
|
386412
387026
|
return false;
|
|
386413
387027
|
}
|
|
386414
|
-
await fs23.promises.mkdir(
|
|
387028
|
+
await fs23.promises.mkdir(path46.dirname(target), { recursive: true });
|
|
386415
387029
|
await fs23.promises.rename(this.within(STAGING_DIR_NAME, staged.stagingPath), target);
|
|
386416
387030
|
return true;
|
|
386417
387031
|
}
|
|
@@ -386457,7 +387071,7 @@ class VersionStore {
|
|
|
386457
387071
|
if (!await exists(packagePath))
|
|
386458
387072
|
return null;
|
|
386459
387073
|
const heldPath = safeJoinUnderRoot(this.environmentPath, LEGACY_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
386460
|
-
await fs23.promises.mkdir(
|
|
387074
|
+
await fs23.promises.mkdir(path46.dirname(heldPath), { recursive: true });
|
|
386461
387075
|
await fs23.promises.rename(packagePath, heldPath);
|
|
386462
387076
|
return { packageName, heldPath };
|
|
386463
387077
|
}
|
|
@@ -386468,7 +387082,7 @@ class VersionStore {
|
|
|
386468
387082
|
let leftover = null;
|
|
386469
387083
|
if (await exists(packagePath)) {
|
|
386470
387084
|
leftover = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${held.packageName}-${crypto5.randomUUID()}`);
|
|
386471
|
-
await fs23.promises.mkdir(
|
|
387085
|
+
await fs23.promises.mkdir(path46.dirname(leftover), { recursive: true });
|
|
386472
387086
|
await fs23.promises.rename(packagePath, leftover);
|
|
386473
387087
|
}
|
|
386474
387088
|
try {
|
|
@@ -386561,10 +387175,10 @@ class VersionStore {
|
|
|
386561
387175
|
}
|
|
386562
387176
|
}
|
|
386563
387177
|
async function readManifestVersion(packagePath) {
|
|
386564
|
-
const manifestPath =
|
|
387178
|
+
const manifestPath = path46.join(packagePath, PACKAGE_MANIFEST_NAME);
|
|
386565
387179
|
let text;
|
|
386566
387180
|
try {
|
|
386567
|
-
text = await readPackageURL(packagePath,
|
|
387181
|
+
text = await readPackageURL(packagePath, pathToFileURL26(manifestPath));
|
|
386568
387182
|
} catch {
|
|
386569
387183
|
throw new PackageVersionError("MANIFEST_VERSION_MISSING", `The package has no ${PACKAGE_MANIFEST_NAME}, so it declares no version. Add one with a "version" field (for example "1.0.0") to publish it.`);
|
|
386570
387184
|
}
|
|
@@ -386614,9 +387228,9 @@ var init_version_store = __esm(() => {
|
|
|
386614
387228
|
import { AsyncLocalStorage as AsyncLocalStorage8 } from "async_hooks";
|
|
386615
387229
|
import crypto6 from "crypto";
|
|
386616
387230
|
import * as fs24 from "fs";
|
|
386617
|
-
import * as
|
|
387231
|
+
import * as path47 from "path";
|
|
386618
387232
|
import { isDeepStrictEqual } from "util";
|
|
386619
|
-
import { pathToFileURL as
|
|
387233
|
+
import { pathToFileURL as pathToFileURL27 } from "url";
|
|
386620
387234
|
function mergePackageManifest(existingManifest, metadata) {
|
|
386621
387235
|
const onDiskMaterialization = existingManifest.materialization !== null && typeof existingManifest.materialization === "object" && !Array.isArray(existingManifest.materialization) ? existingManifest.materialization : undefined;
|
|
386622
387236
|
const resolvedScope = metadata.scope ?? onDiskMaterialization?.scope ?? existingManifest.scope;
|
|
@@ -386818,7 +387432,7 @@ var init_environment = __esm(() => {
|
|
|
386818
387432
|
async writeEnvironmentReadme(readme) {
|
|
386819
387433
|
if (readme === undefined)
|
|
386820
387434
|
return;
|
|
386821
|
-
const readmePath =
|
|
387435
|
+
const readmePath = path47.join(this.environmentPath, "README.md");
|
|
386822
387436
|
try {
|
|
386823
387437
|
await fs24.promises.writeFile(readmePath, readme, "utf-8");
|
|
386824
387438
|
logger.info(`Updated README.md for environment ${this.environmentName}`);
|
|
@@ -387091,7 +387705,7 @@ var init_environment = __esm(() => {
|
|
|
387091
387705
|
const connections = this.lastChangedConnections;
|
|
387092
387706
|
next.refreshBuildPlan({
|
|
387093
387707
|
retryFailed,
|
|
387094
|
-
isStale: () => next.getVersionId() === undefined && this.
|
|
387708
|
+
isStale: () => next.getVersionId() === undefined && this.getRefusedReloads().has(next.getPackageName())
|
|
387095
387709
|
}).then((derived) => {
|
|
387096
387710
|
if (derived) {
|
|
387097
387711
|
const backoff = this.planRefreshBackoff.get(next);
|
|
@@ -387426,14 +388040,14 @@ var init_environment = __esm(() => {
|
|
|
387426
388040
|
if (await isLink(target))
|
|
387427
388041
|
throw outside();
|
|
387428
388042
|
try {
|
|
387429
|
-
await confinedPackagePath(packageRoot,
|
|
388043
|
+
await confinedPackagePath(packageRoot, pathToFileURL27(target));
|
|
387430
388044
|
} catch (error) {
|
|
387431
388045
|
if (error instanceof ImportOutsidePackageError)
|
|
387432
388046
|
throw outside();
|
|
387433
388047
|
throw error;
|
|
387434
388048
|
}
|
|
387435
388049
|
const missing = [];
|
|
387436
|
-
let dir =
|
|
388050
|
+
let dir = path47.dirname(target);
|
|
387437
388051
|
while (dir.startsWith(packageRoot)) {
|
|
387438
388052
|
const stat = await fs24.promises.stat(dir).catch((error) => {
|
|
387439
388053
|
const code = error.code;
|
|
@@ -387445,11 +388059,11 @@ var init_environment = __esm(() => {
|
|
|
387445
388059
|
if (await isLink(dir))
|
|
387446
388060
|
throw outside();
|
|
387447
388061
|
missing.push(dir);
|
|
387448
|
-
dir =
|
|
388062
|
+
dir = path47.dirname(dir);
|
|
387449
388063
|
continue;
|
|
387450
388064
|
}
|
|
387451
388065
|
if (!stat.isDirectory())
|
|
387452
|
-
throw new InvalidModelPathError(`Invalid model path: \`${
|
|
388066
|
+
throw new InvalidModelPathError(`Invalid model path: \`${path47.relative(packageRoot, dir).split(path47.sep).join("/")}\` ` + `is a file in the package, not a directory.`);
|
|
387453
388067
|
break;
|
|
387454
388068
|
}
|
|
387455
388069
|
const [realRoot, realExisting, realTarget] = await Promise.all([
|
|
@@ -387464,10 +388078,10 @@ var init_environment = __esm(() => {
|
|
|
387464
388078
|
for (const real of [realExisting, realTarget]) {
|
|
387465
388079
|
if (real === undefined)
|
|
387466
388080
|
continue;
|
|
387467
|
-
if (real !== realRoot && !real.startsWith(`${realRoot}${
|
|
388081
|
+
if (real !== realRoot && !real.startsWith(`${realRoot}${path47.sep}`)) {
|
|
387468
388082
|
throw new InvalidModelPathError(`Invalid model path: it resolves outside the package.`);
|
|
387469
388083
|
}
|
|
387470
|
-
if (isUnderPublicDir(
|
|
388084
|
+
if (isUnderPublicDir(path47.relative(realRoot, real).split(path47.sep).join("/"))) {
|
|
387471
388085
|
throw new InvalidModelPathError(`Invalid model path: it resolves into \`public/\`, which is served ` + `as raw static files.`);
|
|
387472
388086
|
}
|
|
387473
388087
|
}
|
|
@@ -387577,7 +388191,7 @@ var init_environment = __esm(() => {
|
|
|
387577
388191
|
const dir = safeJoinUnderRoot(environmentPath, dirName);
|
|
387578
388192
|
if (dir.indexOf("..") !== -1)
|
|
387579
388193
|
continue;
|
|
387580
|
-
if (
|
|
388194
|
+
if (path47.basename(dir) !== dirName)
|
|
387581
388195
|
continue;
|
|
387582
388196
|
try {
|
|
387583
388197
|
await fs24.promises.rm(dir, { recursive: true, force: true });
|
|
@@ -388586,7 +389200,7 @@ var init_environment = __esm(() => {
|
|
|
388586
389200
|
}
|
|
388587
389201
|
async stageDownload(packageName, downloader) {
|
|
388588
389202
|
const stagingPath = this.allocateStagingPath(packageName);
|
|
388589
|
-
await fs24.promises.mkdir(
|
|
389203
|
+
await fs24.promises.mkdir(path47.dirname(stagingPath), { recursive: true });
|
|
388590
389204
|
logger.debug("install.phase1.download.started", {
|
|
388591
389205
|
environmentName: this.environmentName,
|
|
388592
389206
|
packageName,
|
|
@@ -388654,7 +389268,7 @@ var init_environment = __esm(() => {
|
|
|
388654
389268
|
const oldExistsOnDisk = await fs24.promises.access(canonicalPath).then(() => true).catch(() => false);
|
|
388655
389269
|
if (oldExistsOnDisk) {
|
|
388656
389270
|
retiredPath = this.allocateRetiredPath(packageName);
|
|
388657
|
-
await fs24.promises.mkdir(
|
|
389271
|
+
await fs24.promises.mkdir(path47.dirname(retiredPath), {
|
|
388658
389272
|
recursive: true
|
|
388659
389273
|
});
|
|
388660
389274
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -389013,7 +389627,7 @@ var init_environment = __esm(() => {
|
|
|
389013
389627
|
const packagePath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
389014
389628
|
const manifestPath = safeJoinUnderRoot(packagePath, "publisher.json");
|
|
389015
389629
|
try {
|
|
389016
|
-
await confinedPackagePath(packagePath,
|
|
389630
|
+
await confinedPackagePath(packagePath, pathToFileURL27(manifestPath));
|
|
389017
389631
|
} catch (error) {
|
|
389018
389632
|
if (!(error instanceof ImportOutsidePackageError))
|
|
389019
389633
|
throw error;
|
|
@@ -389023,7 +389637,7 @@ var init_environment = __esm(() => {
|
|
|
389023
389637
|
let existingManifest = {};
|
|
389024
389638
|
let existingRead = false;
|
|
389025
389639
|
try {
|
|
389026
|
-
existingManifest = JSON.parse(await readPackageURL(packagePath,
|
|
389640
|
+
existingManifest = JSON.parse(await readPackageURL(packagePath, pathToFileURL27(manifestPath)));
|
|
389027
389641
|
existingRead = true;
|
|
389028
389642
|
} catch (_err) {
|
|
389029
389643
|
logger.warn(`Could not read manifest for ${packageName}`);
|
|
@@ -389031,7 +389645,7 @@ var init_environment = __esm(() => {
|
|
|
389031
389645
|
const updatedManifest = mergePackageManifest(existingManifest, metadata);
|
|
389032
389646
|
if (metadata.location !== undefined && metadata.location !== "") {
|
|
389033
389647
|
const recordPath = this.installRecordPath(packageName);
|
|
389034
|
-
await fs24.promises.mkdir(
|
|
389648
|
+
await fs24.promises.mkdir(path47.dirname(recordPath), {
|
|
389035
389649
|
recursive: true
|
|
389036
389650
|
});
|
|
389037
389651
|
await fs24.promises.writeFile(recordPath, JSON.stringify({ location: metadata.location }, null, 2), "utf-8");
|
|
@@ -389041,7 +389655,7 @@ var init_environment = __esm(() => {
|
|
|
389041
389655
|
if (error.code !== "ENOENT")
|
|
389042
389656
|
throw error;
|
|
389043
389657
|
});
|
|
389044
|
-
const temporary =
|
|
389658
|
+
const temporary = path47.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
389045
389659
|
try {
|
|
389046
389660
|
await fs24.promises.writeFile(temporary, JSON.stringify(updatedManifest, null, 2), { encoding: "utf-8", flag: "wx" });
|
|
389047
389661
|
await fs24.promises.rename(temporary, manifestPath);
|
|
@@ -389069,7 +389683,7 @@ var init_environment = __esm(() => {
|
|
|
389069
389683
|
async restorePackageManifestFile(packageName, text) {
|
|
389070
389684
|
const packagePath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
389071
389685
|
const manifestPath = safeJoinUnderRoot(packagePath, "publisher.json");
|
|
389072
|
-
const temporary =
|
|
389686
|
+
const temporary = path47.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
389073
389687
|
try {
|
|
389074
389688
|
if (text === null) {
|
|
389075
389689
|
await fs24.promises.rm(manifestPath, { force: true });
|
|
@@ -389299,6 +389913,15 @@ var init_environment = __esm(() => {
|
|
|
389299
389913
|
return this.lifecycle.failures();
|
|
389300
389914
|
}
|
|
389301
389915
|
getStaleCompileErrors() {
|
|
389916
|
+
const stale = new Map(this.lifecycle.staleRecords());
|
|
389917
|
+
for (const [packageName, pkg] of this.packages) {
|
|
389918
|
+
const kept = pkg.getKeptModelStaleness();
|
|
389919
|
+
if (kept && !stale.has(packageName))
|
|
389920
|
+
stale.set(packageName, kept);
|
|
389921
|
+
}
|
|
389922
|
+
return stale;
|
|
389923
|
+
}
|
|
389924
|
+
getRefusedReloads() {
|
|
389302
389925
|
return this.lifecycle.staleRecords();
|
|
389303
389926
|
}
|
|
389304
389927
|
transition(packageName, event) {
|
|
@@ -389373,7 +389996,7 @@ var init_environment = __esm(() => {
|
|
|
389373
389996
|
const canonicalPath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
389374
389997
|
const retiredPath = this.allocateRetiredPath(packageName);
|
|
389375
389998
|
try {
|
|
389376
|
-
await fs24.promises.mkdir(
|
|
389999
|
+
await fs24.promises.mkdir(path47.dirname(retiredPath), {
|
|
389377
390000
|
recursive: true
|
|
389378
390001
|
});
|
|
389379
390002
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -389504,7 +390127,7 @@ var init_environment = __esm(() => {
|
|
|
389504
390127
|
};
|
|
389505
390128
|
}
|
|
389506
390129
|
async deleteDuckDBConnection(connectionName) {
|
|
389507
|
-
const duckdbPath =
|
|
390130
|
+
const duckdbPath = path47.join(this.environmentPath, `${connectionName}.duckdb`);
|
|
389508
390131
|
try {
|
|
389509
390132
|
await fs24.promises.rm(duckdbPath, { force: true });
|
|
389510
390133
|
logger.info(`Removed DuckDB connection file ${connectionName} from environment ${this.environmentName}`);
|
|
@@ -395704,12 +396327,12 @@ var require_extract_zip = __commonJS(function(exports, module) {
|
|
|
395704
396327
|
|
|
395705
396328
|
// src/service/package_sources/zip.ts
|
|
395706
396329
|
import * as fs26 from "fs";
|
|
395707
|
-
import * as
|
|
396330
|
+
import * as path48 from "path";
|
|
395708
396331
|
async function unzipEnvironment(absoluteEnvironmentPath) {
|
|
395709
396332
|
assertSafeEnvironmentPath(absoluteEnvironmentPath);
|
|
395710
|
-
const archiveDir =
|
|
395711
|
-
const unzippedEnvironmentPath =
|
|
395712
|
-
if (!unzippedEnvironmentPath.startsWith(archiveDir +
|
|
396333
|
+
const archiveDir = path48.resolve(path48.dirname(absoluteEnvironmentPath));
|
|
396334
|
+
const unzippedEnvironmentPath = path48.resolve(archiveDir, path48.basename(absoluteEnvironmentPath, ".zip"));
|
|
396335
|
+
if (!unzippedEnvironmentPath.startsWith(archiveDir + path48.sep)) {
|
|
395713
396336
|
throw new BadRequestError(`Refusing to unzip "${absoluteEnvironmentPath}": target escapes its directory`);
|
|
395714
396337
|
}
|
|
395715
396338
|
await extractZipInto(absoluteEnvironmentPath, unzippedEnvironmentPath);
|
|
@@ -395727,7 +396350,7 @@ async function extractZipInto(archivePath, targetDir) {
|
|
|
395727
396350
|
let totalUncompressedBytes = 0;
|
|
395728
396351
|
try {
|
|
395729
396352
|
await import_extract_zip.default(archivePath, {
|
|
395730
|
-
dir:
|
|
396353
|
+
dir: path48.resolve(targetDir),
|
|
395731
396354
|
onEntry: (entry) => {
|
|
395732
396355
|
if ((entry.externalFileAttributes >>> 16 & 61440) === 40960) {
|
|
395733
396356
|
throw new BadRequestError(`Refusing to unzip "${archivePath}": entry "${entry.fileName}" is a symbolic link`);
|
|
@@ -395756,7 +396379,7 @@ var init_zip = __esm(() => {
|
|
|
395756
396379
|
|
|
395757
396380
|
// src/service/package_sources/gcs_source.ts
|
|
395758
396381
|
import * as fs27 from "fs";
|
|
395759
|
-
import * as
|
|
396382
|
+
import * as path49 from "path";
|
|
395760
396383
|
function isGCSURL(location) {
|
|
395761
396384
|
return location.startsWith("gs://");
|
|
395762
396385
|
}
|
|
@@ -395794,7 +396417,7 @@ class GcsPackageSource {
|
|
|
395794
396417
|
if (file.name.endsWith("/")) {
|
|
395795
396418
|
return;
|
|
395796
396419
|
}
|
|
395797
|
-
await fs27.promises.mkdir(
|
|
396420
|
+
await fs27.promises.mkdir(path49.dirname(absoluteFilePath), {
|
|
395798
396421
|
recursive: true
|
|
395799
396422
|
});
|
|
395800
396423
|
return fs27.promises.writeFile(absoluteFilePath, await file.download());
|
|
@@ -396038,9 +396661,9 @@ var init_git_source = __esm(() => {
|
|
|
396038
396661
|
// src/service/package_sources/local_source.ts
|
|
396039
396662
|
import * as fs29 from "fs";
|
|
396040
396663
|
import * as os8 from "os";
|
|
396041
|
-
import * as
|
|
396664
|
+
import * as path50 from "path";
|
|
396042
396665
|
function isLocalPath(location) {
|
|
396043
|
-
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") ||
|
|
396666
|
+
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") || path50.isAbsolute(location);
|
|
396044
396667
|
}
|
|
396045
396668
|
function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
396046
396669
|
let expanded = location;
|
|
@@ -396049,9 +396672,9 @@ function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
|
396049
396672
|
if (!home) {
|
|
396050
396673
|
throw new Error(`Cannot expand "~" in location "${location}": home directory is not set`);
|
|
396051
396674
|
}
|
|
396052
|
-
expanded =
|
|
396675
|
+
expanded = path50.join(home, location.slice(2));
|
|
396053
396676
|
}
|
|
396054
|
-
return
|
|
396677
|
+
return path50.isAbsolute(expanded) ? expanded : path50.join(anchorDir, expanded);
|
|
396055
396678
|
}
|
|
396056
396679
|
|
|
396057
396680
|
class LocalPackageSource {
|
|
@@ -396089,7 +396712,7 @@ var init_local_source = __esm(() => {
|
|
|
396089
396712
|
|
|
396090
396713
|
// src/service/package_sources/s3_source.ts
|
|
396091
396714
|
import * as fs30 from "fs";
|
|
396092
|
-
import * as
|
|
396715
|
+
import * as path51 from "path";
|
|
396093
396716
|
import { Writable } from "stream";
|
|
396094
396717
|
function isS3URL(location) {
|
|
396095
396718
|
return location.startsWith("s3://");
|
|
@@ -396113,7 +396736,7 @@ class S3PackageSource {
|
|
|
396113
396736
|
const s3Client = this.client();
|
|
396114
396737
|
if (isCompressedFile) {
|
|
396115
396738
|
const zipFilePath = `${absoluteDirPath}.zip`;
|
|
396116
|
-
await fs30.promises.mkdir(
|
|
396739
|
+
await fs30.promises.mkdir(path51.dirname(zipFilePath), {
|
|
396117
396740
|
recursive: true
|
|
396118
396741
|
});
|
|
396119
396742
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -396148,7 +396771,7 @@ class S3PackageSource {
|
|
|
396148
396771
|
return;
|
|
396149
396772
|
}
|
|
396150
396773
|
const absoluteFilePath = safeJoinUnderRoot(absoluteDirPath, relativeFilePath);
|
|
396151
|
-
await fs30.promises.mkdir(
|
|
396774
|
+
await fs30.promises.mkdir(path51.dirname(absoluteFilePath), {
|
|
396152
396775
|
recursive: true
|
|
396153
396776
|
});
|
|
396154
396777
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -396175,7 +396798,7 @@ var init_s3_source = __esm(() => {
|
|
|
396175
396798
|
|
|
396176
396799
|
// src/service/package_sources/index.ts
|
|
396177
396800
|
import { Storage as Storage2 } from "@google-cloud/storage";
|
|
396178
|
-
import * as
|
|
396801
|
+
import * as path52 from "path";
|
|
396179
396802
|
|
|
396180
396803
|
class PackageSources {
|
|
396181
396804
|
resolveLocalPath;
|
|
@@ -396242,7 +396865,7 @@ class PackageSources {
|
|
|
396242
396865
|
} else if (packageLocation.startsWith("s3://")) {
|
|
396243
396866
|
await this.s3.fetch(packageLocation, targetPath, opts);
|
|
396244
396867
|
}
|
|
396245
|
-
if (packageLocation.startsWith("/") ||
|
|
396868
|
+
if (packageLocation.startsWith("/") || path52.isAbsolute(packageLocation)) {
|
|
396246
396869
|
await this.local.fetch(packageLocation, targetPath, opts);
|
|
396247
396870
|
}
|
|
396248
396871
|
}
|
|
@@ -396266,7 +396889,7 @@ var init_package_sources = __esm(() => {
|
|
|
396266
396889
|
// src/service/environment_store.ts
|
|
396267
396890
|
import crypto7 from "crypto";
|
|
396268
396891
|
import * as fs31 from "fs";
|
|
396269
|
-
import * as
|
|
396892
|
+
import * as path53 from "path";
|
|
396270
396893
|
function codesField(message) {
|
|
396271
396894
|
const codes = codesOfLines(message);
|
|
396272
396895
|
return codes.length > 0 ? { codes } : {};
|
|
@@ -396373,7 +396996,7 @@ class EnvironmentStore {
|
|
|
396373
396996
|
const storageConfig = {
|
|
396374
396997
|
type: "duckdb",
|
|
396375
396998
|
duckdb: {
|
|
396376
|
-
path:
|
|
396999
|
+
path: path53.join(serverRootPath, "publisher.db")
|
|
396377
397000
|
}
|
|
396378
397001
|
};
|
|
396379
397002
|
this.storageManager = deps.storageManager ?? new StorageManager(storageConfig);
|
|
@@ -397055,7 +397678,7 @@ class EnvironmentStore {
|
|
|
397055
397678
|
const reInit = settings.get("initializeStorage");
|
|
397056
397679
|
await fs31.promises.mkdir(this.serverRootPath, { recursive: true });
|
|
397057
397680
|
if (reInit) {
|
|
397058
|
-
const uploadDocsPath =
|
|
397681
|
+
const uploadDocsPath = path53.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
397059
397682
|
logger.info(`Reinitialization mode: Cleaning up upload documents path ${uploadDocsPath}`);
|
|
397060
397683
|
try {
|
|
397061
397684
|
await fs31.promises.rm(uploadDocsPath, {
|
|
@@ -397072,7 +397695,7 @@ class EnvironmentStore {
|
|
|
397072
397695
|
} else {
|
|
397073
397696
|
logger.info(`Using existing publisher path`);
|
|
397074
397697
|
}
|
|
397075
|
-
const uploadDocsPath =
|
|
397698
|
+
const uploadDocsPath = path53.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
397076
397699
|
await fs31.promises.mkdir(uploadDocsPath, { recursive: true });
|
|
397077
397700
|
}
|
|
397078
397701
|
async listEnvironments(skipInitializationCheck = false, options = {}) {
|
|
@@ -397496,7 +398119,7 @@ class EnvironmentStore {
|
|
|
397496
398119
|
const isInPlace = this.inPlaceEnvs.has(environmentName) && isLocalPath(_package.location) && !isLocalArchive;
|
|
397497
398120
|
if (isInPlace) {
|
|
397498
398121
|
await clearMountTarget(absolutePackagePath);
|
|
397499
|
-
const absoluteSourcePath =
|
|
398122
|
+
const absoluteSourcePath = path53.resolve(sourcePath);
|
|
397500
398123
|
const linkType = process.platform === "win32" ? "junction" : "dir";
|
|
397501
398124
|
try {
|
|
397502
398125
|
await fs31.promises.symlink(absoluteSourcePath, absolutePackagePath, linkType);
|
|
@@ -397626,7 +398249,7 @@ var init_environment_store = __esm(() => {
|
|
|
397626
398249
|
|
|
397627
398250
|
// src/controller/watch-mode.controller.ts
|
|
397628
398251
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
397629
|
-
import
|
|
398252
|
+
import path54 from "path";
|
|
397630
398253
|
|
|
397631
398254
|
class WatchModeController {
|
|
397632
398255
|
environmentStore;
|
|
@@ -397670,7 +398293,7 @@ class WatchModeController {
|
|
|
397670
398293
|
ignored: (filePath, stats) => {
|
|
397671
398294
|
if (!stats?.isFile())
|
|
397672
398295
|
return false;
|
|
397673
|
-
const ext =
|
|
398296
|
+
const ext = path54.extname(filePath).toLowerCase();
|
|
397674
398297
|
return !MODEL_EXTS.has(ext) && !ASSET_EXTS.has(ext);
|
|
397675
398298
|
},
|
|
397676
398299
|
ignoreInitial: true
|
|
@@ -397690,12 +398313,12 @@ class WatchModeController {
|
|
|
397690
398313
|
};
|
|
397691
398314
|
const onEvent = (kind) => async (filePath) => {
|
|
397692
398315
|
logger.info(`Watch ${kind}: ${filePath}; environment=${watchName}`);
|
|
397693
|
-
const rel =
|
|
397694
|
-
const segments = rel.split(
|
|
398316
|
+
const rel = path54.relative(this.watchingPath ?? "", filePath);
|
|
398317
|
+
const segments = rel.split(path54.sep);
|
|
397695
398318
|
const pkgName = segments.length > 1 && segments[0] && !segments[0].startsWith("..") ? segments[0] : null;
|
|
397696
398319
|
if (!pkgName)
|
|
397697
398320
|
return;
|
|
397698
|
-
const ext =
|
|
398321
|
+
const ext = path54.extname(filePath).toLowerCase();
|
|
397699
398322
|
if (MODEL_EXTS.has(ext)) {
|
|
397700
398323
|
const recompiled = await reloadPackage(pkgName);
|
|
397701
398324
|
if (!recompiled)
|
|
@@ -397768,7 +398391,7 @@ var init_watch_mode_controller = __esm(() => {
|
|
|
397768
398391
|
// src/mcp_config.ts
|
|
397769
398392
|
import * as fs32 from "fs";
|
|
397770
398393
|
import * as os9 from "os";
|
|
397771
|
-
import * as
|
|
398394
|
+
import * as path55 from "path";
|
|
397772
398395
|
function malloyServer(endpoint) {
|
|
397773
398396
|
return { type: "http", url: endpoint };
|
|
397774
398397
|
}
|
|
@@ -397791,11 +398414,11 @@ function mcpEndpoint(host, port) {
|
|
|
397791
398414
|
return `http://${host}:${port}/mcp`;
|
|
397792
398415
|
}
|
|
397793
398416
|
function findGitWorkTreeRoot(dir) {
|
|
397794
|
-
let current =
|
|
398417
|
+
let current = path55.resolve(dir);
|
|
397795
398418
|
for (;; ) {
|
|
397796
|
-
if (fs32.existsSync(
|
|
398419
|
+
if (fs32.existsSync(path55.join(current, ".git")))
|
|
397797
398420
|
return current;
|
|
397798
|
-
const parent =
|
|
398421
|
+
const parent = path55.dirname(current);
|
|
397799
398422
|
if (parent === current)
|
|
397800
398423
|
return;
|
|
397801
398424
|
current = parent;
|
|
@@ -397818,7 +398441,7 @@ function mcpConfigEnabled() {
|
|
|
397818
398441
|
}
|
|
397819
398442
|
function ensureMcpConfig(options) {
|
|
397820
398443
|
const { dir, endpoint, requestedPort, boundPort, homeDir } = options;
|
|
397821
|
-
const file =
|
|
398444
|
+
const file = path55.join(dir, MCP_CONFIG_FILENAME);
|
|
397822
398445
|
try {
|
|
397823
398446
|
const existing = (() => {
|
|
397824
398447
|
try {
|
|
@@ -397845,18 +398468,18 @@ function ensureMcpConfig(options) {
|
|
|
397845
398468
|
try {
|
|
397846
398469
|
return fs32.realpathSync(p);
|
|
397847
398470
|
} catch {
|
|
397848
|
-
return
|
|
398471
|
+
return path55.resolve(p);
|
|
397849
398472
|
}
|
|
397850
398473
|
};
|
|
397851
398474
|
if (realish(dir) === realish(homeDir ?? os9.homedir())) {
|
|
397852
398475
|
return { action: "skipped-home", dir, endpoint, staleConfig };
|
|
397853
398476
|
}
|
|
397854
|
-
if (
|
|
398477
|
+
if (path55.resolve(dir) === path55.parse(path55.resolve(dir)).root) {
|
|
397855
398478
|
return { action: "skipped-root", dir, endpoint, staleConfig };
|
|
397856
398479
|
}
|
|
397857
398480
|
const gitRoot = findGitWorkTreeRoot(dir);
|
|
397858
398481
|
if (gitRoot !== undefined) {
|
|
397859
|
-
const rootCandidate =
|
|
398482
|
+
const rootCandidate = path55.join(gitRoot, MCP_CONFIG_FILENAME);
|
|
397860
398483
|
return {
|
|
397861
398484
|
action: "skipped-git",
|
|
397862
398485
|
dir,
|
|
@@ -400369,7 +400992,7 @@ function scrubForEgress(text) {
|
|
|
400369
400992
|
var PROVIDER_FAILURE_COOLDOWN_MS = 60000;
|
|
400370
400993
|
|
|
400371
400994
|
// src/retrieval/index/schema_index.ts
|
|
400372
|
-
import { createHash as
|
|
400995
|
+
import { createHash as createHash20 } from "crypto";
|
|
400373
400996
|
function recordMembers(columns) {
|
|
400374
400997
|
const records = new Set(columns.filter((c) => isRecordColumnType(c.type)).map((c) => c.name));
|
|
400375
400998
|
const members = new Set;
|
|
@@ -400412,7 +401035,7 @@ function tableIndexText(entity) {
|
|
|
400412
401035
|
}
|
|
400413
401036
|
function schemaFingerprint(tables) {
|
|
400414
401037
|
const canonical = tables.map((t) => `${t.resource}\x00${t.columns.map((c) => `${c.name}:${c.type ?? ""}`).join(",")}`).sort().join("\x01");
|
|
400415
|
-
return
|
|
401038
|
+
return createHash20("sha256").update(canonical).digest("hex");
|
|
400416
401039
|
}
|
|
400417
401040
|
function rankLexically(tables, query, limit, cache) {
|
|
400418
401041
|
const sanitized = sanitizeLunrQuery(query);
|
|
@@ -400730,8 +401353,8 @@ var init_registry3 = __esm(() => {
|
|
|
400730
401353
|
});
|
|
400731
401354
|
|
|
400732
401355
|
// src/retrieval/model/package_entities.ts
|
|
400733
|
-
import
|
|
400734
|
-
import { fileURLToPath as
|
|
401356
|
+
import path56 from "path";
|
|
401357
|
+
import { fileURLToPath as fileURLToPath23 } from "url";
|
|
400735
401358
|
import { parseAnnotation as parseAnnotation3 } from "@malloydata/malloy-tag";
|
|
400736
401359
|
function truncateDoc(doc, max) {
|
|
400737
401360
|
if (doc.length <= max)
|
|
@@ -400830,7 +401453,7 @@ function makeSourceTextReader(pkg) {
|
|
|
400830
401453
|
let text;
|
|
400831
401454
|
try {
|
|
400832
401455
|
if (url.startsWith("file:") && packagePath) {
|
|
400833
|
-
const relative =
|
|
401456
|
+
const relative = path56.relative(packagePath, fileURLToPath23(url)).split(path56.sep).join("/");
|
|
400834
401457
|
text = relative && !relative.startsWith("..") ? pkg.getModel?.(relative)?.getCompiledSourceText?.() : undefined;
|
|
400835
401458
|
}
|
|
400836
401459
|
} catch {
|
|
@@ -401754,7 +402377,7 @@ var init_response2 = __esm(() => {
|
|
|
401754
402377
|
|
|
401755
402378
|
// src/retrieval/model/catalog.ts
|
|
401756
402379
|
import { isSourceDef as isSourceDef21 } from "@malloydata/malloy";
|
|
401757
|
-
import { createHash as
|
|
402380
|
+
import { createHash as createHash21 } from "crypto";
|
|
401758
402381
|
function byText(a, b) {
|
|
401759
402382
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
401760
402383
|
}
|
|
@@ -402685,7 +403308,7 @@ function readDefinitionOf(modelDef, name) {
|
|
|
402685
403308
|
const kept = value.filter((v) => !isOtherNote(v));
|
|
402686
403309
|
return key === "fields" ? kept.map((f) => isTableColumn(f) ? { name: f.name } : f).sort((a, b) => compareFieldNames(a, b)) : kept;
|
|
402687
403310
|
});
|
|
402688
|
-
return
|
|
403311
|
+
return createHash21("sha256").update(text, "utf8").digest("hex");
|
|
402689
403312
|
}
|
|
402690
403313
|
function isSecureGiven(g) {
|
|
402691
403314
|
return (g.annotations ?? []).some((a) => /secure/i.test(a));
|
|
@@ -402857,7 +403480,7 @@ var init_catalog_store = __esm(() => {
|
|
|
402857
403480
|
});
|
|
402858
403481
|
|
|
402859
403482
|
// src/retrieval/llm/prompts/source_summary.ts
|
|
402860
|
-
import { createHash as
|
|
403483
|
+
import { createHash as createHash22 } from "crypto";
|
|
402861
403484
|
function undocumentedOneLine(sourceName) {
|
|
402862
403485
|
return `The \`${sourceName}\` source.`;
|
|
402863
403486
|
}
|
|
@@ -402877,7 +403500,7 @@ function renderSourceSummaryUserPrompt(input) {
|
|
|
402877
403500
|
`);
|
|
402878
403501
|
}
|
|
402879
403502
|
function sourceSummaryPromptHash(instructions) {
|
|
402880
|
-
return
|
|
403503
|
+
return createHash22("sha256").update(instructions).update("\x00").update(renderSourceSummaryUserPrompt({ source: "", doc: "", fields: "" })).digest("hex");
|
|
402881
403504
|
}
|
|
402882
403505
|
var ONE_LINE_SUMMARY_MAX_CHARS2 = 120, NO_SOURCE_DOCS = "No source docs.", DEFAULT_SOURCE_SUMMARY_INSTRUCTIONS, REPLY_FORMAT = `Reply with one JSON object and nothing else:
|
|
402883
403506
|
{"summary": "<prose>", "one_line_summary": "<one sentence>"}`;
|
|
@@ -403035,7 +403658,7 @@ var init_llm_calls = __esm(() => {
|
|
|
403035
403658
|
});
|
|
403036
403659
|
|
|
403037
403660
|
// src/retrieval/index/source_summaries.ts
|
|
403038
|
-
import { createHash as
|
|
403661
|
+
import { createHash as createHash23 } from "crypto";
|
|
403039
403662
|
function resolveSourceSummarySettings(pkg, chatSlot) {
|
|
403040
403663
|
const retrieval = pkg?.getRetrievalSettings?.() ?? DEFAULT_PACKAGE_RETRIEVAL;
|
|
403041
403664
|
if (sourceSummaryConfigOf(retrieval).enabled === false)
|
|
@@ -403232,7 +403855,7 @@ function boundedPrompt(name, doc, own, resolve, maxPromptChars) {
|
|
|
403232
403855
|
}
|
|
403233
403856
|
}
|
|
403234
403857
|
function sourceSummaryInputHash(input, settings) {
|
|
403235
|
-
return
|
|
403858
|
+
return createHash23("sha256").update(settings.promptHash).update("\x00").update(settings.modelId).update("\x00").update(input.prompt).digest("hex");
|
|
403236
403859
|
}
|
|
403237
403860
|
function currentSummaryHashes(entities, settings, hashesCache) {
|
|
403238
403861
|
const frozen = Object.isFrozen(entities);
|
|
@@ -403559,9 +404182,9 @@ var init_derived_text = __esm(() => {
|
|
|
403559
404182
|
});
|
|
403560
404183
|
|
|
403561
404184
|
// src/retrieval/llm/llm_cache.ts
|
|
403562
|
-
import { createHash as
|
|
404185
|
+
import { createHash as createHash24 } from "crypto";
|
|
403563
404186
|
function sha256(text) {
|
|
403564
|
-
return
|
|
404187
|
+
return createHash24("sha256").update(text).digest("hex");
|
|
403565
404188
|
}
|
|
403566
404189
|
async function generateCached(args) {
|
|
403567
404190
|
const { db, table, environmentName, packageName } = args;
|
|
@@ -404334,7 +404957,7 @@ var init_vectors = __esm(() => {
|
|
|
404334
404957
|
});
|
|
404335
404958
|
|
|
404336
404959
|
// src/retrieval/index/values_index.ts
|
|
404337
|
-
import { createHash as
|
|
404960
|
+
import { createHash as createHash25 } from "crypto";
|
|
404338
404961
|
function partitionKeyPart(raw, type) {
|
|
404339
404962
|
const v = Array.isArray(raw) && raw.length === 1 ? raw[0] : raw;
|
|
404340
404963
|
if (v === null || v === undefined || Array.isArray(v))
|
|
@@ -404865,14 +405488,14 @@ async function connectionsDigest(read) {
|
|
|
404865
405488
|
try {
|
|
404866
405489
|
const environment = await read.environmentStore.getEnvironment(parseEnvironmentName(read.environmentName));
|
|
404867
405490
|
const text = JSON.stringify(environment.listApiConnections(), (key, value) => key && CREDENTIAL_KEY.test(key) ? undefined : value);
|
|
404868
|
-
return
|
|
405491
|
+
return createHash25("sha256").update(text, "utf8").digest("hex");
|
|
404869
405492
|
} catch (error) {
|
|
404870
405493
|
logger.warn("[get_context fcj] The connections could not be read for the value read key; every dimension is read", { error: error instanceof Error ? error.message : String(error) });
|
|
404871
405494
|
return `unknown-${Date.now()}`;
|
|
404872
405495
|
}
|
|
404873
405496
|
}
|
|
404874
405497
|
function readKeyOf(readDefinition, node, cap, partitionKey, connections) {
|
|
404875
|
-
return
|
|
405498
|
+
return createHash25("sha256").update(JSON.stringify([
|
|
404876
405499
|
readDefinition,
|
|
404877
405500
|
node.modelPaths[0],
|
|
404878
405501
|
node.source,
|
|
@@ -407147,7 +407770,7 @@ var init_judge2 = __esm(() => {
|
|
|
407147
407770
|
});
|
|
407148
407771
|
|
|
407149
407772
|
// src/retrieval/search/pages.ts
|
|
407150
|
-
import { createHash as
|
|
407773
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
407151
407774
|
function pageAt(cards, offset, options) {
|
|
407152
407775
|
const room = options.maxChars - options.reserveChars;
|
|
407153
407776
|
let used = 2;
|
|
@@ -407239,7 +407862,7 @@ function resultKey(request) {
|
|
|
407239
407862
|
givens: request.givens ?? null,
|
|
407240
407863
|
filterParams: request.filterParams ?? null
|
|
407241
407864
|
};
|
|
407242
|
-
return
|
|
407865
|
+
return createHash26("sha256").update(canonicalJson2(normal)).digest("hex");
|
|
407243
407866
|
}
|
|
407244
407867
|
function canonicalJson2(value) {
|
|
407245
407868
|
if (Array.isArray(value)) {
|
|
@@ -441227,7 +441850,7 @@ var init_lossless_widening = __esm(() => {
|
|
|
441227
441850
|
});
|
|
441228
441851
|
|
|
441229
441852
|
// src/service/materialization/run/storage_table_load.ts
|
|
441230
|
-
import
|
|
441853
|
+
import path57 from "path";
|
|
441231
441854
|
function readerSql(uri, format, options = {}) {
|
|
441232
441855
|
const path = `'${escapeSQL(uri)}'`;
|
|
441233
441856
|
const args = [];
|
|
@@ -441276,8 +441899,8 @@ function assertUnderDataPath(uri, dataPath) {
|
|
|
441276
441899
|
throw outside();
|
|
441277
441900
|
}
|
|
441278
441901
|
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(uri)) {
|
|
441279
|
-
const resolved =
|
|
441280
|
-
if (!resolved.startsWith(`${
|
|
441902
|
+
const resolved = path57.resolve(uri);
|
|
441903
|
+
if (!resolved.startsWith(`${path57.resolve(root)}${path57.sep}`)) {
|
|
441281
441904
|
throw outside();
|
|
441282
441905
|
}
|
|
441283
441906
|
}
|
|
@@ -441668,7 +442291,7 @@ function objectUnreadable(error, uris, byName = false) {
|
|
|
441668
442291
|
logInternalFailure("Load could not read an object", error, "warn");
|
|
441669
442292
|
const said = error.message.split(ECHOED_SQL)[0];
|
|
441670
442293
|
const object = uris.findIndex((uri) => said.includes(uri));
|
|
441671
|
-
const words = readerWords(error, uris.map((uri, i) => [uri, byName ?
|
|
442294
|
+
const words = readerWords(error, uris.map((uri, i) => [uri, byName ? path57.posix.basename(uri) : `objects[${i}]`]));
|
|
441672
442295
|
if (byName)
|
|
441673
442296
|
return new LoadRefusalError("OBJECT_UNREADABLE", words);
|
|
441674
442297
|
return new LoadRefusalError("OBJECT_UNREADABLE", object < 0 ? `An object of the load could not be read: ${words}` : `objects[${object}] could not be read: ${words}`, object < 0 ? undefined : { object });
|
|
@@ -442021,7 +442644,7 @@ var init_storage_table_load = __esm(() => {
|
|
|
442021
442644
|
});
|
|
442022
442645
|
|
|
442023
442646
|
// src/service/catalog_admin.ts
|
|
442024
|
-
import { createHash as
|
|
442647
|
+
import { createHash as createHash27, randomUUID as randomUUID6 } from "crypto";
|
|
442025
442648
|
async function withLoadSlot(fn) {
|
|
442026
442649
|
const slot = loadSlots.tryAcquire();
|
|
442027
442650
|
if (!slot) {
|
|
@@ -442883,7 +443506,7 @@ function idempotencyKeyDigest(key) {
|
|
|
442883
443506
|
if (key === "" || key.length > MAX_IDEMPOTENCY_KEY) {
|
|
442884
443507
|
throw badRequest(`'Idempotency-Key' must be 1 to ${MAX_IDEMPOTENCY_KEY} characters.`);
|
|
442885
443508
|
}
|
|
442886
|
-
return
|
|
443509
|
+
return createHash27("sha256").update(key).digest("hex");
|
|
442887
443510
|
}
|
|
442888
443511
|
function decodeCursor(after) {
|
|
442889
443512
|
const id = /^[A-Za-z0-9_-]+$/.test(after) ? Buffer.from(after, "base64url").toString() : "";
|
|
@@ -450321,7 +450944,7 @@ var require_ip_address = __commonJS(function(exports) {
|
|
|
450321
450944
|
import { isIPv6 } from "node:net";
|
|
450322
450945
|
import { isIPv6 as isIPv62 } from "node:net";
|
|
450323
450946
|
import { Buffer as Buffer4 } from "node:buffer";
|
|
450324
|
-
import { createHash as
|
|
450947
|
+
import { createHash as createHash28 } from "node:crypto";
|
|
450325
450948
|
import { isIP as isIP2 } from "node:net";
|
|
450326
450949
|
function ipKeyGenerator(ip, ipv6Subnet = 56) {
|
|
450327
450950
|
if (isIPv6(ip)) {
|
|
@@ -450419,7 +451042,7 @@ var import_ip_address, import_debug2, ipv4CompatibleSubnet, MemoryStore = class
|
|
|
450419
451042
|
}
|
|
450420
451043
|
return resetSeconds;
|
|
450421
451044
|
}, getPartitionKey = (key) => {
|
|
450422
|
-
const hash =
|
|
451045
|
+
const hash = createHash28("sha256");
|
|
450423
451046
|
hash.update(key);
|
|
450424
451047
|
const partitionKey = hash.digest("hex").slice(0, 12);
|
|
450425
451048
|
return Buffer4.from(partitionKey).toString("base64");
|
|
@@ -451259,9 +451882,9 @@ var init_server_old = __esm(() => {
|
|
|
451259
451882
|
});
|
|
451260
451883
|
|
|
451261
451884
|
// src/authorize_bypass_header.ts
|
|
451262
|
-
import { createHash as
|
|
451885
|
+
import { createHash as createHash29, timingSafeEqual } from "node:crypto";
|
|
451263
451886
|
var BYPASS_AUTHORIZE_HEADER = "x-publisher-bypass-authorize", secretsMatch = (presented, configured) => {
|
|
451264
|
-
const digest = (value) =>
|
|
451887
|
+
const digest = (value) => createHash29("sha256").update(value, "utf8").digest();
|
|
451265
451888
|
return timingSafeEqual(digest(presented), digest(configured));
|
|
451266
451889
|
}, readBypassAuthorize = (req) => {
|
|
451267
451890
|
const configured = settings.get("authorize.bypassSecret");
|
|
@@ -451739,8 +452362,8 @@ var init_api = __esm(() => {
|
|
|
451739
452362
|
|
|
451740
452363
|
// src/routes/data_apps.ts
|
|
451741
452364
|
import * as fsp from "fs/promises";
|
|
451742
|
-
import * as
|
|
451743
|
-
import { pathToFileURL as
|
|
452365
|
+
import * as path58 from "path";
|
|
452366
|
+
import { pathToFileURL as pathToFileURL28 } from "url";
|
|
451744
452367
|
async function serveFromPackage(environmentStore, req, res) {
|
|
451745
452368
|
const subPathRaw = req.params["0"] ?? "";
|
|
451746
452369
|
try {
|
|
@@ -451749,7 +452372,7 @@ async function serveFromPackage(environmentStore, req, res) {
|
|
|
451749
452372
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, {
|
|
451750
452373
|
versionId: VersionRef.parse(staticVersionId)
|
|
451751
452374
|
});
|
|
451752
|
-
const publicRoot =
|
|
452375
|
+
const publicRoot = path58.join(pkg.getPackagePath(), "public");
|
|
451753
452376
|
let subPath = subPathRaw;
|
|
451754
452377
|
if (subPath === "" || subPath.endsWith("/")) {
|
|
451755
452378
|
subPath = subPath + "index.html";
|
|
@@ -451817,7 +452440,7 @@ function registerDataAppListRoute(app, apiPrefix, environmentStore) {
|
|
|
451817
452440
|
app.get(`${apiPrefix}${DATA_APPS_ROUTE}`, apiRoute(async (req) => {
|
|
451818
452441
|
const environment = await environmentStore.getEnvironment(parseEnvironmentName(req.params.environmentName), false);
|
|
451819
452442
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, { versionId: versionRefOf(req) });
|
|
451820
|
-
return listPackageDataApps(req.params.environmentName, req.params.packageName,
|
|
452443
|
+
return listPackageDataApps(req.params.environmentName, req.params.packageName, path58.join(pkg.getPackagePath(), "public"), pkg.getPackageMetadata().versionId);
|
|
451821
452444
|
}));
|
|
451822
452445
|
}
|
|
451823
452446
|
function stripNonTagText(input) {
|
|
@@ -451832,7 +452455,7 @@ function stripNonTagText(input) {
|
|
|
451832
452455
|
async function servedPublic(publicRoot) {
|
|
451833
452456
|
let real;
|
|
451834
452457
|
try {
|
|
451835
|
-
real = await confinedPackagePath(
|
|
452458
|
+
real = await confinedPackagePath(path58.dirname(publicRoot), pathToFileURL28(publicRoot));
|
|
451836
452459
|
} catch {
|
|
451837
452460
|
return { kind: "outside" };
|
|
451838
452461
|
}
|
|
@@ -451844,11 +452467,11 @@ async function servedPublic(publicRoot) {
|
|
|
451844
452467
|
async function insidePublic(publicRoot, realPublic, file) {
|
|
451845
452468
|
let real;
|
|
451846
452469
|
try {
|
|
451847
|
-
real = await confinedPackagePath(
|
|
452470
|
+
real = await confinedPackagePath(path58.dirname(publicRoot), pathToFileURL28(file));
|
|
451848
452471
|
} catch {
|
|
451849
452472
|
return;
|
|
451850
452473
|
}
|
|
451851
|
-
return stepsOutside(
|
|
452474
|
+
return stepsOutside(path58.relative(realPublic, real)) ? undefined : real;
|
|
451852
452475
|
}
|
|
451853
452476
|
async function listPackageDataApps(environmentName, packageName, publicRoot, versionId) {
|
|
451854
452477
|
const out = [];
|
|
@@ -451868,14 +452491,14 @@ async function listPackageDataApps(environmentName, packageName, publicRoot, ver
|
|
|
451868
452491
|
for (const entry of entries) {
|
|
451869
452492
|
if (entry.name.startsWith(".") || entry.name === "node_modules")
|
|
451870
452493
|
continue;
|
|
451871
|
-
const full =
|
|
452494
|
+
const full = path58.join(dir, entry.name);
|
|
451872
452495
|
const real = await insidePublic(publicRoot, realPublic, full);
|
|
451873
452496
|
if (real === undefined)
|
|
451874
452497
|
continue;
|
|
451875
452498
|
if (entry.isDirectory()) {
|
|
451876
452499
|
await walk(full, real, depth + 1);
|
|
451877
452500
|
} else if (entry.isFile() && (entry.name.endsWith(".html") || entry.name.endsWith(".htm"))) {
|
|
451878
|
-
const rel =
|
|
452501
|
+
const rel = path58.relative(publicRoot, full).replace(/\\/g, "/");
|
|
451879
452502
|
let title = rel;
|
|
451880
452503
|
let fit;
|
|
451881
452504
|
try {
|
|
@@ -452054,9 +452677,9 @@ var init_spa_fallback = __esm(() => {
|
|
|
452054
452677
|
});
|
|
452055
452678
|
|
|
452056
452679
|
// src/routes/spa.ts
|
|
452057
|
-
import * as
|
|
452680
|
+
import * as path59 from "path";
|
|
452058
452681
|
function registerSpaFallback(app, apiPrefix, appRoot, environmentStore) {
|
|
452059
|
-
const SPA_INDEX =
|
|
452682
|
+
const SPA_INDEX = path59.resolve(appRoot, "index.html");
|
|
452060
452683
|
const escapeHtml = (value) => value.replace(/[<>&]/g, (c) => ({ "<": "<", ">": ">", "&": "&" })[c] ?? c);
|
|
452061
452684
|
const loadedPackage = (environmentName, packageName) => environmentStore.getLoadedEnvironments().find((environment) => environment.getEnvironmentName() === environmentName)?.peekPackage(packageName);
|
|
452062
452685
|
const loadedRoutes = {
|
|
@@ -452118,7 +452741,7 @@ var init_spa = __esm(() => {
|
|
|
452118
452741
|
});
|
|
452119
452742
|
|
|
452120
452743
|
// src/routes/main_app.ts
|
|
452121
|
-
import * as
|
|
452744
|
+
import * as path60 from "path";
|
|
452122
452745
|
function createMainApp(options) {
|
|
452123
452746
|
const { controllers } = options;
|
|
452124
452747
|
const { environmentStore } = controllers;
|
|
@@ -452132,7 +452755,7 @@ function createMainApp(options) {
|
|
|
452132
452755
|
registerDataAppStaticRoutes(app, environmentStore, options.dataAppRuntimePath);
|
|
452133
452756
|
if (options.consoleRoot) {
|
|
452134
452757
|
app.use("/", import_express2.default.static(options.consoleRoot));
|
|
452135
|
-
app.use("/api-doc.html", import_express2.default.static(
|
|
452758
|
+
app.use("/api-doc.html", import_express2.default.static(path60.join(options.consoleRoot, "api-doc.html")));
|
|
452136
452759
|
}
|
|
452137
452760
|
if (options.proxyConsoleToDevServer) {
|
|
452138
452761
|
app.use(import_http_proxy_middleware.createProxyMiddleware({
|
|
@@ -452386,7 +453009,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452386
453009
|
init.body = Readable3.toWeb(incoming);
|
|
452387
453010
|
}
|
|
452388
453011
|
return new Request$1(url, init);
|
|
452389
|
-
}, getRequestCache, requestCache, incomingKey,
|
|
453012
|
+
}, getRequestCache, requestCache, incomingKey, urlKey2, methodKey, headersKey, abortControllerKey, getAbortController, abortRequest, bodyBufferKey, bodyReadPromiseKey, bodyConsumedDirectlyKey, bodyLockReaderKey, abortReasonKey, newBodyUnusableError = () => {
|
|
452390
453013
|
return /* @__PURE__ */ new TypeError("Body is unusable");
|
|
452391
453014
|
}, rejectBodyUnusable = () => {
|
|
452392
453015
|
return Promise.reject(newBodyUnusableError());
|
|
@@ -452571,7 +453194,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452571
453194
|
if (incoming instanceof Http2ServerRequest)
|
|
452572
453195
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
452573
453196
|
try {
|
|
452574
|
-
req[
|
|
453197
|
+
req[urlKey2] = new URL(incomingUrl).href;
|
|
452575
453198
|
} catch (e) {
|
|
452576
453199
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
452577
453200
|
}
|
|
@@ -452588,7 +453211,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452588
453211
|
} else
|
|
452589
453212
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
452590
453213
|
try {
|
|
452591
|
-
req[
|
|
453214
|
+
req[urlKey2] = buildUrl(scheme, host, incomingUrl);
|
|
452592
453215
|
} catch (e) {
|
|
452593
453216
|
if (e instanceof RequestError)
|
|
452594
453217
|
throw e;
|
|
@@ -453091,7 +453714,7 @@ var init_dist6 = __esm(() => {
|
|
|
453091
453714
|
getRequestCache = Symbol("getRequestCache");
|
|
453092
453715
|
requestCache = Symbol("requestCache");
|
|
453093
453716
|
incomingKey = Symbol("incomingKey");
|
|
453094
|
-
|
|
453717
|
+
urlKey2 = Symbol("urlKey");
|
|
453095
453718
|
methodKey = Symbol("methodKey");
|
|
453096
453719
|
headersKey = Symbol("headersKey");
|
|
453097
453720
|
abortControllerKey = Symbol("abortControllerKey");
|
|
@@ -453109,7 +453732,7 @@ var init_dist6 = __esm(() => {
|
|
|
453109
453732
|
return this[methodKey];
|
|
453110
453733
|
},
|
|
453111
453734
|
get url() {
|
|
453112
|
-
return this[
|
|
453735
|
+
return this[urlKey2];
|
|
453113
453736
|
},
|
|
453114
453737
|
get headers() {
|
|
453115
453738
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
@@ -453145,14 +453768,14 @@ var init_dist6 = __esm(() => {
|
|
|
453145
453768
|
} });
|
|
453146
453769
|
init.duplex = "half";
|
|
453147
453770
|
}
|
|
453148
|
-
const req = new Request$1(this[
|
|
453771
|
+
const req = new Request$1(this[urlKey2], init);
|
|
453149
453772
|
if (method === "TRACE")
|
|
453150
453773
|
Object.defineProperty(req, "method", { get() {
|
|
453151
453774
|
return "TRACE";
|
|
453152
453775
|
} });
|
|
453153
453776
|
return this[requestCache] = req;
|
|
453154
453777
|
}
|
|
453155
|
-
return this[requestCache] = newRequestFromIncoming(this.method, this[
|
|
453778
|
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey2], this.headers, this[incomingKey], abortController);
|
|
453156
453779
|
},
|
|
453157
453780
|
get body() {
|
|
453158
453781
|
if (!this[bodyConsumedDirectlyKey])
|
|
@@ -481988,8 +482611,8 @@ var init_experimental_dialects = __esm(() => {
|
|
|
481988
482611
|
|
|
481989
482612
|
// src/main_server.ts
|
|
481990
482613
|
import * as http5 from "http";
|
|
481991
|
-
import * as
|
|
481992
|
-
import { fileURLToPath as
|
|
482614
|
+
import * as path61 from "path";
|
|
482615
|
+
import { fileURLToPath as fileURLToPath24 } from "url";
|
|
481993
482616
|
function startMaterializationSchedulerFromEnv(store, service) {
|
|
481994
482617
|
const config = getMaterializationSchedulerConfig();
|
|
481995
482618
|
if (!config)
|
|
@@ -482024,9 +482647,9 @@ async function buildApp(settings) {
|
|
|
482024
482647
|
const MCP_CONFIG_ENABLED = mcpConfigEnabled();
|
|
482025
482648
|
const SHUTDOWN_DRAIN_DURATION_SECONDS = settings.get("shutdown.drainDurationSeconds");
|
|
482026
482649
|
const SHUTDOWN_GRACEFUL_CLOSE_TIMEOUT_SECONDS = settings.get("shutdown.gracefulCloseTimeoutSeconds");
|
|
482027
|
-
const __filename_esm =
|
|
482028
|
-
const ROOT =
|
|
482029
|
-
const SERVER_ROOT =
|
|
482650
|
+
const __filename_esm = fileURLToPath24(import.meta.url);
|
|
482651
|
+
const ROOT = path61.join(path61.dirname(__filename_esm), "app");
|
|
482652
|
+
const SERVER_ROOT = path61.resolve(process.cwd(), settings.get("root"));
|
|
482030
482653
|
const isDevelopment = externalEnv("NODE_ENV") === "development";
|
|
482031
482654
|
checkHeapConfiguration();
|
|
482032
482655
|
const environmentStore = new EnvironmentStore(SERVER_ROOT);
|
|
@@ -482131,7 +482754,7 @@ async function buildApp(settings) {
|
|
|
482131
482754
|
const mcpApp = createMcpApp(appServices);
|
|
482132
482755
|
const app = createMainApp({
|
|
482133
482756
|
controllers: appServices,
|
|
482134
|
-
dataAppRuntimePath:
|
|
482757
|
+
dataAppRuntimePath: path61.join(path61.dirname(__filename_esm), "runtime", "publisher.js"),
|
|
482135
482758
|
consoleRoot: isDevelopment ? undefined : ROOT,
|
|
482136
482759
|
proxyConsoleToDevServer: isDevelopment,
|
|
482137
482760
|
frameAncestors: settings.get("frameAncestors"),
|