@malloy-publisher/server 0.18.2 → 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 +46 -11
- 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 +441 -281
- package/dist/server.mjs +998 -340
- 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();
|
|
@@ -135178,13 +135271,26 @@ function duckdbTableCollations(definition) {
|
|
|
135178
135271
|
function unquoted(name) {
|
|
135179
135272
|
return /^".*"$/.test(name) ? name.slice(1, -1).replace(/""/g, '"') : name;
|
|
135180
135273
|
}
|
|
135274
|
+
function bigqueryNamesNoCollation(name) {
|
|
135275
|
+
return typeof name !== "string" || BQ_NO_COLLATION.includes(name.trim().toUpperCase());
|
|
135276
|
+
}
|
|
135277
|
+
function bigqueryCollatedSql(column) {
|
|
135278
|
+
return `UPPER(TRIM(COALESCE(${column}, ''))) NOT IN (${BQ_NO_COLLATION.map((v) => `'${v}'`).join(", ")})`;
|
|
135279
|
+
}
|
|
135181
135280
|
function bigqueryColumnCollation(name) {
|
|
135182
|
-
return
|
|
135281
|
+
return bigqueryNamesNoCollation(name) ? BINARY_COLLATION : `bigquery:${name.trim()}`;
|
|
135282
|
+
}
|
|
135283
|
+
function canonicalCollation(identity) {
|
|
135284
|
+
const prefix = "bigquery:";
|
|
135285
|
+
return identity.startsWith(prefix) && bigqueryNamesNoCollation(identity.slice(prefix.length)) ? BINARY_COLLATION : identity;
|
|
135183
135286
|
}
|
|
135184
135287
|
function postgresColumnCollation(identity, judged) {
|
|
135185
135288
|
return judged === "binary" ? BINARY_COLLATION : `postgres:${identity}`;
|
|
135186
135289
|
}
|
|
135187
|
-
var BINARY_COLLATION = "binary", PG_COLLATION_COLUMNS = "c.collname AS name, c.collisdeterministic AS det, c.collcollate AS cc, c.collprovider AS prov, d.datcollate AS dbc, to_jsonb(d) ->> 'datlocprovider' AS dbp", PG_COLLATION_IDENTITY = `CASE WHEN c.collname = 'default' AND c.collnamespace = 'pg_catalog'::regnamespace THEN concat_ws('|', 'db', coalesce(to_jsonb(d) ->> 'datlocprovider', ''), d.datcollate, d.datctype, coalesce(to_jsonb(d) ->> 'daticulocale', ''), coalesce(to_jsonb(d) ->> 'datlocale', ''), coalesce(to_jsonb(d) ->> 'daticurules', ''), coalesce(to_jsonb(d) ->> 'datcollversion', '')) ELSE concat_ws('|', 'coll', c.collprovider, c.collisdeterministic::text, coalesce(c.collcollate, ''), coalesce(c.collctype, ''), coalesce(to_jsonb(c) ->> 'colliculocale', ''), coalesce(to_jsonb(c) ->> 'colllocale', ''), coalesce(to_jsonb(c) ->> 'collicurules', ''), coalesce(to_jsonb(c) ->> 'collversion', '')) END`, DUCKDB_COLLATE_DEFINITIONS = "SELECT (SELECT count(*) FROM duckdb_tables() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_views() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_functions() WHERE NOT internal AND function_type IN ('macro', 'table_macro') AND (macro_definition IS NULL OR macro_definition ILIKE '%collate%')) AS n";
|
|
135290
|
+
var BINARY_COLLATION = "binary", PG_COLLATION_COLUMNS = "c.collname AS name, c.collisdeterministic AS det, c.collcollate AS cc, c.collprovider AS prov, d.datcollate AS dbc, to_jsonb(d) ->> 'datlocprovider' AS dbp", PG_COLLATION_IDENTITY = `CASE WHEN c.collname = 'default' AND c.collnamespace = 'pg_catalog'::regnamespace THEN concat_ws('|', 'db', coalesce(to_jsonb(d) ->> 'datlocprovider', ''), d.datcollate, d.datctype, coalesce(to_jsonb(d) ->> 'daticulocale', ''), coalesce(to_jsonb(d) ->> 'datlocale', ''), coalesce(to_jsonb(d) ->> 'daticurules', ''), coalesce(to_jsonb(d) ->> 'datcollversion', '')) ELSE concat_ws('|', 'coll', c.collprovider, c.collisdeterministic::text, coalesce(c.collcollate, ''), coalesce(c.collctype, ''), coalesce(to_jsonb(c) ->> 'colliculocale', ''), coalesce(to_jsonb(c) ->> 'colllocale', ''), coalesce(to_jsonb(c) ->> 'collicurules', ''), coalesce(to_jsonb(c) ->> 'collversion', '')) END`, BQ_NO_COLLATION, DUCKDB_COLLATE_DEFINITIONS = "SELECT (SELECT count(*) FROM duckdb_tables() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_views() WHERE NOT internal AND sql ILIKE '%collate%') + (SELECT count(*) FROM duckdb_functions() WHERE NOT internal AND function_type IN ('macro', 'table_macro') AND (macro_definition IS NULL OR macro_definition ILIKE '%collate%')) AS n";
|
|
135291
|
+
var init_collation = __esm(() => {
|
|
135292
|
+
BQ_NO_COLLATION = ["", "NULL"];
|
|
135293
|
+
});
|
|
135188
135294
|
|
|
135189
135295
|
// src/service/materialization/domain/vocabulary.ts
|
|
135190
135296
|
var init_vocabulary = () => {};
|
|
@@ -135360,7 +135466,7 @@ function parseContract(raw) {
|
|
|
135360
135466
|
columns.push({
|
|
135361
135467
|
name: c.name,
|
|
135362
135468
|
nativeType: c.nativeType,
|
|
135363
|
-
collation: typeof c.collation === "string" ? c.collation : null,
|
|
135469
|
+
collation: typeof c.collation === "string" ? canonicalCollation(c.collation) : null,
|
|
135364
135470
|
compare: typeof c.compare === "string" && COMPARES.has(c.compare) ? c.compare : "none",
|
|
135365
135471
|
gateExact: c.gateExact === true,
|
|
135366
135472
|
...typeof c.declaredType === "string" && c.declaredType !== "" ? { declaredType: c.declaredType } : {}
|
|
@@ -135403,13 +135509,16 @@ function columnNamed(columns, name) {
|
|
|
135403
135509
|
const folded = columns.filter((c) => c.name.toLowerCase() === name.toLowerCase());
|
|
135404
135510
|
return folded.length === 1 ? folded[0] : undefined;
|
|
135405
135511
|
}
|
|
135406
|
-
function
|
|
135407
|
-
return nativeType.replace(
|
|
135512
|
+
function committedNativeType(nativeType, dialect) {
|
|
135513
|
+
return dialect === STORAGE_DIALECT ? nativeType.replace(DUCKDB_GEOMETRY_CRS, "GEOMETRY") : nativeType;
|
|
135514
|
+
}
|
|
135515
|
+
function spelledType(nativeType, dialect) {
|
|
135516
|
+
return committedNativeType(nativeType, dialect).replace(/\s+/g, " ").replace(/\s*([(),])\s*/g, "$1").trim().toUpperCase();
|
|
135408
135517
|
}
|
|
135409
135518
|
function contractDigest(contract) {
|
|
135410
135519
|
const canonical = contract.columns.map((c) => [
|
|
135411
135520
|
c.name,
|
|
135412
|
-
spelledType(c.nativeType),
|
|
135521
|
+
spelledType(c.nativeType, contract.dialect),
|
|
135413
135522
|
c.collation
|
|
135414
135523
|
]);
|
|
135415
135524
|
return createHash5("sha256").update(JSON.stringify(canonical)).digest("hex").slice(0, 32);
|
|
@@ -135449,7 +135558,7 @@ function deriveContract(args) {
|
|
|
135449
135558
|
const collation = c.isString && stored.collations ? collationOf(stored.collations, c.name) : null;
|
|
135450
135559
|
return {
|
|
135451
135560
|
name: c.name,
|
|
135452
|
-
nativeType: c.nativeType,
|
|
135561
|
+
nativeType: committedNativeType(c.nativeType, stored.dialect),
|
|
135453
135562
|
collation,
|
|
135454
135563
|
compare: columnCompare(args, c.isString, collation, c.name),
|
|
135455
135564
|
gateExact: tier === "database" ? c.storedAsDouble !== true : gateColumnTypeExact(c.nativeType, upstreamTypeNamed(args.upstreamTypes, c.name)),
|
|
@@ -135509,7 +135618,7 @@ function compatible(contract, observed) {
|
|
|
135509
135618
|
continue;
|
|
135510
135619
|
}
|
|
135511
135620
|
const type = now.nativeType ?? now.type;
|
|
135512
|
-
if (type === undefined || spelledType(type) !== spelledType(c.nativeType)) {
|
|
135621
|
+
if (type === undefined || spelledType(type, contract.dialect) !== spelledType(c.nativeType, contract.dialect)) {
|
|
135513
135622
|
retyped.push(c.name);
|
|
135514
135623
|
continue;
|
|
135515
135624
|
}
|
|
@@ -135542,10 +135651,13 @@ function declaredMoves(contract, declared) {
|
|
|
135542
135651
|
return now !== undefined && now !== "" && now !== c.declaredType ? [c.name] : [];
|
|
135543
135652
|
});
|
|
135544
135653
|
}
|
|
135545
|
-
var CONTRACT_VERSION = 1, COMPARES, COMPARE_RANK;
|
|
135654
|
+
var CONTRACT_VERSION = 1, COMPARES, DUCKDB_GEOMETRY_CRS, COMPARE_RANK;
|
|
135546
135655
|
var init_column_contract = __esm(() => {
|
|
135656
|
+
init_collation();
|
|
135657
|
+
init_dialect();
|
|
135547
135658
|
init_gate_policy();
|
|
135548
135659
|
COMPARES = new Set(["exact", "equality", "none"]);
|
|
135660
|
+
DUCKDB_GEOMETRY_CRS = /\bGEOMETRY\s*\(\s*'(?:[^']|'')*'\s*\)/gi;
|
|
135549
135661
|
COMPARE_RANK = {
|
|
135550
135662
|
none: 0,
|
|
135551
135663
|
equality: 1,
|
|
@@ -138623,9 +138735,11 @@ class BigQueryCatalog {
|
|
|
138623
138735
|
return bigqueryProbeOnce(this.reads, [this.connectionName, "dataset", dataset], () => bigqueryDatasetTables(this.io, dataset));
|
|
138624
138736
|
}
|
|
138625
138737
|
}
|
|
138626
|
-
var BQ_COLLATED
|
|
138738
|
+
var BQ_COLLATED, MAX_PROJECT_DATASETS = 1e4, TABLE_TYPES, PROJECT_ID, BIGQUERY_COLLATION;
|
|
138627
138739
|
var init_bigquery2 = __esm(() => {
|
|
138628
138740
|
init_quoting();
|
|
138741
|
+
init_collation();
|
|
138742
|
+
BQ_COLLATED = bigqueryCollatedSql("collation_name");
|
|
138629
138743
|
TABLE_TYPES = new Set(["BASE TABLE", "CLONE", "SNAPSHOT"]);
|
|
138630
138744
|
PROJECT_ID = /^(?:[a-z0-9.-]+:)?[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
138631
138745
|
BIGQUERY_COLLATION = Object.freeze({ scope: "dataset" });
|
|
@@ -138663,6 +138777,7 @@ async function duckdbTableListed(io, tablePath) {
|
|
|
138663
138777
|
}
|
|
138664
138778
|
var DUCKDB_COLLATION;
|
|
138665
138779
|
var init_duckdb2 = __esm(() => {
|
|
138780
|
+
init_collation();
|
|
138666
138781
|
DUCKDB_COLLATION = Object.freeze({
|
|
138667
138782
|
scope: "instance",
|
|
138668
138783
|
sourceColumns: duckdbCollation,
|
|
@@ -138716,6 +138831,7 @@ async function postgresTableListed(io, tablePath) {
|
|
|
138716
138831
|
}
|
|
138717
138832
|
var POSTGRES_COLLATION;
|
|
138718
138833
|
var init_postgres2 = __esm(() => {
|
|
138834
|
+
init_collation();
|
|
138719
138835
|
POSTGRES_COLLATION = Object.freeze({
|
|
138720
138836
|
scope: "column",
|
|
138721
138837
|
sourceColumns: (io, sql) => postgresCollation(io, unfinalizedPostgresSQL(sql)),
|
|
@@ -138734,7 +138850,7 @@ function collationReaderOf(dialect) {
|
|
|
138734
138850
|
return name !== undefined && Object.hasOwn(COLLATION_READERS, name) ? COLLATION_READERS[name] : undefined;
|
|
138735
138851
|
}
|
|
138736
138852
|
var COLLATION_READERS;
|
|
138737
|
-
var
|
|
138853
|
+
var init_collation2 = __esm(() => {
|
|
138738
138854
|
init_dialect();
|
|
138739
138855
|
init_bigquery2();
|
|
138740
138856
|
init_duckdb2();
|
|
@@ -139112,6 +139228,8 @@ var init_source_capability = __esm(() => {
|
|
|
139112
139228
|
init_malloy_text();
|
|
139113
139229
|
init_source_reads();
|
|
139114
139230
|
init_collation();
|
|
139231
|
+
init_collation();
|
|
139232
|
+
init_collation2();
|
|
139115
139233
|
init_bigquery2();
|
|
139116
139234
|
init_postgres2();
|
|
139117
139235
|
init_catalog_io();
|
|
@@ -140841,11 +140959,22 @@ function errorCodeOf(err) {
|
|
|
140841
140959
|
}
|
|
140842
140960
|
return "Error";
|
|
140843
140961
|
}
|
|
140844
|
-
|
|
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;
|
|
140845
140972
|
var init_error_code = __esm(() => {
|
|
140846
140973
|
init_driver_errors();
|
|
140847
140974
|
init_errors2();
|
|
140848
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}$/;
|
|
140849
140978
|
});
|
|
140850
140979
|
|
|
140851
140980
|
// src/service/materialization/plan/refusal_key.ts
|
|
@@ -141263,6 +141392,21 @@ function kindOf2(def, base) {
|
|
|
141263
141392
|
return "rename";
|
|
141264
141393
|
return "query";
|
|
141265
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
|
+
}
|
|
141266
141410
|
function sourceChain(struct, modelDef) {
|
|
141267
141411
|
return SourceMap.of(modelDef).chainOf(struct);
|
|
141268
141412
|
}
|
|
@@ -157283,6 +157427,7 @@ var RelationProbeUnsupportedError, CURRENT_SCHEMA_SQL, DUCKDB_CATALOGS_SQL = "SE
|
|
|
157283
157427
|
var init_warehouse_sql = __esm(() => {
|
|
157284
157428
|
init_introspection_sql();
|
|
157285
157429
|
init_quoting();
|
|
157430
|
+
init_collation();
|
|
157286
157431
|
init_dialect();
|
|
157287
157432
|
RelationProbeUnsupportedError = class RelationProbeUnsupportedError extends Error {
|
|
157288
157433
|
};
|
|
@@ -157565,7 +157710,7 @@ function movedColumns(built, read) {
|
|
|
157565
157710
|
if (!now)
|
|
157566
157711
|
return { kind: "moved", reason: `its column '${name}' is gone` };
|
|
157567
157712
|
const nowType = now.nativeType ?? now.type ?? "";
|
|
157568
|
-
if (now.storedAsDouble ||
|
|
157713
|
+
if (now.storedAsDouble || spelledType(nowType, read.dialect) !== spelledType(type, read.dialect)) {
|
|
157569
157714
|
return {
|
|
157570
157715
|
kind: "moved",
|
|
157571
157716
|
reason: `its column '${name}' was built as ${type} and is now ` + `${nowType || "of no readable type"}`
|
|
@@ -157593,9 +157738,6 @@ function storedUpstreamMove(entry, read) {
|
|
|
157593
157738
|
const reason = verdict.code === "column_gone" ? `its column '${name}' is gone` : verdict.code === "column_retyped" ? `its column '${name}' was built as ${built?.nativeType ?? "?"} ` + `and is now ${now?.nativeType ?? now?.type ?? "of no readable type"}` : `its column '${name}' no longer matches the contract its build ` + `recorded (${verdict.code})`;
|
|
157594
157739
|
return { kind: "moved", reason };
|
|
157595
157740
|
}
|
|
157596
|
-
function spelled(nativeType) {
|
|
157597
|
-
return nativeType.replace(/\s+/g, " ").replace(/\s*([(),])\s*/g, "$1").trim().toUpperCase();
|
|
157598
|
-
}
|
|
157599
157741
|
function columnNamed2(columns, name) {
|
|
157600
157742
|
const exact = columns.find((c) => c.name === name);
|
|
157601
157743
|
if (exact)
|
|
@@ -158127,7 +158269,7 @@ var init_generated_files = __esm(() => {
|
|
|
158127
158269
|
});
|
|
158128
158270
|
|
|
158129
158271
|
// package.json
|
|
158130
|
-
var version = "0.18.
|
|
158272
|
+
var version = "0.18.4";
|
|
158131
158273
|
var init_package = () => {};
|
|
158132
158274
|
|
|
158133
158275
|
// src/version.ts
|
|
@@ -162662,13 +162804,14 @@ async function collectGeneratedTables(parts, args) {
|
|
|
162662
162804
|
parts.modelGateLines.nameProblems.push(...persistNameProblems(text, modelPath));
|
|
162663
162805
|
}
|
|
162664
162806
|
}
|
|
162807
|
+
const materializeOn = getMaterializeEnabled();
|
|
162665
162808
|
collectPersistQueryFindings(parts, {
|
|
162666
162809
|
modelPath,
|
|
162667
162810
|
packagePath,
|
|
162668
162811
|
malloyModel,
|
|
162669
|
-
notBuilt: !
|
|
162812
|
+
notBuilt: !materializeOn
|
|
162670
162813
|
});
|
|
162671
|
-
if (!
|
|
162814
|
+
if (!materializeOn) {
|
|
162672
162815
|
collectPersistViewFindingsSwitchedOff(parts, {
|
|
162673
162816
|
modelPath,
|
|
162674
162817
|
packagePath,
|
|
@@ -162676,7 +162819,7 @@ async function collectGeneratedTables(parts, args) {
|
|
|
162676
162819
|
});
|
|
162677
162820
|
}
|
|
162678
162821
|
let materialized;
|
|
162679
|
-
if (
|
|
162822
|
+
if (materializeOn) {
|
|
162680
162823
|
materialized = await collectGeneratedMaterialize(parts, {
|
|
162681
162824
|
modelPath,
|
|
162682
162825
|
packagePath,
|
|
@@ -162793,7 +162936,7 @@ function reportPersistLineFindings(parts, targets, planned, args) {
|
|
|
162793
162936
|
route: "@",
|
|
162794
162937
|
tier: "malformed",
|
|
162795
162938
|
code: "persist-not-materializable",
|
|
162796
|
-
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`,
|
|
162797
162940
|
subject: name,
|
|
162798
162941
|
model: modelPath
|
|
162799
162942
|
});
|
|
@@ -168770,6 +168913,9 @@ var init_served_copy_containment = __esm(() => {
|
|
|
168770
168913
|
});
|
|
168771
168914
|
|
|
168772
168915
|
// src/service/materialization/text/kept_ancestors.ts
|
|
168916
|
+
function nodeIn(map, sourceID, elsewhere) {
|
|
168917
|
+
return map.node(sourceID) ?? detachedNode(elsewhere?.(sourceID));
|
|
168918
|
+
}
|
|
168773
168919
|
function plainRenamesOf(map, sourceID, url) {
|
|
168774
168920
|
const out = [];
|
|
168775
168921
|
const reached = new Set([sourceID]);
|
|
@@ -168819,15 +168965,15 @@ function locatedIn(def, url) {
|
|
|
168819
168965
|
const location = def?.location;
|
|
168820
168966
|
return location?.url === url && typeof location.range?.start?.line === "number" && typeof location.range?.end?.line === "number" ? location.range : undefined;
|
|
168821
168967
|
}
|
|
168822
|
-
function keptAncestorChain(map, sourceID, url) {
|
|
168968
|
+
function keptAncestorChain(map, sourceID, url, elsewhere) {
|
|
168823
168969
|
const out = [];
|
|
168824
|
-
let node = map
|
|
168970
|
+
let node = nodeIn(map, sourceID, elsewhere);
|
|
168825
168971
|
let childURL = url;
|
|
168826
168972
|
for (let hops = 0;node && hops < MAX_HOPS; hops++) {
|
|
168827
168973
|
const base = node.base;
|
|
168828
168974
|
if (!base || base.hop === "query" || base.sourceID === undefined)
|
|
168829
168975
|
break;
|
|
168830
|
-
const parent = map
|
|
168976
|
+
const parent = nodeIn(map, base.sourceID, elsewhere);
|
|
168831
168977
|
const parentURL = declaringURLOf(parent?.def);
|
|
168832
168978
|
const range = parentURL ? locatedIn(parent?.def, parentURL) : undefined;
|
|
168833
168979
|
if (!parent || !parentURL || !range)
|
|
@@ -168844,17 +168990,29 @@ function keptAncestorChain(map, sourceID, url) {
|
|
|
168844
168990
|
}
|
|
168845
168991
|
return out;
|
|
168846
168992
|
}
|
|
168847
|
-
function keptAncestorChainOrDeclared(map, sourceID, url, fileText) {
|
|
168848
|
-
const
|
|
168849
|
-
const
|
|
168850
|
-
|
|
168851
|
-
|
|
168852
|
-
|
|
168853
|
-
|
|
168854
|
-
|
|
168855
|
-
|
|
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;
|
|
168856
169014
|
}
|
|
168857
|
-
function declaredTableBase(def, url,
|
|
169015
|
+
function declaredTableBase(def, url, fileText, nodeOf) {
|
|
168858
169016
|
const own = def;
|
|
168859
169017
|
if (own?.type !== "table")
|
|
168860
169018
|
return;
|
|
@@ -168865,8 +169023,8 @@ function declaredTableBase(def, url, map, fileText) {
|
|
|
168865
169023
|
const name = declaredBaseName(text, range);
|
|
168866
169024
|
if (name === undefined)
|
|
168867
169025
|
return;
|
|
168868
|
-
const parentID =
|
|
168869
|
-
const parent = parentID ?
|
|
169026
|
+
const parentID = declaredBaseID(name, url, text, nodeOf);
|
|
169027
|
+
const parent = parentID ? nodeOf(parentID) : undefined;
|
|
168870
169028
|
const base = parent?.def;
|
|
168871
169029
|
if (!parent || base?.type !== "table" || base.connection !== own.connection || base.tablePath !== own.tablePath) {
|
|
168872
169030
|
return;
|
|
@@ -168882,6 +169040,16 @@ function declaredTableBase(def, url, map, fileText) {
|
|
|
168882
169040
|
}
|
|
168883
169041
|
return { sourceID: parent.sourceID, url: parentURL, range: parentRange };
|
|
168884
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
|
+
}
|
|
168885
169053
|
function fieldList(def) {
|
|
168886
169054
|
return Array.isArray(def.fields) ? def.fields : [];
|
|
168887
169055
|
}
|
|
@@ -169077,6 +169245,7 @@ var MAX_HOPS = 64;
|
|
|
169077
169245
|
var init_kept_ancestors = __esm(() => {
|
|
169078
169246
|
init_declaration_text();
|
|
169079
169247
|
init_malloy_lexer_core();
|
|
169248
|
+
init_source_map();
|
|
169080
169249
|
init_table_plans();
|
|
169081
169250
|
});
|
|
169082
169251
|
|
|
@@ -170710,6 +170879,21 @@ class ServedCopyServe {
|
|
|
170710
170879
|
async loadQuery(queryString, givens, pinned = this.current()) {
|
|
170711
170880
|
return this.answer(await this.ensureCompiled(pinned), queryString, givens, pinned);
|
|
170712
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
|
+
}
|
|
170713
170897
|
async beginAttempt(compiled, queryString, givens) {
|
|
170714
170898
|
if (!compiled.materializer || compiled.rerooted.length === 0) {
|
|
170715
170899
|
const crossConnection = compiled.problems.some((p) => p.reason === "cross_connection_unbuilt");
|
|
@@ -170746,24 +170930,9 @@ class ServedCopyServe {
|
|
|
170746
170930
|
if (zoned.size > 0 && readsMissingName(zoned, error, queryString)) {
|
|
170747
170931
|
decline(ZONED_TRUNCATION_REASON, "served_copy_time_zone");
|
|
170748
170932
|
}
|
|
170749
|
-
const
|
|
170750
|
-
|
|
170751
|
-
|
|
170752
|
-
if (storedLeftOut.size > 0 && readsMissingName(storedLeftOut, error, queryString)) {
|
|
170753
|
-
const missing = new Set([
|
|
170754
|
-
...String(error instanceof Error ? error.message : error).matchAll(/'([^']+)' is not defined/g)
|
|
170755
|
-
].map((m) => m[1]));
|
|
170756
|
-
const read = [...storedLeftOut].filter((n) => missing.has(n));
|
|
170757
|
-
const named = read.length > 0 ? read : [...storedLeftOut];
|
|
170758
|
-
const sourceIDs = new Set([...compiled.leftOutColumns ?? []].filter(([, names]) => names.some((n) => named.includes(n))).map(([sourceID]) => sourceID));
|
|
170759
|
-
const tableIds = compiled.aliased.filter((b) => b.sourceIDs?.some((id) => sourceIDs.has(id))).map((b) => b.virtualHandle);
|
|
170760
|
-
const why = [
|
|
170761
|
-
...new Set(named.flatMap((c) => {
|
|
170762
|
-
const reasons = [...sourceIDs].map((id) => compiled.leftOutWhy?.get(id)?.get(c)).filter((w) => w !== undefined);
|
|
170763
|
-
return reasons.length > 0 ? reasons : [noCastPhrase("a stored column")];
|
|
170764
|
-
}))
|
|
170765
|
-
];
|
|
170766
|
-
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);
|
|
170767
170936
|
}
|
|
170768
170937
|
throw error;
|
|
170769
170938
|
}
|
|
@@ -171191,8 +171360,8 @@ class ServedCopyServe {
|
|
|
171191
171360
|
const plan = this.materializePlans[reroot.sourceID];
|
|
171192
171361
|
if (!plan)
|
|
171193
171362
|
return;
|
|
171194
|
-
const confirmed = confirmedAncestors(fileText, reroot.url, reroot.range, keptAncestorChainOrDeclared(map, reroot.sourceID, reroot.url, fileText));
|
|
171195
|
-
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)));
|
|
171196
171365
|
if (!needed)
|
|
171197
171366
|
return;
|
|
171198
171367
|
return confirmed.flatMap((a) => a.runText ? [a.runText] : []).reverse().join(" ");
|
|
@@ -172045,6 +172214,66 @@ function leftOutPhrase(ref, field, storedType) {
|
|
|
172045
172214
|
function leftOutPhraseOf(subject, c) {
|
|
172046
172215
|
return leftOutPhrase(subject.columnRef(c.name), subject.fieldsByName.get(c.name), c.type);
|
|
172047
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
|
+
}
|
|
172048
172277
|
function noCastPhrase(ref) {
|
|
172049
172278
|
return `no cast reads ${ref} as declared`;
|
|
172050
172279
|
}
|
|
@@ -172907,7 +173136,7 @@ function zonedTruncations(columns, def, fieldsByName, chainZone, restatesStageZo
|
|
|
172907
173136
|
restated: []
|
|
172908
173137
|
};
|
|
172909
173138
|
}
|
|
172910
|
-
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;
|
|
172911
173140
|
var init_served_copy_serve = __esm(() => {
|
|
172912
173141
|
init_ducklake_catalog_unavailable();
|
|
172913
173142
|
init_served_copy_lanes();
|
|
@@ -180456,6 +180685,7 @@ class PlanLifecycle {
|
|
|
180456
180685
|
};
|
|
180457
180686
|
connectionsChangedSinceDerived = new Set;
|
|
180458
180687
|
refreshFailedTransiently = false;
|
|
180688
|
+
heldWithdrawn = new Set;
|
|
180459
180689
|
stale;
|
|
180460
180690
|
staleSeq = 0;
|
|
180461
180691
|
refreshChain = Promise.resolve(true);
|
|
@@ -180554,6 +180784,9 @@ class PlanLifecycle {
|
|
|
180554
180784
|
get withdrawn() {
|
|
180555
180785
|
return this.serving().withdrawn;
|
|
180556
180786
|
}
|
|
180787
|
+
holdWithdrawn(hold) {
|
|
180788
|
+
this.heldWithdrawn = hold ? new Set(this.withdrawn) : new Set;
|
|
180789
|
+
}
|
|
180557
180790
|
servingPlan() {
|
|
180558
180791
|
return this.state.serving?.plan ?? null;
|
|
180559
180792
|
}
|
|
@@ -180603,7 +180836,7 @@ class PlanLifecycle {
|
|
|
180603
180836
|
buildConnectionNames: new Set(outcome.buildConnectionNames),
|
|
180604
180837
|
asOfBuild: outcome.asOfBuild ?? {},
|
|
180605
180838
|
upstreamSchemas: outcome.upstreamSchemas ?? {},
|
|
180606
|
-
withdrawn: new Set,
|
|
180839
|
+
withdrawn: new Set(this.heldWithdrawn),
|
|
180607
180840
|
stringCapabilityReads: outcome.stringCapabilityReads ?? {}
|
|
180608
180841
|
};
|
|
180609
180842
|
}
|
|
@@ -181173,6 +181406,12 @@ function verdictExplains(reason, verdict) {
|
|
|
181173
181406
|
return true;
|
|
181174
181407
|
return reason === "ROW_LEVEL_GATE" && (verdict === "row_level_gate" || verdict === "refused");
|
|
181175
181408
|
}
|
|
181409
|
+
function contractVerdictOfTwin(candidate, tier, verdicts) {
|
|
181410
|
+
if (tier !== "database" || candidate.reason !== "NOT_BUILT")
|
|
181411
|
+
return;
|
|
181412
|
+
const twin = verdicts.get(liveVerdictKey("storage", candidate.tableId));
|
|
181413
|
+
return twin && CONTRACT_VERDICTS.has(twin.reason) ? twin : undefined;
|
|
181414
|
+
}
|
|
181176
181415
|
function applyServeVerdicts(considered, tierOf, input) {
|
|
181177
181416
|
const verdicts = input.catalog?.liveVerdicts ?? new Map;
|
|
181178
181417
|
const warnings = [];
|
|
@@ -181187,7 +181426,7 @@ function applyServeVerdicts(considered, tierOf, input) {
|
|
|
181187
181426
|
const tier = tierOf.get(candidate);
|
|
181188
181427
|
if (!tier)
|
|
181189
181428
|
continue;
|
|
181190
|
-
const verdict = verdicts.get(liveVerdictKey(tier, candidate.tableId));
|
|
181429
|
+
const verdict = verdicts.get(liveVerdictKey(tier, candidate.tableId)) ?? contractVerdictOfTwin(candidate, tier, verdicts);
|
|
181191
181430
|
if (!verdict || !verdictExplains(candidate.reason, verdict.reason)) {
|
|
181192
181431
|
if (own && ownVerdictExplains(candidate, own)) {
|
|
181193
181432
|
candidate.reason = "NOT_SERVED";
|
|
@@ -181264,6 +181503,10 @@ function verdictWarningMessage(reason) {
|
|
|
181264
181503
|
return "This table's storage destination is not configured on this server, so its queries are answered live.";
|
|
181265
181504
|
case "connection_cannot_hold_table":
|
|
181266
181505
|
return "This table's connection cannot hold a table, so its queries are answered live.";
|
|
181506
|
+
case "incompatible":
|
|
181507
|
+
return "This table no longer matches the column contract its build recorded, so its queries are answered live until a build rebuilds it.";
|
|
181508
|
+
case "contract_missing":
|
|
181509
|
+
return "This table carries no column contract, so its queries are answered live until a build rebuilds it in full.";
|
|
181267
181510
|
case "types_unrecorded":
|
|
181268
181511
|
return "This table's build recorded no column types, so a change since the build cannot be ruled out; its queries are answered live until it is rebuilt.";
|
|
181269
181512
|
default:
|
|
@@ -181527,10 +181770,11 @@ function fieldPathsIn2(e) {
|
|
|
181527
181770
|
}, { skipKeys: FIELD_PATH_SKIPPED_KEYS3 });
|
|
181528
181771
|
return out;
|
|
181529
181772
|
}
|
|
181530
|
-
var MAX_NOT_CONSIDERED = 10, FIELD_PATH_SKIPPED_KEYS3;
|
|
181773
|
+
var MAX_NOT_CONSIDERED = 10, CONTRACT_VERDICTS, FIELD_PATH_SKIPPED_KEYS3;
|
|
181531
181774
|
var init_query_path = __esm(() => {
|
|
181532
181775
|
init_array_query();
|
|
181533
181776
|
init_leg_decline();
|
|
181777
|
+
CONTRACT_VERDICTS = new Set(["incompatible", "contract_missing"]);
|
|
181534
181778
|
FIELD_PATH_SKIPPED_KEYS3 = new Set(["overload", "at"]);
|
|
181535
181779
|
});
|
|
181536
181780
|
|
|
@@ -186097,6 +186341,7 @@ var init_inline_uniqueness = __esm(() => {
|
|
|
186097
186341
|
|
|
186098
186342
|
// src/service/materialization/run/build_failure_class.ts
|
|
186099
186343
|
import { MalloyError as MalloyError6 } from "@malloydata/malloy";
|
|
186344
|
+
import * as path27 from "path";
|
|
186100
186345
|
function isDeterministicWarehouseError(err) {
|
|
186101
186346
|
for (const e of causeChain(err)) {
|
|
186102
186347
|
const fields = e;
|
|
@@ -186162,6 +186407,49 @@ function classifySourceFailure(err, failedUpstreams) {
|
|
|
186162
186407
|
const upstreamDetail = failedUpstreams.map((u) => `upstream '${u.name}' failed in this run: ${u.reason}`).join("; ");
|
|
186163
186408
|
return { retryable, upstreamDetail };
|
|
186164
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
|
+
}
|
|
186165
186453
|
function failedUpstreamsOf(sourceID, err, upstreamsBySourceID, failedBySourceID) {
|
|
186166
186454
|
const declared = upstreamsBySourceID.get(sourceID) ?? [];
|
|
186167
186455
|
const missedId = strictMissSourceId(err)?.sourceID;
|
|
@@ -186220,8 +186508,9 @@ function failedRunManifestOf(err) {
|
|
|
186220
186508
|
function classifyRunFailure(err) {
|
|
186221
186509
|
return err instanceof BuildRunFailedError ? err.retryable : classifyBuildError(err);
|
|
186222
186510
|
}
|
|
186223
|
-
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;
|
|
186224
186512
|
var init_build_failure_class = __esm(() => {
|
|
186513
|
+
init_read_text();
|
|
186225
186514
|
init_errors2();
|
|
186226
186515
|
init_driver_errors();
|
|
186227
186516
|
init_utils();
|
|
@@ -187774,7 +188063,7 @@ var init_database_build_strategy = __esm(() => {
|
|
|
187774
188063
|
|
|
187775
188064
|
// src/service/materialization/run/storage_admin.ts
|
|
187776
188065
|
import { existsSync as existsSync3, readdirSync as readdirSync3 } from "node:fs";
|
|
187777
|
-
import
|
|
188066
|
+
import path28 from "node:path";
|
|
187778
188067
|
function dropStorageTableSql(destinationName, physicalTableName, schema) {
|
|
187779
188068
|
return `DROP TABLE IF EXISTS ${quoteManifestTablePath(storageTablePath(destinationName, physicalTableName, schema), STORAGE_DIALECT)}`;
|
|
187780
188069
|
}
|
|
@@ -187817,7 +188106,7 @@ async function listStorageTables(params) {
|
|
|
187817
188106
|
} else {
|
|
187818
188107
|
const dbPath = storageDestinationFile(environmentPath, destinationName);
|
|
187819
188108
|
const destinationRoot = storageDestinationRoot(environmentPath);
|
|
187820
|
-
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(
|
|
188109
|
+
if (!existsSync3(destinationRoot) || !readdirSync3(destinationRoot).includes(path28.basename(dbPath))) {
|
|
187821
188110
|
return [];
|
|
187822
188111
|
}
|
|
187823
188112
|
await session.runSQL(`ATTACH '${escapeSQL(dbPath)}' AS ${quoteIdentifier(destinationName, STORAGE_DIALECT)} (READ_ONLY)`);
|
|
@@ -188682,10 +188971,14 @@ class RunTelemetry {
|
|
|
188682
188971
|
refused,
|
|
188683
188972
|
failed,
|
|
188684
188973
|
...cancelled > 0 ? { cancelled } : {},
|
|
188685
|
-
...err !== undefined ?
|
|
188974
|
+
...err !== undefined ? errorLogFields(err) : {}
|
|
188686
188975
|
});
|
|
188687
188976
|
}
|
|
188688
188977
|
}
|
|
188978
|
+
function errorLogFields(err) {
|
|
188979
|
+
const detail = runtimeErrorTextOf(err);
|
|
188980
|
+
return { code: errorCodeOf(err), ...detail ? { detail } : {} };
|
|
188981
|
+
}
|
|
188689
188982
|
function markRunFailureReported(err) {
|
|
188690
188983
|
if (typeof err === "object" && err !== null)
|
|
188691
188984
|
reportedRunFailures.add(err);
|
|
@@ -188771,7 +189064,7 @@ function reportSourceFailed(source, err, retryable, cancelled) {
|
|
|
188771
189064
|
...source.durationMs !== undefined ? { durationMs: source.durationMs } : {},
|
|
188772
189065
|
outcome: failureClass === "none" ? "cancelled" : "failed",
|
|
188773
189066
|
failureClass,
|
|
188774
|
-
|
|
189067
|
+
...errorLogFields(err),
|
|
188775
189068
|
...source.destination ? { destinationName: source.destination } : {}
|
|
188776
189069
|
});
|
|
188777
189070
|
}
|
|
@@ -188949,8 +189242,30 @@ function assertInstructedDestinationWritable(persistSource, instruction, compile
|
|
|
188949
189242
|
}
|
|
188950
189243
|
const declared = declaredStorage(persistSource);
|
|
188951
189244
|
if (declared && !instruction.destination) {
|
|
188952
|
-
|
|
188953
|
-
|
|
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}\``;
|
|
188954
189269
|
}
|
|
188955
189270
|
}
|
|
188956
189271
|
function recordInstructedBuildFailure(run, persistSource, instruction, sourceEntityId, buildErr, build) {
|
|
@@ -188960,8 +189275,12 @@ function recordInstructedBuildFailure(run, persistSource, instruction, sourceEnt
|
|
|
188960
189275
|
} catch {
|
|
188961
189276
|
reason = redactStorageUrls(redactPgSecrets(errMessage(buildErr)));
|
|
188962
189277
|
}
|
|
188963
|
-
const
|
|
188964
|
-
|
|
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)
|
|
188965
189284
|
reason = `${reason}; ${upstreamDetail}`;
|
|
188966
189285
|
run.failedBySourceID.set(persistSource.sourceID, {
|
|
188967
189286
|
name: persistSource.name,
|
|
@@ -189654,7 +189973,7 @@ var init_table_ownership = __esm(() => {
|
|
|
189654
189973
|
});
|
|
189655
189974
|
|
|
189656
189975
|
// src/service/materialization/run/run_instructions.ts
|
|
189657
|
-
import * as
|
|
189976
|
+
import * as path29 from "path";
|
|
189658
189977
|
import { fileURLToPath as fileURLToPath11 } from "url";
|
|
189659
189978
|
function gateSources(compiled, include, pulledIn = new Set) {
|
|
189660
189979
|
const sources = [];
|
|
@@ -189721,9 +190040,9 @@ function modelPathOf(compiled, persistSource, packagePath) {
|
|
|
189721
190040
|
if (packagePath && url.startsWith("file:")) {
|
|
189722
190041
|
try {
|
|
189723
190042
|
const file = authorModelPath(fileURLToPath11(url));
|
|
189724
|
-
const relative =
|
|
189725
|
-
if (relative && !relative.startsWith("..") && !
|
|
189726
|
-
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("/");
|
|
189727
190046
|
}
|
|
189728
190047
|
} catch {}
|
|
189729
190048
|
}
|
|
@@ -194021,7 +194340,7 @@ class MaterializationService {
|
|
|
194021
194340
|
const environment = await this.host.getEnvironment(parseEnvironmentName(environmentName), false);
|
|
194022
194341
|
const version = await this.resolveRunVersion(environmentName, packageName, options.versionId ?? VersionRef.LATEST);
|
|
194023
194342
|
const pkg = await environment.getPackage(parsePackageName(packageName), false, version !== null ? { versionId: VersionRef.parse(version) } : {});
|
|
194024
|
-
if (version === null && environment.
|
|
194343
|
+
if (version === null && environment.getRefusedReloads().has(packageName)) {
|
|
194025
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.`);
|
|
194026
194345
|
}
|
|
194027
194346
|
const scope = version !== null ? pkg.getPackageMetadata().scope ?? "package" : null;
|
|
@@ -194277,7 +194596,7 @@ class MaterializationService {
|
|
|
194277
194596
|
const owned = versionId !== undefined ? ownedVersionOf(pkg) : undefined;
|
|
194278
194597
|
const reader = versionId !== undefined ? { versionId, owned } : {};
|
|
194279
194598
|
const { runPlan: compiled, packagePlan } = versionId !== undefined ? await compileRunPlan(pkg, signal) : await environment.withPackageLock(packageName, () => compileRunPlan(pkg, signal));
|
|
194280
|
-
const stale = versionId === undefined && environment.
|
|
194599
|
+
const stale = versionId === undefined && environment.getRefusedReloads().has(packageName);
|
|
194281
194600
|
const invalid = runPlanGateText(packagePlan, {
|
|
194282
194601
|
enforceCollisions: getPersistCollisionEnforce(),
|
|
194283
194602
|
versionScoped: owned !== undefined
|
|
@@ -194420,7 +194739,7 @@ Fix the files and reload the package, then run again.`);
|
|
|
194420
194739
|
return await this.collaborators.executeInstructedBuild({
|
|
194421
194740
|
refusedAtPlan,
|
|
194422
194741
|
compiled,
|
|
194423
|
-
environment: withChainBuildText(environment, pkg, () => versionId === undefined && (environment.
|
|
194742
|
+
environment: withChainBuildText(environment, pkg, () => versionId === undefined && (environment.getRefusedReloads?.().has(packageName) ?? false)),
|
|
194424
194743
|
instructions,
|
|
194425
194744
|
seedEntries: carried,
|
|
194426
194745
|
signal,
|
|
@@ -195913,19 +196232,19 @@ var init_package_load_metrics = __esm(() => {
|
|
|
195913
196232
|
});
|
|
195914
196233
|
|
|
195915
196234
|
// src/controller/manifest_location.ts
|
|
195916
|
-
import * as
|
|
196235
|
+
import * as path30 from "path";
|
|
195917
196236
|
import { fileURLToPath as fileURLToPath12 } from "url";
|
|
195918
196237
|
function isManifestLocation(value) {
|
|
195919
196238
|
if (/^(gs|s3):\/\/[^/]+\/./.test(value))
|
|
195920
196239
|
return true;
|
|
195921
196240
|
if (value.startsWith("file://")) {
|
|
195922
196241
|
try {
|
|
195923
|
-
return
|
|
196242
|
+
return path30.isAbsolute(fileURLToPath12(value));
|
|
195924
196243
|
} catch {
|
|
195925
196244
|
return false;
|
|
195926
196245
|
}
|
|
195927
196246
|
}
|
|
195928
|
-
return !value.includes("://") &&
|
|
196247
|
+
return !value.includes("://") && path30.isAbsolute(value);
|
|
195929
196248
|
}
|
|
195930
196249
|
function versionManifestLocation(value) {
|
|
195931
196250
|
if (value === undefined)
|
|
@@ -197823,7 +198142,7 @@ var init_report_controller = __esm(() => {
|
|
|
197823
198142
|
|
|
197824
198143
|
// src/service/skills/build_skills_bundle.ts
|
|
197825
198144
|
import * as fs13 from "fs";
|
|
197826
|
-
import * as
|
|
198145
|
+
import * as path31 from "path";
|
|
197827
198146
|
function unquote3(s) {
|
|
197828
198147
|
return s.trim().replace(/^["']|["']$/g, "");
|
|
197829
198148
|
}
|
|
@@ -197841,7 +198160,7 @@ function parseSkill(md, dirName) {
|
|
|
197841
198160
|
return { name, description, body };
|
|
197842
198161
|
}
|
|
197843
198162
|
function referenceName(skillName, file) {
|
|
197844
|
-
return `${skillName}/${
|
|
198163
|
+
return `${skillName}/${path31.basename(file, ".md")}`;
|
|
197845
198164
|
}
|
|
197846
198165
|
function parseReference(md, skillName, file) {
|
|
197847
198166
|
const body = stripLicenseHeader(md.replace(/\r\n/g, `
|
|
@@ -197854,7 +198173,7 @@ function parseReference(md, skillName, file) {
|
|
|
197854
198173
|
};
|
|
197855
198174
|
}
|
|
197856
198175
|
function referencePointer(skillName, files, channel = "bundled") {
|
|
197857
|
-
const stems = files.map((f) =>
|
|
198176
|
+
const stems = files.map((f) => path31.basename(f, ".md"));
|
|
197858
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.`;
|
|
197859
198178
|
return [
|
|
197860
198179
|
`## Reference files over MCP`,
|
|
@@ -197866,7 +198185,7 @@ function referencePointer(skillName, files, channel = "bundled") {
|
|
|
197866
198185
|
`);
|
|
197867
198186
|
}
|
|
197868
198187
|
function referenceFiles(skillDir) {
|
|
197869
|
-
const dir =
|
|
198188
|
+
const dir = path31.join(skillDir, REFERENCE_DIR);
|
|
197870
198189
|
if (!fs13.existsSync(dir))
|
|
197871
198190
|
return [];
|
|
197872
198191
|
return fs13.readdirSync(dir).filter((f) => f.endsWith(".md")).sort();
|
|
@@ -202305,7 +202624,7 @@ End with a short **Next steps**: one or two specific deeper analyses the data co
|
|
|
202305
202624
|
{
|
|
202306
202625
|
name: "malloy-analysis-report",
|
|
202307
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.',
|
|
202308
|
-
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."
|
|
202309
202628
|
},
|
|
202310
202629
|
{
|
|
202311
202630
|
name: "malloy-charts",
|
|
@@ -206099,7 +206418,7 @@ If you did not start the server (someone handed you a running one), **probe befo
|
|
|
206099
206418
|
}
|
|
206100
206419
|
\`\`\`
|
|
206101
206420
|
|
|
206102
|
-
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.)
|
|
206103
206422
|
|
|
206104
206423
|
### Publishing
|
|
206105
206424
|
|
|
@@ -208242,7 +208561,7 @@ Present coverage in this order:
|
|
|
208242
208561
|
{
|
|
208243
208562
|
name: "malloy-materialization",
|
|
208244
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.",
|
|
208245
|
-
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."
|
|
208246
208565
|
},
|
|
208247
208566
|
{
|
|
208248
208567
|
name: "malloy-materialization/access-filter",
|
|
@@ -209031,7 +209350,7 @@ When you've been doing analysis, writing queries, building views, creating repor
|
|
|
209031
209350
|
|
|
209032
209351
|
## Step 1: IDENTIFY, what belongs in a model?
|
|
209033
209352
|
|
|
209034
|
-
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?**
|
|
209035
209354
|
|
|
209036
209355
|
A measure or dimension belongs in a model if it meets ANY of these criteria:
|
|
209037
209356
|
|
|
@@ -209245,7 +209564,7 @@ source: first_touch is conn.table('events') -> {
|
|
|
209245
209564
|
{
|
|
209246
209565
|
name: "malloy-modeling",
|
|
209247
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.",
|
|
209248
|
-
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"
|
|
209249
209568
|
},
|
|
209250
209569
|
{
|
|
209251
209570
|
name: "malloy-notebooks",
|
|
@@ -211450,7 +211769,7 @@ A flat layout at the package root is the simplest default, for models and report
|
|
|
211450
211769
|
|
|
211451
211770
|
Publishable contents:
|
|
211452
211771
|
- \`.malloy\` files - Semantic model definitions (base sources + joined sources)
|
|
211453
|
-
- 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.
|
|
211454
211773
|
- Data files (CSV/Parquet/XLSX) - Embedded data published with package
|
|
211455
211774
|
|
|
211456
211775
|
## Version Management
|
|
@@ -211840,8 +212159,8 @@ For anything not covered here, call \`search_malloy_docs\` with the topic (for e
|
|
|
211840
212159
|
},
|
|
211841
212160
|
{
|
|
211842
212161
|
name: "malloy-reports",
|
|
211843
|
-
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.
|
|
211844
|
-
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."
|
|
211845
212164
|
},
|
|
211846
212165
|
{
|
|
211847
212166
|
name: "malloy-reports/grid",
|
|
@@ -211934,9 +212253,7 @@ One query per tile, and remember a chart renders only the **first** aggregate in
|
|
|
211934
212253
|
|
|
211935
212254
|
## Existing \`.malloynb\` files
|
|
211936
212255
|
|
|
211937
|
-
A \`.malloynb\` (cells delimited by \`>>>markdown\` and \`>>>malloy\`) is a deprecated format
|
|
211938
|
-
|
|
211939
|
-
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.
|
|
211940
212257
|
|
|
211941
212258
|
## Common mistakes
|
|
211942
212259
|
|
|
@@ -212157,7 +212474,7 @@ This review covers 10,173 lines across 47 files. Only ~1,500 lines were deep-rev
|
|
|
212157
212474
|
{
|
|
212158
212475
|
name: "malloy-review/rubric-structure",
|
|
212159
212476
|
description: "Rubric: Structure. Reference detail for the malloy-review skill.",
|
|
212160
|
-
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.\""
|
|
212161
212478
|
},
|
|
212162
212479
|
{
|
|
212163
212480
|
name: "malloy-review/rubric-style",
|
|
@@ -212560,7 +212877,7 @@ function compareText(a, b) {
|
|
|
212560
212877
|
// src/service/package_revision.ts
|
|
212561
212878
|
import { createHash as createHash13, randomUUID as randomUUID4 } from "crypto";
|
|
212562
212879
|
import fs14 from "fs";
|
|
212563
|
-
import
|
|
212880
|
+
import path32 from "path";
|
|
212564
212881
|
import { pathToFileURL as pathToFileURL14 } from "url";
|
|
212565
212882
|
function computeSourceContentSha(packagePath, contentPaths, extra, contentShas) {
|
|
212566
212883
|
const hash = createHash13("sha256");
|
|
@@ -212571,7 +212888,7 @@ function computeSourceContentSha(packagePath, contentPaths, extra, contentShas)
|
|
|
212571
212888
|
if (precomputed !== undefined) {
|
|
212572
212889
|
hash.update(`\x00sha256\x00${precomputed}`);
|
|
212573
212890
|
} else {
|
|
212574
|
-
const absolute =
|
|
212891
|
+
const absolute = path32.join(packagePath, relativePath);
|
|
212575
212892
|
try {
|
|
212576
212893
|
hash.update(fs14.readFileSync(confinedPackagePathSync(packagePath, pathToFileURL14(absolute))));
|
|
212577
212894
|
} catch {
|
|
@@ -212611,7 +212928,7 @@ var init_package_revision = __esm(() => {
|
|
|
212611
212928
|
// src/service/skills/package_skills.ts
|
|
212612
212929
|
import { createHash as createHash14 } from "crypto";
|
|
212613
212930
|
import * as fs15 from "fs";
|
|
212614
|
-
import * as
|
|
212931
|
+
import * as path33 from "path";
|
|
212615
212932
|
import { pathToFileURL as pathToFileURL15 } from "url";
|
|
212616
212933
|
function insidePackage(packageRoot, p) {
|
|
212617
212934
|
try {
|
|
@@ -212680,7 +212997,7 @@ function readFileInside(packageRoot, file, maxBytes, asset = false) {
|
|
|
212680
212997
|
}
|
|
212681
212998
|
function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
212682
212999
|
try {
|
|
212683
|
-
if (insidePackage(packageRoot,
|
|
213000
|
+
if (insidePackage(packageRoot, path33.join(skillDir, "reference")) === undefined) {
|
|
212684
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.`);
|
|
212685
213002
|
return [];
|
|
212686
213003
|
}
|
|
@@ -212693,7 +213010,7 @@ function referenceFilesInside(packageRoot, skillDir, rel, warnings) {
|
|
|
212693
213010
|
}
|
|
212694
213011
|
}
|
|
212695
213012
|
function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
212696
|
-
const root =
|
|
213013
|
+
const root = path33.join(packagePath, dirRel);
|
|
212697
213014
|
const skills = [];
|
|
212698
213015
|
const files = [];
|
|
212699
213016
|
const warnings = [];
|
|
@@ -212707,7 +213024,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212707
213024
|
let escapes;
|
|
212708
213025
|
try {
|
|
212709
213026
|
fs15.realpathSync(packagePath);
|
|
212710
|
-
packageRoot =
|
|
213027
|
+
packageRoot = path33.resolve(packagePath);
|
|
212711
213028
|
const inside = insidePackage(packageRoot, root);
|
|
212712
213029
|
escapes = inside === undefined;
|
|
212713
213030
|
if (inside !== undefined) {
|
|
@@ -212728,7 +213045,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212728
213045
|
for (const entry of [...entries].sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
|
|
212729
213046
|
if (entry.name.startsWith("."))
|
|
212730
213047
|
continue;
|
|
212731
|
-
const skillDir =
|
|
213048
|
+
const skillDir = path33.join(root, entry.name);
|
|
212732
213049
|
const skillInside = insidePackage(packageRoot, skillDir);
|
|
212733
213050
|
if (skillInside !== undefined) {
|
|
212734
213051
|
try {
|
|
@@ -212739,7 +213056,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212739
213056
|
}
|
|
212740
213057
|
}
|
|
212741
213058
|
const rel = `${dirRel}/${entry.name}`;
|
|
212742
|
-
const read = readFileInside(packageRoot,
|
|
213059
|
+
const read = readFileInside(packageRoot, path33.join(skillDir, "SKILL.md"), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212743
213060
|
if ("problem" in read) {
|
|
212744
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.`);
|
|
212745
213062
|
continue;
|
|
@@ -212757,7 +213074,7 @@ function readSkillsDir(packagePath, dirRel = PACKAGE_SKILLS_DIR) {
|
|
|
212757
213074
|
const served = [];
|
|
212758
213075
|
for (const file of referenceFilesInside(packageRoot, skillDir, rel, warnings)) {
|
|
212759
213076
|
const relative = `${rel}/reference/${file}`;
|
|
212760
|
-
const ref = readFileInside(packageRoot,
|
|
213077
|
+
const ref = readFileInside(packageRoot, path33.join(skillDir, "reference", file), PACKAGE_SKILL_FILE_MAX_BYTES);
|
|
212761
213078
|
if ("problem" in ref) {
|
|
212762
213079
|
warnings.push(`Package skill reference '${relative}' ${ref.problem}, so it is not served.`);
|
|
212763
213080
|
continue;
|
|
@@ -212780,13 +213097,13 @@ function agentPath(value, what) {
|
|
|
212780
213097
|
if (typeof value !== "string" || value === "" || value.includes("\x00")) {
|
|
212781
213098
|
throw new AgentProblem(`${what} must be a non-empty package-relative path`);
|
|
212782
213099
|
}
|
|
212783
|
-
if (
|
|
213100
|
+
if (path33.posix.isAbsolute(value) || path33.win32.isAbsolute(value)) {
|
|
212784
213101
|
throw new AgentProblem(`${what} '${value}' is an absolute path`);
|
|
212785
213102
|
}
|
|
212786
213103
|
if (value.includes("\\")) {
|
|
212787
213104
|
throw new AgentProblem(`${what} '${value}' contains a backslash; write it with forward slashes`);
|
|
212788
213105
|
}
|
|
212789
|
-
const normalized =
|
|
213106
|
+
const normalized = path33.posix.normalize(value).replace(/\/+$/, "");
|
|
212790
213107
|
if (normalized === "." || normalized === ".." || normalized.startsWith("../")) {
|
|
212791
213108
|
throw new AgentProblem(`${what} '${value}' is outside the package`);
|
|
212792
213109
|
}
|
|
@@ -212809,7 +213126,7 @@ function servedTreeHoldsManifest(packageRoot, root) {
|
|
|
212809
213126
|
const inside = insidePackage(packageRoot, root);
|
|
212810
213127
|
if (inside === undefined)
|
|
212811
213128
|
return false;
|
|
212812
|
-
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"))));
|
|
212813
213130
|
} catch {
|
|
212814
213131
|
return false;
|
|
212815
213132
|
}
|
|
@@ -212819,12 +213136,12 @@ function readAgentText(packagePath, packageRoot, value, what) {
|
|
|
212819
213136
|
if (!rel.toLowerCase().endsWith(".md")) {
|
|
212820
213137
|
throw new AgentProblem(`${what} '${rel}' is not a .md file`);
|
|
212821
213138
|
}
|
|
212822
|
-
for (let dir =
|
|
212823
|
-
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))) {
|
|
212824
213141
|
throw new AgentProblem(`${what} '${rel}' sits under a nested publisher.json at '${dir}'`);
|
|
212825
213142
|
}
|
|
212826
213143
|
}
|
|
212827
|
-
const read = readFileInside(packageRoot,
|
|
213144
|
+
const read = readFileInside(packageRoot, path33.join(packagePath, rel), PACKAGE_AGENT_TEXT_MAX_BYTES);
|
|
212828
213145
|
if ("problem" in read) {
|
|
212829
213146
|
throw new AgentProblem(`${what} '${rel}' ${read.problem}`);
|
|
212830
213147
|
}
|
|
@@ -212883,7 +213200,7 @@ function readAgentBudget(raw) {
|
|
|
212883
213200
|
return Object.keys(budget).length > 0 ? budget : undefined;
|
|
212884
213201
|
}
|
|
212885
213202
|
function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
212886
|
-
const assetsDir =
|
|
213203
|
+
const assetsDir = path33.join(skillDir, "assets");
|
|
212887
213204
|
const realSkillDir = insidePackage(packageRoot, skillDir);
|
|
212888
213205
|
if (realSkillDir === undefined) {
|
|
212889
213206
|
throw new AgentProblem(`'${skillRel}' resolves outside the package`);
|
|
@@ -212892,13 +213209,13 @@ function realAssetsDir(packageRoot, skillDir, skillRel) {
|
|
|
212892
213209
|
throw new AgentProblem(`'${skillRel}/assets' is a link; replace it with a real directory`);
|
|
212893
213210
|
}
|
|
212894
213211
|
const real = fs15.realpathSync(assetsDir);
|
|
212895
|
-
if (real !==
|
|
213212
|
+
if (real !== path33.join(realSkillDir, "assets")) {
|
|
212896
213213
|
throw new AgentProblem(`'${skillRel}/assets' resolves outside the skill's own directory`);
|
|
212897
213214
|
}
|
|
212898
213215
|
return assetsDir;
|
|
212899
213216
|
}
|
|
212900
213217
|
function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk) {
|
|
212901
|
-
const assetsDir =
|
|
213218
|
+
const assetsDir = path33.join(skillDir, "assets");
|
|
212902
213219
|
let link;
|
|
212903
213220
|
try {
|
|
212904
213221
|
link = fs15.lstatSync(assetsDir);
|
|
@@ -212962,7 +213279,7 @@ function assetFilesInside(packageRoot, skillDir, skillRel, skill, budget, walk)
|
|
|
212962
213279
|
skip(shown, `its path is over ${ASSET_PATH_MAX_CHARS} characters`);
|
|
212963
213280
|
continue;
|
|
212964
213281
|
}
|
|
212965
|
-
const absolute =
|
|
213282
|
+
const absolute = path33.join(dir, entry.name);
|
|
212966
213283
|
if (entry.isDirectory()) {
|
|
212967
213284
|
if (depth >= ASSET_MAX_DEPTH) {
|
|
212968
213285
|
skip(shown, `it is nested deeper than ${ASSET_MAX_DEPTH} levels`);
|
|
@@ -213034,8 +213351,8 @@ function readAgentAsset(packagePath, agent, relativeFilepath) {
|
|
|
213034
213351
|
if (skillRel === undefined || !listing)
|
|
213035
213352
|
return;
|
|
213036
213353
|
try {
|
|
213037
|
-
const skillDir =
|
|
213038
|
-
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);
|
|
213039
213356
|
if (!("text" in read))
|
|
213040
213357
|
return;
|
|
213041
213358
|
return createHash14("sha256").update(read.text).digest("hex") === listing.sha256 ? read.text : undefined;
|
|
@@ -213064,7 +213381,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213064
213381
|
};
|
|
213065
213382
|
let bytes = 0;
|
|
213066
213383
|
for (const root of roots) {
|
|
213067
|
-
const rootInside = insidePackage(packageRoot,
|
|
213384
|
+
const rootInside = insidePackage(packageRoot, path33.join(packagePath, root));
|
|
213068
213385
|
if (rootInside === undefined) {
|
|
213069
213386
|
throw new AgentProblem(`skills directory '${root}' resolves outside the package`);
|
|
213070
213387
|
}
|
|
@@ -213075,8 +213392,8 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213075
213392
|
} catch {
|
|
213076
213393
|
throw new AgentProblem(`skills directory '${root}' does not exist`);
|
|
213077
213394
|
}
|
|
213078
|
-
for (let dir = root;dir !== "."; dir =
|
|
213079
|
-
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));
|
|
213080
213397
|
if (holds) {
|
|
213081
213398
|
throw new AgentProblem(`skills directory '${root}' contains a nested publisher.json`);
|
|
213082
213399
|
}
|
|
@@ -213115,7 +213432,7 @@ function readAgentSkills(packagePath, packageRoot, raw, paths, warnings, assetBu
|
|
|
213115
213432
|
}
|
|
213116
213433
|
for (const skill of skillNames) {
|
|
213117
213434
|
const skillRel = `${root}/${skill}`;
|
|
213118
|
-
const listed = assetFilesInside(packageRoot,
|
|
213435
|
+
const listed = assetFilesInside(packageRoot, path33.join(packagePath, skillRel), skillRel, skill, assetBudget, walk);
|
|
213119
213436
|
for (const asset of listed) {
|
|
213120
213437
|
assets.set(asset.relative_filepath, asset);
|
|
213121
213438
|
assetRoots.set(skill, skillRel);
|
|
@@ -213229,7 +213546,7 @@ function readPackageAgents(packagePath, raw) {
|
|
|
213229
213546
|
let packageRoot;
|
|
213230
213547
|
try {
|
|
213231
213548
|
fs15.realpathSync(packagePath);
|
|
213232
|
-
packageRoot =
|
|
213549
|
+
packageRoot = path33.resolve(packagePath);
|
|
213233
213550
|
} catch {
|
|
213234
213551
|
return result;
|
|
213235
213552
|
}
|
|
@@ -215181,7 +215498,7 @@ var init_esm2 = __esm(() => {
|
|
|
215181
215498
|
// src/service/configured_publish_retry.ts
|
|
215182
215499
|
import { createHash as createHash15 } from "crypto";
|
|
215183
215500
|
import * as fs16 from "fs";
|
|
215184
|
-
import * as
|
|
215501
|
+
import * as path34 from "path";
|
|
215185
215502
|
function backoffAfter(failures) {
|
|
215186
215503
|
if (failures <= 0)
|
|
215187
215504
|
return 0;
|
|
@@ -215192,13 +215509,13 @@ async function localPackageFingerprint(root) {
|
|
|
215192
215509
|
const walk = async (dir) => {
|
|
215193
215510
|
const entries = await fs16.promises.readdir(dir, { withFileTypes: true });
|
|
215194
215511
|
for (const entry of entries) {
|
|
215195
|
-
const full =
|
|
215512
|
+
const full = path34.join(dir, entry.name);
|
|
215196
215513
|
if (entry.isDirectory()) {
|
|
215197
215514
|
if (!SKIPPED_DIRS.has(entry.name))
|
|
215198
215515
|
await walk(full);
|
|
215199
215516
|
} else if (entry.isFile() && FINGERPRINTED.test(entry.name)) {
|
|
215200
215517
|
const stat = await fs16.promises.stat(full);
|
|
215201
|
-
lines.push(`${
|
|
215518
|
+
lines.push(`${path34.relative(root, full)}\x00${stat.size}\x00${stat.mtimeMs}`);
|
|
215202
215519
|
}
|
|
215203
215520
|
}
|
|
215204
215521
|
};
|
|
@@ -368658,8 +368975,12 @@ var init_dim_index_entity_id = __esm(() => {
|
|
|
368658
368975
|
});
|
|
368659
368976
|
|
|
368660
368977
|
// src/service/entities/source_extraction.ts
|
|
368661
|
-
import
|
|
368978
|
+
import path35 from "path";
|
|
368662
368979
|
import { fileURLToPath as fileURLToPath14 } from "url";
|
|
368980
|
+
import {
|
|
368981
|
+
isJoined as isJoined7,
|
|
368982
|
+
isJoinedSource
|
|
368983
|
+
} from "@malloydata/malloy";
|
|
368663
368984
|
function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
368664
368985
|
const sourceToModelPath = new Map;
|
|
368665
368986
|
for (const explore of explores) {
|
|
@@ -368673,7 +368994,7 @@ function buildSourceToModelPathMap(explores, relpath, packageRoot) {
|
|
|
368673
368994
|
if (fullPath.startsWith(packageRoot)) {
|
|
368674
368995
|
modelPath = fullPath.slice(packageRoot.length).replace(/^[/\\]/, "");
|
|
368675
368996
|
} else {
|
|
368676
|
-
modelPath =
|
|
368997
|
+
modelPath = path35.basename(fullPath);
|
|
368677
368998
|
}
|
|
368678
368999
|
} else {
|
|
368679
369000
|
modelPath = url;
|
|
@@ -368705,6 +369026,17 @@ function parseJoinCode(joinCode, fieldName, sourceToModelPath) {
|
|
|
368705
369026
|
is_nested_index: isNestedIndex
|
|
368706
369027
|
};
|
|
368707
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
|
+
}
|
|
368708
369040
|
function descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary) {
|
|
368709
369041
|
const targetName = joinMetadata.original_source_name;
|
|
368710
369042
|
const targetIsAtTopLevel = targetName != null && topLevelExploreNames.has(targetName);
|
|
@@ -368715,7 +369047,7 @@ function descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, bo
|
|
|
368715
369047
|
function joinDescent(explores, relativePath, packageRoot, docString, boundary) {
|
|
368716
369048
|
const sourceToModelPath = buildSourceToModelPathMap(explores, relativePath, packageRoot);
|
|
368717
369049
|
const topLevelExploreNames = new Set(explores.map((e) => e.name));
|
|
368718
|
-
return (join, parentSourceName) => descendsIntoJoin(
|
|
369050
|
+
return (join, parentSourceName) => descendsIntoJoin(joinMetadataOf(join, docString, sourceToModelPath), parentSourceName.split(".")[0], topLevelExploreNames, boundary);
|
|
368719
369051
|
}
|
|
368720
369052
|
function getEntitiesFromExplore(explore, docString, relativePath, parentPath, sourceToModelPath, dimIndexFingerprints, topLevelExploreNames, boundary, guard) {
|
|
368721
369053
|
const entities = [];
|
|
@@ -368727,8 +369059,7 @@ function getEntitiesFromExplore(explore, docString, relativePath, parentPath, so
|
|
|
368727
369059
|
}
|
|
368728
369060
|
let joinMetadata = null;
|
|
368729
369061
|
if (field.isExploreField()) {
|
|
368730
|
-
|
|
368731
|
-
joinMetadata = parseJoinCode(joinCode, field.name, sourceToModelPath);
|
|
369062
|
+
joinMetadata = joinMetadataOf(field, docString, sourceToModelPath);
|
|
368732
369063
|
const descent = descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary);
|
|
368733
369064
|
if (descent !== false) {
|
|
368734
369065
|
const nestedEntities = getEntitiesFromExplore(field, docString, relativePath, sourceName, sourceToModelPath, dimIndexFingerprints, topLevelExploreNames, boundary, descent === true ? guard : guardDescent(guard, rootSourceName, descent.unlessQueryable));
|
|
@@ -368764,8 +369095,7 @@ function planJoinAuthorizeMetadata(explore, docString, relativePath, parentPath,
|
|
|
368764
369095
|
}
|
|
368765
369096
|
if (getAccessModifier(field) !== "public" /* Public */)
|
|
368766
369097
|
continue;
|
|
368767
|
-
const
|
|
368768
|
-
const joinMetadata = parseJoinCode(joinCode, field.name, sourceToModelPath);
|
|
369098
|
+
const joinMetadata = joinMetadataOf(field, docString, sourceToModelPath);
|
|
368769
369099
|
const targetName = joinMetadata.original_source_name;
|
|
368770
369100
|
const descent = descendsIntoJoin(joinMetadata, rootSourceName, topLevelExploreNames, boundary);
|
|
368771
369101
|
const joinedExplore = field;
|
|
@@ -369502,7 +369832,8 @@ function toApiField(entity) {
|
|
|
369502
369832
|
},
|
|
369503
369833
|
...join.original_source_path != null && {
|
|
369504
369834
|
sourcePath: join.original_source_path
|
|
369505
|
-
}
|
|
369835
|
+
},
|
|
369836
|
+
...join.relationship && { relationship: join.relationship }
|
|
369506
369837
|
};
|
|
369507
369838
|
}
|
|
369508
369839
|
if (entity.dim_index_fingerprint) {
|
|
@@ -369757,6 +370088,9 @@ function checkLoadPackageResult(raw) {
|
|
|
369757
370088
|
if (raw.refreshedSchemaKeys !== undefined && !(Array.isArray(raw.refreshedSchemaKeys) && raw.refreshedSchemaKeys.every((key) => typeof key === "string"))) {
|
|
369758
370089
|
throw new PackageLoadProtocolError(`a load-package-result has refreshedSchemaKeys that are not strings`);
|
|
369759
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
|
+
}
|
|
369760
370094
|
for (const model of raw.models)
|
|
369761
370095
|
decodeSerializedModel(model);
|
|
369762
370096
|
return raw;
|
|
@@ -370600,7 +370934,8 @@ function adaptResult(result) {
|
|
|
370600
370934
|
})),
|
|
370601
370935
|
loadDurationMs: result.loadDurationMs,
|
|
370602
370936
|
timings: result.timings,
|
|
370603
|
-
buildPlan: result.buildPlan
|
|
370937
|
+
buildPlan: result.buildPlan,
|
|
370938
|
+
...result.fileDigests ? { fileDigests: result.fileDigests } : {}
|
|
370604
370939
|
};
|
|
370605
370940
|
}
|
|
370606
370941
|
function currentPackageLoadPool() {
|
|
@@ -370636,11 +370971,221 @@ var init_package_load_pool = __esm(() => {
|
|
|
370636
370971
|
};
|
|
370637
370972
|
});
|
|
370638
370973
|
|
|
370639
|
-
// src/
|
|
370974
|
+
// src/package_load/job_files.ts
|
|
370975
|
+
import {
|
|
370976
|
+
CacheManager,
|
|
370977
|
+
InMemoryModelCache
|
|
370978
|
+
} from "@malloydata/malloy";
|
|
370640
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";
|
|
370641
371186
|
import * as fs19 from "fs";
|
|
370642
|
-
import * as
|
|
370643
|
-
import { pathToFileURL as
|
|
371187
|
+
import * as path37 from "path";
|
|
371188
|
+
import { pathToFileURL as pathToFileURL19 } from "url";
|
|
370644
371189
|
function alsoLikelyOn(settings) {
|
|
370645
371190
|
return settings.alsoLikely === "auto" ? settings.connect === "list" : settings.alsoLikely;
|
|
370646
371191
|
}
|
|
@@ -370659,12 +371204,12 @@ function describe3(value) {
|
|
|
370659
371204
|
function resolvePromptPath(packageRoot, rel, promptKey = "judge") {
|
|
370660
371205
|
const key = `retrieval.prompts.${promptKey}`;
|
|
370661
371206
|
const fix = `Fix: use a path inside the package, e.g. "prompts/${promptKey}.md".`;
|
|
370662
|
-
if (rel.includes("\x00") ||
|
|
371207
|
+
if (rel.includes("\x00") || path37.isAbsolute(rel) || /^[A-Za-z]:[\\/]/.test(rel) || rel.startsWith("\\")) {
|
|
370663
371208
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} is an absolute path. ${fix}`);
|
|
370664
371209
|
}
|
|
370665
|
-
const root =
|
|
370666
|
-
const resolved =
|
|
370667
|
-
const within =
|
|
371210
|
+
const root = path37.resolve(packageRoot);
|
|
371211
|
+
const resolved = path37.resolve(root, rel);
|
|
371212
|
+
const within = path37.relative(root, resolved);
|
|
370668
371213
|
if (within === "" || stepsOutside(within)) {
|
|
370669
371214
|
fail(`Invalid publisher.json ${key}: ${describe3(rel)} resolves outside the package directory. ${fix}`);
|
|
370670
371215
|
}
|
|
@@ -370859,7 +371404,7 @@ async function readPromptFile(packageRoot, key, rel) {
|
|
|
370859
371404
|
try {
|
|
370860
371405
|
let realFile;
|
|
370861
371406
|
try {
|
|
370862
|
-
realFile = await confinedPackagePath(packageRoot,
|
|
371407
|
+
realFile = await confinedPackagePath(packageRoot, pathToFileURL19(file));
|
|
370863
371408
|
} catch (error) {
|
|
370864
371409
|
if (!(error instanceof ImportOutsidePackageError))
|
|
370865
371410
|
throw error;
|
|
@@ -370877,7 +371422,7 @@ async function readPromptFile(packageRoot, key, rel) {
|
|
|
370877
371422
|
return {
|
|
370878
371423
|
path: rel,
|
|
370879
371424
|
text,
|
|
370880
|
-
hash:
|
|
371425
|
+
hash: createHash18("sha256").update(text).digest("hex")
|
|
370881
371426
|
};
|
|
370882
371427
|
}
|
|
370883
371428
|
async function readPackageRetrieval(packageRoot, raw) {
|
|
@@ -372079,11 +372624,11 @@ class VariantCompileCache {
|
|
|
372079
372624
|
var DEFAULT_LIMIT = 500;
|
|
372080
372625
|
|
|
372081
372626
|
// src/service/materialization/serve/author_imports.ts
|
|
372082
|
-
import * as
|
|
372083
|
-
import { fileURLToPath as
|
|
372627
|
+
import * as path38 from "path";
|
|
372628
|
+
import { fileURLToPath as fileURLToPath17 } from "url";
|
|
372084
372629
|
function relativeImport(from, url) {
|
|
372085
372630
|
try {
|
|
372086
|
-
return
|
|
372631
|
+
return path38.relative(path38.dirname(fileURLToPath17(from)), fileURLToPath17(url)).split(path38.sep).join("/");
|
|
372087
372632
|
} catch {
|
|
372088
372633
|
return;
|
|
372089
372634
|
}
|
|
@@ -372136,15 +372681,15 @@ var init_author_imports = __esm(() => {
|
|
|
372136
372681
|
});
|
|
372137
372682
|
|
|
372138
372683
|
// src/service/materialization/serve/declaring_file_variant.ts
|
|
372139
|
-
import * as
|
|
372140
|
-
import { fileURLToPath as
|
|
372684
|
+
import * as path39 from "path";
|
|
372685
|
+
import { fileURLToPath as fileURLToPath18, pathToFileURL as pathToFileURL20 } from "url";
|
|
372141
372686
|
async function compileDeclaringFileVariant(args) {
|
|
372142
372687
|
const { packagePath, modelPath, packageConfig, modelDef } = args;
|
|
372143
372688
|
const declared = args.sourceID !== undefined ? declaringFileOf2(args.sourceID, args.copySuffix) : args.declaringURL !== undefined ? declaringFileAt("", args.declaringURL, args.copySuffix) : { error: "no declaring file" };
|
|
372144
372689
|
if ("error" in declared)
|
|
372145
372690
|
return declared;
|
|
372146
372691
|
const { declaringURL, copyURL, copyName } = declared;
|
|
372147
|
-
const modelFile =
|
|
372692
|
+
const modelFile = path39.join(packagePath, modelPath);
|
|
372148
372693
|
const authorFiles = packageFiles(packagePath, modelPath, args.basis ? args.config : packageConfig);
|
|
372149
372694
|
const blanked = args.basis ? new Map(args.basis.files) : await authorFiles.blanked(modelDef);
|
|
372150
372695
|
if (!blanked)
|
|
@@ -372174,7 +372719,7 @@ async function compileDeclaringFileVariant(args) {
|
|
|
372174
372719
|
...args.alsoRedeclared ?? []
|
|
372175
372720
|
]);
|
|
372176
372721
|
const exported = new Set(namesModel.exports ?? []);
|
|
372177
|
-
const modelHref = overlayKey(
|
|
372722
|
+
const modelHref = overlayKey(pathToFileURL20(modelFile));
|
|
372178
372723
|
for (const importer of importersOf(namesModel, declaringURL)) {
|
|
372179
372724
|
if (overlayKey(importer) === modelHref && [...redeclared].some((n) => exported.has(n))) {
|
|
372180
372725
|
continue;
|
|
@@ -372210,7 +372755,7 @@ async function compileDeclaringFileVariant(args) {
|
|
|
372210
372755
|
${importOthers}
|
|
372211
372756
|
${declaration}
|
|
372212
372757
|
${exportAll}`);
|
|
372213
|
-
const imports = authorNameImports(namesModel, args.queryModelURL,
|
|
372758
|
+
const imports = authorNameImports(namesModel, args.queryModelURL, pathToFileURL20(modelFile).href, {
|
|
372214
372759
|
skip: new Set(args.alsoExported ?? []),
|
|
372215
372760
|
redirect: {
|
|
372216
372761
|
from: overlayKey(declaringURL),
|
|
@@ -372239,13 +372784,13 @@ function declaringFileOf2(sourceID, copySuffix) {
|
|
|
372239
372784
|
function declaringFileAt(name, url, copySuffix) {
|
|
372240
372785
|
let declaringFile;
|
|
372241
372786
|
try {
|
|
372242
|
-
declaringFile =
|
|
372787
|
+
declaringFile = fileURLToPath18(url);
|
|
372243
372788
|
} catch {
|
|
372244
372789
|
return { error: "not a local file" };
|
|
372245
372790
|
}
|
|
372246
|
-
const declaringURL =
|
|
372247
|
-
const copyURL =
|
|
372248
|
-
const copyName =
|
|
372791
|
+
const declaringURL = pathToFileURL20(declaringFile);
|
|
372792
|
+
const copyURL = pathToFileURL20(`${declaringFile}${copySuffix}`);
|
|
372793
|
+
const copyName = path39.basename(fileURLToPath18(copyURL));
|
|
372249
372794
|
return { name, declaringURL, copyURL, copyName };
|
|
372250
372795
|
}
|
|
372251
372796
|
async function namesDeclaredIn(files, overlay, url) {
|
|
@@ -372375,8 +372920,8 @@ var init_stored_typed_source = __esm(() => {
|
|
|
372375
372920
|
});
|
|
372376
372921
|
|
|
372377
372922
|
// src/service/materialization/serve/view_variants.ts
|
|
372378
|
-
import * as
|
|
372379
|
-
import { fileURLToPath as
|
|
372923
|
+
import * as path40 from "path";
|
|
372924
|
+
import { fileURLToPath as fileURLToPath19, pathToFileURL as pathToFileURL21 } from "url";
|
|
372380
372925
|
|
|
372381
372926
|
class PersistedViewServe {
|
|
372382
372927
|
host;
|
|
@@ -372659,7 +373204,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372659
373204
|
return { refusal: read.refusal };
|
|
372660
373205
|
const sourceTimezone = shape.sourceTimezone ? `
|
|
372661
373206
|
timezone: ${stringLiteral(shape.sourceTimezone)}` : "";
|
|
372662
|
-
const modelFile =
|
|
373207
|
+
const modelFile = path40.join(packagePath, args.modelPath);
|
|
372663
373208
|
const config = table.binding && !isDatabase(table.binding) && args.destinations ? servedCopyConfig(packageConfig, args.destinations(), new Set([table.binding.destinationName])) : packageConfig;
|
|
372664
373209
|
return compileDeclaringFileVariant({
|
|
372665
373210
|
packagePath,
|
|
@@ -372669,7 +373214,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372669
373214
|
modelDef: args.modelDef,
|
|
372670
373215
|
...args.redeclare,
|
|
372671
373216
|
copySuffix: ".view-author.malloy",
|
|
372672
|
-
queryModelURL:
|
|
373217
|
+
queryModelURL: pathToFileURL21(`${modelFile}.view.malloy`),
|
|
372673
373218
|
flags: VARIANT_FLAGS,
|
|
372674
373219
|
declare: ({ gates, sourceName, copyName, declaringURL, addFile }) => {
|
|
372675
373220
|
if (table.binding) {
|
|
@@ -372702,7 +373247,7 @@ async function compilePersistedResultVariant(args) {
|
|
|
372702
373247
|
sourceTimezone,
|
|
372703
373248
|
stored: {
|
|
372704
373249
|
name,
|
|
372705
|
-
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)))}`
|
|
372706
373251
|
}
|
|
372707
373252
|
});
|
|
372708
373253
|
}
|
|
@@ -373912,6 +374457,7 @@ var init_admission_lookup = __esm(() => {
|
|
|
373912
374457
|
init_prepared_query();
|
|
373913
374458
|
init_source_reads();
|
|
373914
374459
|
init_collation();
|
|
374460
|
+
init_collation2();
|
|
373915
374461
|
init_bigquery2();
|
|
373916
374462
|
init_string_paths();
|
|
373917
374463
|
init_gate_reads();
|
|
@@ -378612,8 +379158,8 @@ var init_join_rollup = __esm(() => {
|
|
|
378612
379158
|
});
|
|
378613
379159
|
|
|
378614
379160
|
// src/service/materialization/serve/rollup_variants.ts
|
|
378615
|
-
import * as
|
|
378616
|
-
import { fileURLToPath as
|
|
379161
|
+
import * as path41 from "path";
|
|
379162
|
+
import { fileURLToPath as fileURLToPath20, pathToFileURL as pathToFileURL22 } from "url";
|
|
378617
379163
|
import { EMPTY_BUILD_MANIFEST as EMPTY_BUILD_MANIFEST4 } from "@malloydata/malloy";
|
|
378618
379164
|
|
|
378619
379165
|
class RollupVariantServe {
|
|
@@ -379417,8 +379963,8 @@ class RollupVariantServe {
|
|
|
379417
379963
|
if (!packagePath || !packageConfig)
|
|
379418
379964
|
return { error: "no context" };
|
|
379419
379965
|
const modelPath = this.host.modelPath();
|
|
379420
|
-
const modelFile =
|
|
379421
|
-
const queryModelURL =
|
|
379966
|
+
const modelFile = path41.join(packagePath, modelPath);
|
|
379967
|
+
const queryModelURL = pathToFileURL22(`${modelFile}.rollup.malloy`);
|
|
379422
379968
|
const reads = table.binding ? storedRollupReads(plan, table.binding, this.host.modelDef(), declaredRollupColumns(this.host.catalog(), table.binding)) : undefined;
|
|
379423
379969
|
const destinations = this.host.serveDestinationConfig();
|
|
379424
379970
|
const config = table.binding && !isDatabase(table.binding) && destinations ? servedCopyConfig(packageConfig, destinations(), new Set([table.binding.destinationName])) : packageConfig;
|
|
@@ -379461,11 +380007,11 @@ class RollupVariantServe {
|
|
|
379461
380007
|
const companion = declared ? rollupCompanionURLOf(declared.url) : undefined;
|
|
379462
380008
|
let declaringFile;
|
|
379463
380009
|
try {
|
|
379464
|
-
declaringFile = declared ?
|
|
380010
|
+
declaringFile = declared ? fileURLToPath20(declared.url) : undefined;
|
|
379465
380011
|
} catch {
|
|
379466
380012
|
declaringFile = undefined;
|
|
379467
380013
|
}
|
|
379468
|
-
const text = companion && declaringFile ? generateRollupBuildFile([plan],
|
|
380014
|
+
const text = companion && declaringFile ? generateRollupBuildFile([plan], path41.basename(declaringFile)) : undefined;
|
|
379469
380015
|
if (!companion || !text || !declaringFile) {
|
|
379470
380016
|
return { error: "no companion" };
|
|
379471
380017
|
}
|
|
@@ -379476,16 +380022,16 @@ class RollupVariantServe {
|
|
|
379476
380022
|
for (const [url, file] of blanked)
|
|
379477
380023
|
overlay.set(url, file);
|
|
379478
380024
|
if (readsBuildCopy(plan)) {
|
|
379479
|
-
const baseURL =
|
|
380025
|
+
const baseURL = pathToFileURL22(declaringFile);
|
|
379480
380026
|
const made = rollupBuildCopyText(blanked.get(overlayKey(baseURL)) ?? await authorFiles.readIfAny(baseURL.href) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379481
380027
|
if (!("copy" in made))
|
|
379482
380028
|
return { error: made.reason };
|
|
379483
|
-
overlay.set(
|
|
380029
|
+
overlay.set(pathToFileURL22(path41.join(path41.dirname(declaringFile), rollupBuildCopyName(path41.basename(declaringFile), plan.baseDeclaredName))).href, made.copy);
|
|
379484
380030
|
}
|
|
379485
380031
|
const read = withoutLeftOut(plan, this.host.modelDef(), table.leftOut);
|
|
379486
380032
|
const declaration = `${databaseRollupSource(read.plan, this.host.modelDef(), servedName, relativeImport(queryModelURL, companion.href), read.dropped)}
|
|
379487
380033
|
${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
379488
|
-
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);
|
|
379489
380035
|
overlay.set(queryModelURL.href, modelText);
|
|
379490
380036
|
const { materializer, model, runtime } = await packageFiles(packagePath, modelPath, config).compile(queryModelURL, overlay);
|
|
379491
380037
|
return {
|
|
@@ -379501,7 +380047,7 @@ ${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
|
379501
380047
|
const read = withoutLeftOut(plan, modelDef, reads.leftOut);
|
|
379502
380048
|
const declaration = `${storedRollupDeclaration(read.plan, binding, reads, servedName, modelDef, read.dropped)}
|
|
379503
380049
|
${sourceOverRollup(read.plan, use, servedName, "")}`;
|
|
379504
|
-
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)]]) });
|
|
379505
380051
|
const overlay = new Map(basis.files);
|
|
379506
380052
|
overlay.set(ctx.queryModelURL.href, `${flagLine(modelDef)}
|
|
379507
380053
|
${imports}
|
|
@@ -379600,23 +380146,23 @@ ${gates}${over}`;
|
|
|
379600
380146
|
}
|
|
379601
380147
|
let baseFile;
|
|
379602
380148
|
try {
|
|
379603
|
-
baseFile = base ?
|
|
380149
|
+
baseFile = base ? fileURLToPath20(base.url) : undefined;
|
|
379604
380150
|
} catch {
|
|
379605
380151
|
baseFile = undefined;
|
|
379606
380152
|
}
|
|
379607
380153
|
if (!companion || !baseFile)
|
|
379608
380154
|
return { error: "no companion" };
|
|
379609
|
-
const overlaid = overlayKey(
|
|
379610
|
-
const importPath = overlaid ? copyName :
|
|
380155
|
+
const overlaid = overlayKey(pathToFileURL22(baseFile)) === overlayKey(declaringURL);
|
|
380156
|
+
const importPath = overlaid ? copyName : path41.basename(baseFile);
|
|
379611
380157
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379612
380158
|
if (!text)
|
|
379613
380159
|
return { error: "no companion" };
|
|
379614
380160
|
addFile(companion, text);
|
|
379615
380161
|
if (readsBuildCopy(plan)) {
|
|
379616
|
-
const made = rollupBuildCopyText(await authorText(
|
|
380162
|
+
const made = rollupBuildCopyText(await authorText(pathToFileURL22(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379617
380163
|
if (!("copy" in made))
|
|
379618
380164
|
return { error: made.reason };
|
|
379619
|
-
addFile(
|
|
380165
|
+
addFile(pathToFileURL22(path41.join(path41.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379620
380166
|
}
|
|
379621
380167
|
return `${databaseRollupSource(read.plan, modelDef, servedName, relativeImport(declaringURL, companion.href), read.dropped)}
|
|
379622
380168
|
${gates}${over}`;
|
|
@@ -379648,23 +380194,23 @@ async function databaseRollupInOverlay(plan, read, modelDef, ctx) {
|
|
|
379648
380194
|
const companion = base ? rollupCompanionURLOf(base.url) : undefined;
|
|
379649
380195
|
let baseFile;
|
|
379650
380196
|
try {
|
|
379651
|
-
baseFile = base ?
|
|
380197
|
+
baseFile = base ? fileURLToPath20(base.url) : undefined;
|
|
379652
380198
|
} catch {
|
|
379653
380199
|
baseFile = undefined;
|
|
379654
380200
|
}
|
|
379655
380201
|
if (!companion || !baseFile)
|
|
379656
380202
|
return { error: "no companion" };
|
|
379657
|
-
const overlaid = overlayKey(
|
|
379658
|
-
const importPath = overlaid ? copyName :
|
|
380203
|
+
const overlaid = overlayKey(pathToFileURL22(baseFile)) === overlayKey(declaringURL);
|
|
380204
|
+
const importPath = overlaid ? copyName : path41.basename(baseFile);
|
|
379659
380205
|
const text = generateRollupBuildFile([plan], importPath);
|
|
379660
380206
|
if (!text)
|
|
379661
380207
|
return { error: "no companion" };
|
|
379662
380208
|
addFile(companion, text);
|
|
379663
380209
|
if (readsBuildCopy(plan)) {
|
|
379664
|
-
const made = rollupBuildCopyText(await authorText(
|
|
380210
|
+
const made = rollupBuildCopyText(await authorText(pathToFileURL22(baseFile)) ?? "", plan, (plan.privateGrain ?? []).length > 0);
|
|
379665
380211
|
if (!("copy" in made))
|
|
379666
380212
|
return { error: made.reason };
|
|
379667
|
-
addFile(
|
|
380213
|
+
addFile(pathToFileURL22(path41.join(path41.dirname(baseFile), rollupBuildCopyName(importPath, plan.baseDeclaredName))), made.copy);
|
|
379668
380214
|
}
|
|
379669
380215
|
return databaseRollupSource(read.plan, modelDef, ctx.servedName, relativeImport(declaringURL, companion.href), read.dropped);
|
|
379670
380216
|
}
|
|
@@ -380372,18 +380918,30 @@ class PackageModelPolicy {
|
|
|
380372
380918
|
boundaries;
|
|
380373
380919
|
siblingResolver;
|
|
380374
380920
|
serving;
|
|
380921
|
+
successor;
|
|
380375
380922
|
forModel(modelPath) {
|
|
380923
|
+
const live = () => this.current();
|
|
380376
380924
|
return Object.freeze({
|
|
380377
380925
|
origin: "package",
|
|
380378
|
-
discoveryCurationEnabled: () =>
|
|
380379
|
-
queryBoundary: () =>
|
|
380380
|
-
siblingModelDefResolver: () =>
|
|
380381
|
-
snapshot: () =>
|
|
380382
|
-
preaggregateEntityIds: () =>
|
|
380383
|
-
materializedTables: () =>
|
|
380384
|
-
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)
|
|
380385
380933
|
});
|
|
380386
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
|
+
}
|
|
380387
380945
|
setDiscoveryCuration(enabled) {
|
|
380388
380946
|
this.discoveryCuration = enabled;
|
|
380389
380947
|
}
|
|
@@ -380429,8 +380987,8 @@ import {
|
|
|
380429
380987
|
Annotations as Annotations11
|
|
380430
380988
|
} from "@malloydata/malloy";
|
|
380431
380989
|
import { createRequire as createRequire4 } from "module";
|
|
380432
|
-
import * as
|
|
380433
|
-
import { fileURLToPath as
|
|
380990
|
+
import * as path42 from "path";
|
|
380991
|
+
import { fileURLToPath as fileURLToPath21, pathToFileURL as pathToFileURL23 } from "url";
|
|
380434
380992
|
function placeholderGivens(givens) {
|
|
380435
380993
|
const out = {};
|
|
380436
380994
|
for (const given of givens ?? []) {
|
|
@@ -380671,7 +381229,7 @@ var init_model = __esm(() => {
|
|
|
380671
381229
|
if (this.modelFile === undefined)
|
|
380672
381230
|
return false;
|
|
380673
381231
|
try {
|
|
380674
|
-
return
|
|
381232
|
+
return path42.resolve(fileURLToPath21(url)) === this.modelFile;
|
|
380675
381233
|
} catch {
|
|
380676
381234
|
return false;
|
|
380677
381235
|
}
|
|
@@ -380780,7 +381338,7 @@ var init_model = __esm(() => {
|
|
|
380780
381338
|
modelType,
|
|
380781
381339
|
modelMaterializer,
|
|
380782
381340
|
modelDef,
|
|
380783
|
-
modelFile:
|
|
381341
|
+
modelFile: path42.resolve(packagePath, modelPath),
|
|
380784
381342
|
sources,
|
|
380785
381343
|
queries,
|
|
380786
381344
|
sourceInfos,
|
|
@@ -380861,7 +381419,7 @@ var init_model = __esm(() => {
|
|
|
380861
381419
|
modelType: data.modelType,
|
|
380862
381420
|
modelMaterializer,
|
|
380863
381421
|
modelDef,
|
|
380864
|
-
modelFile:
|
|
381422
|
+
modelFile: path42.resolve(packagePath, data.modelPath),
|
|
380865
381423
|
sources,
|
|
380866
381424
|
queries,
|
|
380867
381425
|
sourceInfos,
|
|
@@ -381735,6 +382293,7 @@ var init_model = __esm(() => {
|
|
|
381735
382293
|
givens
|
|
381736
382294
|
}));
|
|
381737
382295
|
},
|
|
382296
|
+
authorPreparedQuery: async (queryString) => this.modelMaterializer?.loadRestrictedQuery(queryString).getPreparedQuery(),
|
|
381738
382297
|
ensureSharedQueryModel: (materializer) => this.ensureSharedQueryModel(materializer),
|
|
381739
382298
|
modelPath: () => this.modelPath,
|
|
381740
382299
|
modelDef: () => this.modelDef,
|
|
@@ -382382,9 +382941,9 @@ var init_model = __esm(() => {
|
|
|
382382
382941
|
return createModelMaterializer(...args);
|
|
382383
382942
|
}
|
|
382384
382943
|
async getFileText(packagePath) {
|
|
382385
|
-
const fullPath =
|
|
382944
|
+
const fullPath = path42.join(packagePath, this.modelPath);
|
|
382386
382945
|
try {
|
|
382387
|
-
return await readPackageURL(packagePath,
|
|
382946
|
+
return await readPackageURL(packagePath, pathToFileURL23(fullPath));
|
|
382388
382947
|
} catch {
|
|
382389
382948
|
throw new ModelNotFoundError(`Model file not found: ${this.modelPath}`);
|
|
382390
382949
|
}
|
|
@@ -382513,8 +383072,8 @@ var init_package_load_gates = __esm(() => {
|
|
|
382513
383072
|
|
|
382514
383073
|
// src/service/package.ts
|
|
382515
383074
|
import * as fs20 from "fs/promises";
|
|
382516
|
-
import * as
|
|
382517
|
-
import { pathToFileURL as
|
|
383075
|
+
import * as path43 from "path";
|
|
383076
|
+
import { pathToFileURL as pathToFileURL24 } from "url";
|
|
382518
383077
|
import"@malloydata/db-duckdb/native";
|
|
382519
383078
|
import { DuckDBConnection as DuckDBConnection8 } from "@malloydata/db-duckdb";
|
|
382520
383079
|
import {
|
|
@@ -382526,6 +383085,22 @@ import {
|
|
|
382526
383085
|
MalloyError as MalloyError16,
|
|
382527
383086
|
Model as MalloyModel
|
|
382528
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
|
+
}
|
|
382529
383104
|
function packageLoadFailureStatus(error) {
|
|
382530
383105
|
if (error instanceof ModelCompilationError || error instanceof MalloyError16) {
|
|
382531
383106
|
return "compilation_error";
|
|
@@ -382538,7 +383113,7 @@ function packageLoadFailureStatus(error) {
|
|
|
382538
383113
|
}
|
|
382539
383114
|
return "error";
|
|
382540
383115
|
}
|
|
382541
|
-
var COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
|
|
383116
|
+
var MODEL_RECOMPILE_FAILED = "model-recompile-failed", COMPUTED_PACKAGE_FIELDS, JOIN_BYPASS_NOTE, Package;
|
|
382542
383117
|
var init_package2 = __esm(() => {
|
|
382543
383118
|
init_materialization();
|
|
382544
383119
|
init_malloy_text();
|
|
@@ -382552,6 +383127,7 @@ var init_package2 = __esm(() => {
|
|
|
382552
383127
|
init_access_gates();
|
|
382553
383128
|
init_explore_walk();
|
|
382554
383129
|
init_package_load_pool();
|
|
383130
|
+
init_job_files();
|
|
382555
383131
|
init_package_manifest();
|
|
382556
383132
|
init_package_retrieval_settings();
|
|
382557
383133
|
init_constants();
|
|
@@ -382651,6 +383227,9 @@ var init_package2 = __esm(() => {
|
|
|
382651
383227
|
this.mz.plan.databaseSourceEligibility = eligibility;
|
|
382652
383228
|
}
|
|
382653
383229
|
renderTagWarnings = [];
|
|
383230
|
+
recompileFailedWarnings = [];
|
|
383231
|
+
keptModelStaleness;
|
|
383232
|
+
compiledFrom = new Map;
|
|
382654
383233
|
reloadedFor;
|
|
382655
383234
|
connectionEdits = 0;
|
|
382656
383235
|
entitiesWarnings = [];
|
|
@@ -382886,7 +383465,7 @@ var init_package2 = __esm(() => {
|
|
|
382886
383465
|
applySiblingModelResolverToModels() {
|
|
382887
383466
|
const byUrl = new Map;
|
|
382888
383467
|
for (const [modelPath, model] of this.models) {
|
|
382889
|
-
byUrl.set(
|
|
383468
|
+
byUrl.set(pathToFileURL24(path43.join(this.packagePath, modelPath)).toString(), model);
|
|
382890
383469
|
}
|
|
382891
383470
|
this.modelPolicy.setSiblingModelDefResolver((url) => byUrl.get(url)?.getModelDef());
|
|
382892
383471
|
}
|
|
@@ -383187,7 +383766,7 @@ var init_package2 = __esm(() => {
|
|
|
383187
383766
|
buildManifest
|
|
383188
383767
|
}, "throw", async (sm) => {
|
|
383189
383768
|
if (sm.modelPath.endsWith(MODEL_FILE_SUFFIX)) {
|
|
383190
|
-
const modelSource = await readPackageURL(packagePath,
|
|
383769
|
+
const modelSource = await readPackageURL(packagePath, pathToFileURL24(path43.join(packagePath, sm.modelPath)));
|
|
383191
383770
|
nameProblems.push(...persistNameProblems(modelSource, sm.modelPath));
|
|
383192
383771
|
}
|
|
383193
383772
|
}));
|
|
@@ -383200,6 +383779,7 @@ var init_package2 = __esm(() => {
|
|
|
383200
383779
|
const executionTime = performance.now() - startTime;
|
|
383201
383780
|
const pkg = new Package(environmentName, packageName, packagePath, packageConfig, databases, models, malloyConfig, modelPolicy);
|
|
383202
383781
|
pkg.dryRun = dryRun;
|
|
383782
|
+
pkg.compiledFrom = pkg.compiledFromOf(models, outcome.fileDigests);
|
|
383203
383783
|
pkg.refreshesUpstreamSchemas = refreshSchemas;
|
|
383204
383784
|
pkg.persistNameProblems = nameProblems;
|
|
383205
383785
|
let reportTimings;
|
|
@@ -383484,7 +384064,7 @@ var init_package2 = __esm(() => {
|
|
|
383484
384064
|
for (const [modelPath, model] of this.models) {
|
|
383485
384065
|
if (!modelPath.endsWith(MODEL_FILE_SUFFIX))
|
|
383486
384066
|
continue;
|
|
383487
|
-
const absolutePath =
|
|
384067
|
+
const absolutePath = path43.join(this.packagePath, modelPath);
|
|
383488
384068
|
const modelDef = model.getModelDef();
|
|
383489
384069
|
const compilationError = model.getCompilationError();
|
|
383490
384070
|
if (compilationError !== undefined || modelDef === undefined) {
|
|
@@ -383499,7 +384079,7 @@ var init_package2 = __esm(() => {
|
|
|
383499
384079
|
relativePath: modelPath,
|
|
383500
384080
|
absolutePath,
|
|
383501
384081
|
model: new MalloyModel(modelDef, [], []),
|
|
383502
|
-
text: model.getCompiledSourceText() ?? await readPackageURL(this.packagePath,
|
|
384082
|
+
text: model.getCompiledSourceText() ?? await readPackageURL(this.packagePath, pathToFileURL24(absolutePath))
|
|
383503
384083
|
});
|
|
383504
384084
|
}
|
|
383505
384085
|
return modelFiles;
|
|
@@ -383568,6 +384148,7 @@ var init_package2 = __esm(() => {
|
|
|
383568
384148
|
}
|
|
383569
384149
|
const allWarnings = [
|
|
383570
384150
|
...this.renderTagWarnings,
|
|
384151
|
+
...this.recompileFailedWarnings,
|
|
383571
384152
|
...this.entitiesWarnings,
|
|
383572
384153
|
...this.readerWarnings,
|
|
383573
384154
|
...this.reportWarnings,
|
|
@@ -384055,11 +384636,33 @@ var init_package2 = __esm(() => {
|
|
|
384055
384636
|
buildManifest,
|
|
384056
384637
|
modelPolicy: nextModelPolicy
|
|
384057
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: [] };
|
|
384058
384647
|
const discoveryStarted = performance.now();
|
|
384059
384648
|
const discovery = await this.discoverReportsIn(nextModels, "reload");
|
|
384060
384649
|
const discoveryMs = performance.now() - discoveryStarted;
|
|
384061
384650
|
this.models = nextModels;
|
|
384651
|
+
this.modelPolicy.handOffTo(nextModelPolicy);
|
|
384062
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;
|
|
384063
384666
|
this.adoptOutcomeMetadata(outcome);
|
|
384064
384667
|
this.refreshServingIdentity();
|
|
384065
384668
|
const previousSurface = this.packageMetadata.explores;
|
|
@@ -384092,6 +384695,52 @@ var init_package2 = __esm(() => {
|
|
|
384092
384695
|
this.logEmptyDiscoveryWarnings();
|
|
384093
384696
|
return true;
|
|
384094
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
|
+
}
|
|
384095
384744
|
static compileKeyOf(entries) {
|
|
384096
384745
|
return JSON.stringify(Object.keys(entries).sort().map((id) => [
|
|
384097
384746
|
id,
|
|
@@ -384172,7 +384821,7 @@ var init_package2 = __esm(() => {
|
|
|
384172
384821
|
}
|
|
384173
384822
|
async readModelText(model, modelPath) {
|
|
384174
384823
|
try {
|
|
384175
|
-
return model.getCompiledSourceText() ?? await readPackageURL(this.packagePath,
|
|
384824
|
+
return model.getCompiledSourceText() ?? await readPackageURL(this.packagePath, pathToFileURL24(safeJoinUnderRoot(this.packagePath, modelPath)));
|
|
384176
384825
|
} catch {
|
|
384177
384826
|
return;
|
|
384178
384827
|
}
|
|
@@ -384180,7 +384829,7 @@ var init_package2 = __esm(() => {
|
|
|
384180
384829
|
modelPathsByImportUrl() {
|
|
384181
384830
|
const byUrl = new Map;
|
|
384182
384831
|
for (const modelPath of this.models.keys()) {
|
|
384183
|
-
byUrl.set(
|
|
384832
|
+
byUrl.set(pathToFileURL24(path43.join(this.packagePath, modelPath)).toString(), modelPath);
|
|
384184
384833
|
}
|
|
384185
384834
|
return byUrl;
|
|
384186
384835
|
}
|
|
@@ -384777,7 +385426,7 @@ var init_package2 = __esm(() => {
|
|
|
384777
385426
|
}
|
|
384778
385427
|
let real;
|
|
384779
385428
|
try {
|
|
384780
|
-
real = await confinedPackagePath(packagePath,
|
|
385429
|
+
real = await confinedPackagePath(packagePath, pathToFileURL24(packageConfigPath));
|
|
384781
385430
|
} catch {
|
|
384782
385431
|
throw notThere();
|
|
384783
385432
|
}
|
|
@@ -384826,9 +385475,9 @@ var init_package2 = __esm(() => {
|
|
|
384826
385475
|
static async getDatabasePaths(packagePath) {
|
|
384827
385476
|
const files = await listPackageTree(packagePath);
|
|
384828
385477
|
const candidates = files.map((fullPath) => {
|
|
384829
|
-
return
|
|
385478
|
+
return path43.relative(packagePath, fullPath).replace(/\\/g, "/");
|
|
384830
385479
|
}).filter((modelPath) => {
|
|
384831
|
-
if (
|
|
385480
|
+
if (path43.basename(modelPath).startsWith("~$")) {
|
|
384832
385481
|
return false;
|
|
384833
385482
|
}
|
|
384834
385483
|
return modelPath.endsWith(".parquet") || modelPath.endsWith(".csv") || modelPath.endsWith(".xlsx");
|
|
@@ -384836,7 +385485,7 @@ var init_package2 = __esm(() => {
|
|
|
384836
385485
|
const probed = [];
|
|
384837
385486
|
for (const relativePath of candidates) {
|
|
384838
385487
|
try {
|
|
384839
|
-
const real = await confinedPackagePath(packagePath,
|
|
385488
|
+
const real = await confinedPackagePath(packagePath, pathToFileURL24(path43.join(packagePath, relativePath)));
|
|
384840
385489
|
if ((await fs20.stat(real)).isFile())
|
|
384841
385490
|
probed.push(relativePath);
|
|
384842
385491
|
} catch {}
|
|
@@ -384844,7 +385493,7 @@ var init_package2 = __esm(() => {
|
|
|
384844
385493
|
return probed;
|
|
384845
385494
|
}
|
|
384846
385495
|
static async getDatabaseInfo(packagePath, databasePath, conn) {
|
|
384847
|
-
const fullPath =
|
|
385496
|
+
const fullPath = path43.join(packagePath, databasePath);
|
|
384848
385497
|
const runtime = new ConnectionRuntime({
|
|
384849
385498
|
urlReader: new EmptyURLReader,
|
|
384850
385499
|
connections: [conn]
|
|
@@ -385444,9 +386093,9 @@ var init_compile_document = __esm(() => {
|
|
|
385444
386093
|
// src/service/compile_source.ts
|
|
385445
386094
|
import { MalloyError as MalloyError18, Runtime as Runtime3 } from "@malloydata/malloy";
|
|
385446
386095
|
import * as fs21 from "fs";
|
|
385447
|
-
import * as
|
|
385448
|
-
import { fileURLToPath as
|
|
385449
|
-
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) {
|
|
385450
386099
|
const rel = pathModule.relative(packagePath, filePath);
|
|
385451
386100
|
if (rel === "" || rel.startsWith("..") || pathModule.isAbsolute(rel)) {
|
|
385452
386101
|
return;
|
|
@@ -385561,8 +386210,8 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385561
386210
|
const source = request.source ?? (scope === "file" ? overlaidText(overlay, modelName) : undefined);
|
|
385562
386211
|
const packagePath = versioned ? versioned.getPackagePath() : safeJoinUnderRoot(host.environmentPath, packageName);
|
|
385563
386212
|
const modelPath = safeJoinUnderRoot(packagePath, modelName);
|
|
385564
|
-
const modelDir =
|
|
385565
|
-
const virtualUrl = scope === "append" ?
|
|
386213
|
+
const modelDir = path44.dirname(modelPath);
|
|
386214
|
+
const virtualUrl = scope === "append" ? pathToFileURL25(path44.join(modelDir, "__compile_check.malloy")) : pathToFileURL25(modelPath);
|
|
385566
386215
|
const virtualUri = virtualUrl.toString();
|
|
385567
386216
|
const { fullSource, callerRegion } = scope === "append" ? await appendToSavedModel(packagePath, modelPath, source, virtualUri) : { fullSource: source ?? "", callerRegion: undefined };
|
|
385568
386217
|
const substitute = scope !== "package" || source !== undefined;
|
|
@@ -385602,7 +386251,7 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385602
386251
|
let model;
|
|
385603
386252
|
if (url && url.startsWith("file:")) {
|
|
385604
386253
|
try {
|
|
385605
|
-
model = packageRelativeModelPath(packagePath,
|
|
386254
|
+
model = packageRelativeModelPath(packagePath, fileURLToPath22(url));
|
|
385606
386255
|
} catch {}
|
|
385607
386256
|
}
|
|
385608
386257
|
if (scope === "append" && url === virtualUri) {
|
|
@@ -385633,7 +386282,7 @@ async function openCompileContext(host, request, versioned) {
|
|
|
385633
386282
|
async function appendToSavedModel(packagePath, modelPath, source, virtualUri) {
|
|
385634
386283
|
let modelContent = "";
|
|
385635
386284
|
try {
|
|
385636
|
-
modelContent = await readPackageURL(packagePath,
|
|
386285
|
+
modelContent = await readPackageURL(packagePath, pathToFileURL25(modelPath));
|
|
385637
386286
|
} catch {}
|
|
385638
386287
|
const fullSource = modelContent ? `${modelContent}
|
|
385639
386288
|
${source}` : source ?? "";
|
|
@@ -385789,7 +386438,7 @@ async function compileAppend(ctx) {
|
|
|
385789
386438
|
async function loadAppendBase(ctx) {
|
|
385790
386439
|
const { runtime, modelPath, modelName, environmentName } = ctx;
|
|
385791
386440
|
try {
|
|
385792
|
-
const appendBase = runtime.loadModel(
|
|
386441
|
+
const appendBase = runtime.loadModel(pathToFileURL25(modelPath));
|
|
385793
386442
|
const baseModel = await appendBase.getModel();
|
|
385794
386443
|
return { appendBase, baseModel };
|
|
385795
386444
|
} catch (error) {
|
|
@@ -385951,7 +386600,7 @@ async function compilePackageDryRun(ctx) {
|
|
|
385951
386600
|
if (compiled.problems) {
|
|
385952
386601
|
collect(compiled.problems, compiled.modelPath);
|
|
385953
386602
|
}
|
|
385954
|
-
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;
|
|
385955
386604
|
if (readerProblem)
|
|
385956
386605
|
collect([readerProblem], compiled.modelPath);
|
|
385957
386606
|
if (compiled.compilationError) {
|
|
@@ -385967,11 +386616,11 @@ async function compilePackageDryRun(ctx) {
|
|
|
385967
386616
|
], compiled.modelPath);
|
|
385968
386617
|
}
|
|
385969
386618
|
}
|
|
385970
|
-
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(() => {
|
|
385971
386620
|
return;
|
|
385972
386621
|
}));
|
|
385973
386622
|
if (lintText !== undefined) {
|
|
385974
|
-
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);
|
|
385975
386624
|
}
|
|
385976
386625
|
}
|
|
385977
386626
|
for (const warning of renderTagWarnings) {
|
|
@@ -386241,7 +386890,7 @@ var init_status_snapshot = __esm(() => {
|
|
|
386241
386890
|
// src/service/versions/package_content_hash.ts
|
|
386242
386891
|
import * as crypto4 from "crypto";
|
|
386243
386892
|
import * as fs22 from "fs";
|
|
386244
|
-
import * as
|
|
386893
|
+
import * as path45 from "path";
|
|
386245
386894
|
async function hashPackageTree(root) {
|
|
386246
386895
|
const hash = crypto4.createHash("sha256");
|
|
386247
386896
|
const entries = await listEntries(root, "");
|
|
@@ -386283,7 +386932,7 @@ async function hashPackageTree(root) {
|
|
|
386283
386932
|
return hash.digest("hex");
|
|
386284
386933
|
}
|
|
386285
386934
|
async function readEntry(root, entry) {
|
|
386286
|
-
const absolute =
|
|
386935
|
+
const absolute = path45.join(root, ...entry.relative.split("/"));
|
|
386287
386936
|
if (entry.kind === "dir")
|
|
386288
386937
|
return { kind: "dir" };
|
|
386289
386938
|
if (entry.kind === "link") {
|
|
@@ -386296,7 +386945,7 @@ async function readEntry(root, entry) {
|
|
|
386296
386945
|
return { kind: "file", absolute, size: bytes.length, bytes };
|
|
386297
386946
|
}
|
|
386298
386947
|
async function listEntries(root, prefix) {
|
|
386299
|
-
const directory = prefix === "" ? root :
|
|
386948
|
+
const directory = prefix === "" ? root : path45.join(root, ...prefix.split("/"));
|
|
386300
386949
|
const dirents = await fs22.promises.readdir(directory, {
|
|
386301
386950
|
withFileTypes: true
|
|
386302
386951
|
});
|
|
@@ -386325,8 +386974,8 @@ var init_package_content_hash = __esm(() => {
|
|
|
386325
386974
|
// src/service/versions/version_store.ts
|
|
386326
386975
|
import * as crypto5 from "crypto";
|
|
386327
386976
|
import * as fs23 from "fs";
|
|
386328
|
-
import * as
|
|
386329
|
-
import { pathToFileURL as
|
|
386977
|
+
import * as path46 from "path";
|
|
386978
|
+
import { pathToFileURL as pathToFileURL26 } from "url";
|
|
386330
386979
|
|
|
386331
386980
|
class VersionStore {
|
|
386332
386981
|
environmentPath;
|
|
@@ -386342,7 +386991,7 @@ class VersionStore {
|
|
|
386342
386991
|
async stage(packageName, downloader) {
|
|
386343
386992
|
assertSafePackageName(packageName);
|
|
386344
386993
|
const stagingPath = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
386345
|
-
await fs23.promises.mkdir(
|
|
386994
|
+
await fs23.promises.mkdir(path46.dirname(stagingPath), { recursive: true });
|
|
386346
386995
|
try {
|
|
386347
386996
|
await downloader(stagingPath);
|
|
386348
386997
|
const manifest = await readManifestVersion(stagingPath);
|
|
@@ -386364,8 +387013,8 @@ class VersionStore {
|
|
|
386364
387013
|
}
|
|
386365
387014
|
within(area, candidate) {
|
|
386366
387015
|
const root = safeJoinUnderRoot(this.environmentPath, area);
|
|
386367
|
-
const resolved =
|
|
386368
|
-
if (!resolved.startsWith(root +
|
|
387016
|
+
const resolved = path46.resolve(candidate);
|
|
387017
|
+
if (!resolved.startsWith(root + path46.sep)) {
|
|
386369
387018
|
throw new Error(`Not a path under ${area}: ${JSON.stringify(candidate)}`);
|
|
386370
387019
|
}
|
|
386371
387020
|
return resolved;
|
|
@@ -386376,7 +387025,7 @@ class VersionStore {
|
|
|
386376
387025
|
await this.discard(staged);
|
|
386377
387026
|
return false;
|
|
386378
387027
|
}
|
|
386379
|
-
await fs23.promises.mkdir(
|
|
387028
|
+
await fs23.promises.mkdir(path46.dirname(target), { recursive: true });
|
|
386380
387029
|
await fs23.promises.rename(this.within(STAGING_DIR_NAME, staged.stagingPath), target);
|
|
386381
387030
|
return true;
|
|
386382
387031
|
}
|
|
@@ -386422,7 +387071,7 @@ class VersionStore {
|
|
|
386422
387071
|
if (!await exists(packagePath))
|
|
386423
387072
|
return null;
|
|
386424
387073
|
const heldPath = safeJoinUnderRoot(this.environmentPath, LEGACY_DIR_NAME, `${packageName}-${crypto5.randomUUID()}`);
|
|
386425
|
-
await fs23.promises.mkdir(
|
|
387074
|
+
await fs23.promises.mkdir(path46.dirname(heldPath), { recursive: true });
|
|
386426
387075
|
await fs23.promises.rename(packagePath, heldPath);
|
|
386427
387076
|
return { packageName, heldPath };
|
|
386428
387077
|
}
|
|
@@ -386433,7 +387082,7 @@ class VersionStore {
|
|
|
386433
387082
|
let leftover = null;
|
|
386434
387083
|
if (await exists(packagePath)) {
|
|
386435
387084
|
leftover = safeJoinUnderRoot(this.environmentPath, STAGING_DIR_NAME, `${held.packageName}-${crypto5.randomUUID()}`);
|
|
386436
|
-
await fs23.promises.mkdir(
|
|
387085
|
+
await fs23.promises.mkdir(path46.dirname(leftover), { recursive: true });
|
|
386437
387086
|
await fs23.promises.rename(packagePath, leftover);
|
|
386438
387087
|
}
|
|
386439
387088
|
try {
|
|
@@ -386526,10 +387175,10 @@ class VersionStore {
|
|
|
386526
387175
|
}
|
|
386527
387176
|
}
|
|
386528
387177
|
async function readManifestVersion(packagePath) {
|
|
386529
|
-
const manifestPath =
|
|
387178
|
+
const manifestPath = path46.join(packagePath, PACKAGE_MANIFEST_NAME);
|
|
386530
387179
|
let text;
|
|
386531
387180
|
try {
|
|
386532
|
-
text = await readPackageURL(packagePath,
|
|
387181
|
+
text = await readPackageURL(packagePath, pathToFileURL26(manifestPath));
|
|
386533
387182
|
} catch {
|
|
386534
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.`);
|
|
386535
387184
|
}
|
|
@@ -386579,9 +387228,9 @@ var init_version_store = __esm(() => {
|
|
|
386579
387228
|
import { AsyncLocalStorage as AsyncLocalStorage8 } from "async_hooks";
|
|
386580
387229
|
import crypto6 from "crypto";
|
|
386581
387230
|
import * as fs24 from "fs";
|
|
386582
|
-
import * as
|
|
387231
|
+
import * as path47 from "path";
|
|
386583
387232
|
import { isDeepStrictEqual } from "util";
|
|
386584
|
-
import { pathToFileURL as
|
|
387233
|
+
import { pathToFileURL as pathToFileURL27 } from "url";
|
|
386585
387234
|
function mergePackageManifest(existingManifest, metadata) {
|
|
386586
387235
|
const onDiskMaterialization = existingManifest.materialization !== null && typeof existingManifest.materialization === "object" && !Array.isArray(existingManifest.materialization) ? existingManifest.materialization : undefined;
|
|
386587
387236
|
const resolvedScope = metadata.scope ?? onDiskMaterialization?.scope ?? existingManifest.scope;
|
|
@@ -386783,7 +387432,7 @@ var init_environment = __esm(() => {
|
|
|
386783
387432
|
async writeEnvironmentReadme(readme) {
|
|
386784
387433
|
if (readme === undefined)
|
|
386785
387434
|
return;
|
|
386786
|
-
const readmePath =
|
|
387435
|
+
const readmePath = path47.join(this.environmentPath, "README.md");
|
|
386787
387436
|
try {
|
|
386788
387437
|
await fs24.promises.writeFile(readmePath, readme, "utf-8");
|
|
386789
387438
|
logger.info(`Updated README.md for environment ${this.environmentName}`);
|
|
@@ -387056,7 +387705,7 @@ var init_environment = __esm(() => {
|
|
|
387056
387705
|
const connections = this.lastChangedConnections;
|
|
387057
387706
|
next.refreshBuildPlan({
|
|
387058
387707
|
retryFailed,
|
|
387059
|
-
isStale: () => next.getVersionId() === undefined && this.
|
|
387708
|
+
isStale: () => next.getVersionId() === undefined && this.getRefusedReloads().has(next.getPackageName())
|
|
387060
387709
|
}).then((derived) => {
|
|
387061
387710
|
if (derived) {
|
|
387062
387711
|
const backoff = this.planRefreshBackoff.get(next);
|
|
@@ -387391,14 +388040,14 @@ var init_environment = __esm(() => {
|
|
|
387391
388040
|
if (await isLink(target))
|
|
387392
388041
|
throw outside();
|
|
387393
388042
|
try {
|
|
387394
|
-
await confinedPackagePath(packageRoot,
|
|
388043
|
+
await confinedPackagePath(packageRoot, pathToFileURL27(target));
|
|
387395
388044
|
} catch (error) {
|
|
387396
388045
|
if (error instanceof ImportOutsidePackageError)
|
|
387397
388046
|
throw outside();
|
|
387398
388047
|
throw error;
|
|
387399
388048
|
}
|
|
387400
388049
|
const missing = [];
|
|
387401
|
-
let dir =
|
|
388050
|
+
let dir = path47.dirname(target);
|
|
387402
388051
|
while (dir.startsWith(packageRoot)) {
|
|
387403
388052
|
const stat = await fs24.promises.stat(dir).catch((error) => {
|
|
387404
388053
|
const code = error.code;
|
|
@@ -387410,11 +388059,11 @@ var init_environment = __esm(() => {
|
|
|
387410
388059
|
if (await isLink(dir))
|
|
387411
388060
|
throw outside();
|
|
387412
388061
|
missing.push(dir);
|
|
387413
|
-
dir =
|
|
388062
|
+
dir = path47.dirname(dir);
|
|
387414
388063
|
continue;
|
|
387415
388064
|
}
|
|
387416
388065
|
if (!stat.isDirectory())
|
|
387417
|
-
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.`);
|
|
387418
388067
|
break;
|
|
387419
388068
|
}
|
|
387420
388069
|
const [realRoot, realExisting, realTarget] = await Promise.all([
|
|
@@ -387429,10 +388078,10 @@ var init_environment = __esm(() => {
|
|
|
387429
388078
|
for (const real of [realExisting, realTarget]) {
|
|
387430
388079
|
if (real === undefined)
|
|
387431
388080
|
continue;
|
|
387432
|
-
if (real !== realRoot && !real.startsWith(`${realRoot}${
|
|
388081
|
+
if (real !== realRoot && !real.startsWith(`${realRoot}${path47.sep}`)) {
|
|
387433
388082
|
throw new InvalidModelPathError(`Invalid model path: it resolves outside the package.`);
|
|
387434
388083
|
}
|
|
387435
|
-
if (isUnderPublicDir(
|
|
388084
|
+
if (isUnderPublicDir(path47.relative(realRoot, real).split(path47.sep).join("/"))) {
|
|
387436
388085
|
throw new InvalidModelPathError(`Invalid model path: it resolves into \`public/\`, which is served ` + `as raw static files.`);
|
|
387437
388086
|
}
|
|
387438
388087
|
}
|
|
@@ -387542,7 +388191,7 @@ var init_environment = __esm(() => {
|
|
|
387542
388191
|
const dir = safeJoinUnderRoot(environmentPath, dirName);
|
|
387543
388192
|
if (dir.indexOf("..") !== -1)
|
|
387544
388193
|
continue;
|
|
387545
|
-
if (
|
|
388194
|
+
if (path47.basename(dir) !== dirName)
|
|
387546
388195
|
continue;
|
|
387547
388196
|
try {
|
|
387548
388197
|
await fs24.promises.rm(dir, { recursive: true, force: true });
|
|
@@ -388551,7 +389200,7 @@ var init_environment = __esm(() => {
|
|
|
388551
389200
|
}
|
|
388552
389201
|
async stageDownload(packageName, downloader) {
|
|
388553
389202
|
const stagingPath = this.allocateStagingPath(packageName);
|
|
388554
|
-
await fs24.promises.mkdir(
|
|
389203
|
+
await fs24.promises.mkdir(path47.dirname(stagingPath), { recursive: true });
|
|
388555
389204
|
logger.debug("install.phase1.download.started", {
|
|
388556
389205
|
environmentName: this.environmentName,
|
|
388557
389206
|
packageName,
|
|
@@ -388619,7 +389268,7 @@ var init_environment = __esm(() => {
|
|
|
388619
389268
|
const oldExistsOnDisk = await fs24.promises.access(canonicalPath).then(() => true).catch(() => false);
|
|
388620
389269
|
if (oldExistsOnDisk) {
|
|
388621
389270
|
retiredPath = this.allocateRetiredPath(packageName);
|
|
388622
|
-
await fs24.promises.mkdir(
|
|
389271
|
+
await fs24.promises.mkdir(path47.dirname(retiredPath), {
|
|
388623
389272
|
recursive: true
|
|
388624
389273
|
});
|
|
388625
389274
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -388978,7 +389627,7 @@ var init_environment = __esm(() => {
|
|
|
388978
389627
|
const packagePath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
388979
389628
|
const manifestPath = safeJoinUnderRoot(packagePath, "publisher.json");
|
|
388980
389629
|
try {
|
|
388981
|
-
await confinedPackagePath(packagePath,
|
|
389630
|
+
await confinedPackagePath(packagePath, pathToFileURL27(manifestPath));
|
|
388982
389631
|
} catch (error) {
|
|
388983
389632
|
if (!(error instanceof ImportOutsidePackageError))
|
|
388984
389633
|
throw error;
|
|
@@ -388988,7 +389637,7 @@ var init_environment = __esm(() => {
|
|
|
388988
389637
|
let existingManifest = {};
|
|
388989
389638
|
let existingRead = false;
|
|
388990
389639
|
try {
|
|
388991
|
-
existingManifest = JSON.parse(await readPackageURL(packagePath,
|
|
389640
|
+
existingManifest = JSON.parse(await readPackageURL(packagePath, pathToFileURL27(manifestPath)));
|
|
388992
389641
|
existingRead = true;
|
|
388993
389642
|
} catch (_err) {
|
|
388994
389643
|
logger.warn(`Could not read manifest for ${packageName}`);
|
|
@@ -388996,7 +389645,7 @@ var init_environment = __esm(() => {
|
|
|
388996
389645
|
const updatedManifest = mergePackageManifest(existingManifest, metadata);
|
|
388997
389646
|
if (metadata.location !== undefined && metadata.location !== "") {
|
|
388998
389647
|
const recordPath = this.installRecordPath(packageName);
|
|
388999
|
-
await fs24.promises.mkdir(
|
|
389648
|
+
await fs24.promises.mkdir(path47.dirname(recordPath), {
|
|
389000
389649
|
recursive: true
|
|
389001
389650
|
});
|
|
389002
389651
|
await fs24.promises.writeFile(recordPath, JSON.stringify({ location: metadata.location }, null, 2), "utf-8");
|
|
@@ -389006,7 +389655,7 @@ var init_environment = __esm(() => {
|
|
|
389006
389655
|
if (error.code !== "ENOENT")
|
|
389007
389656
|
throw error;
|
|
389008
389657
|
});
|
|
389009
|
-
const temporary =
|
|
389658
|
+
const temporary = path47.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
389010
389659
|
try {
|
|
389011
389660
|
await fs24.promises.writeFile(temporary, JSON.stringify(updatedManifest, null, 2), { encoding: "utf-8", flag: "wx" });
|
|
389012
389661
|
await fs24.promises.rename(temporary, manifestPath);
|
|
@@ -389034,7 +389683,7 @@ var init_environment = __esm(() => {
|
|
|
389034
389683
|
async restorePackageManifestFile(packageName, text) {
|
|
389035
389684
|
const packagePath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
389036
389685
|
const manifestPath = safeJoinUnderRoot(packagePath, "publisher.json");
|
|
389037
|
-
const temporary =
|
|
389686
|
+
const temporary = path47.join(packagePath, `.publisher.json.${crypto6.randomUUID()}.tmp`);
|
|
389038
389687
|
try {
|
|
389039
389688
|
if (text === null) {
|
|
389040
389689
|
await fs24.promises.rm(manifestPath, { force: true });
|
|
@@ -389264,6 +389913,15 @@ var init_environment = __esm(() => {
|
|
|
389264
389913
|
return this.lifecycle.failures();
|
|
389265
389914
|
}
|
|
389266
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() {
|
|
389267
389925
|
return this.lifecycle.staleRecords();
|
|
389268
389926
|
}
|
|
389269
389927
|
transition(packageName, event) {
|
|
@@ -389338,7 +389996,7 @@ var init_environment = __esm(() => {
|
|
|
389338
389996
|
const canonicalPath = safeJoinUnderRoot(this.environmentPath, packageName);
|
|
389339
389997
|
const retiredPath = this.allocateRetiredPath(packageName);
|
|
389340
389998
|
try {
|
|
389341
|
-
await fs24.promises.mkdir(
|
|
389999
|
+
await fs24.promises.mkdir(path47.dirname(retiredPath), {
|
|
389342
390000
|
recursive: true
|
|
389343
390001
|
});
|
|
389344
390002
|
await fs24.promises.rename(canonicalPath, retiredPath);
|
|
@@ -389469,7 +390127,7 @@ var init_environment = __esm(() => {
|
|
|
389469
390127
|
};
|
|
389470
390128
|
}
|
|
389471
390129
|
async deleteDuckDBConnection(connectionName) {
|
|
389472
|
-
const duckdbPath =
|
|
390130
|
+
const duckdbPath = path47.join(this.environmentPath, `${connectionName}.duckdb`);
|
|
389473
390131
|
try {
|
|
389474
390132
|
await fs24.promises.rm(duckdbPath, { force: true });
|
|
389475
390133
|
logger.info(`Removed DuckDB connection file ${connectionName} from environment ${this.environmentName}`);
|
|
@@ -395669,12 +396327,12 @@ var require_extract_zip = __commonJS(function(exports, module) {
|
|
|
395669
396327
|
|
|
395670
396328
|
// src/service/package_sources/zip.ts
|
|
395671
396329
|
import * as fs26 from "fs";
|
|
395672
|
-
import * as
|
|
396330
|
+
import * as path48 from "path";
|
|
395673
396331
|
async function unzipEnvironment(absoluteEnvironmentPath) {
|
|
395674
396332
|
assertSafeEnvironmentPath(absoluteEnvironmentPath);
|
|
395675
|
-
const archiveDir =
|
|
395676
|
-
const unzippedEnvironmentPath =
|
|
395677
|
-
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)) {
|
|
395678
396336
|
throw new BadRequestError(`Refusing to unzip "${absoluteEnvironmentPath}": target escapes its directory`);
|
|
395679
396337
|
}
|
|
395680
396338
|
await extractZipInto(absoluteEnvironmentPath, unzippedEnvironmentPath);
|
|
@@ -395692,7 +396350,7 @@ async function extractZipInto(archivePath, targetDir) {
|
|
|
395692
396350
|
let totalUncompressedBytes = 0;
|
|
395693
396351
|
try {
|
|
395694
396352
|
await import_extract_zip.default(archivePath, {
|
|
395695
|
-
dir:
|
|
396353
|
+
dir: path48.resolve(targetDir),
|
|
395696
396354
|
onEntry: (entry) => {
|
|
395697
396355
|
if ((entry.externalFileAttributes >>> 16 & 61440) === 40960) {
|
|
395698
396356
|
throw new BadRequestError(`Refusing to unzip "${archivePath}": entry "${entry.fileName}" is a symbolic link`);
|
|
@@ -395721,7 +396379,7 @@ var init_zip = __esm(() => {
|
|
|
395721
396379
|
|
|
395722
396380
|
// src/service/package_sources/gcs_source.ts
|
|
395723
396381
|
import * as fs27 from "fs";
|
|
395724
|
-
import * as
|
|
396382
|
+
import * as path49 from "path";
|
|
395725
396383
|
function isGCSURL(location) {
|
|
395726
396384
|
return location.startsWith("gs://");
|
|
395727
396385
|
}
|
|
@@ -395759,7 +396417,7 @@ class GcsPackageSource {
|
|
|
395759
396417
|
if (file.name.endsWith("/")) {
|
|
395760
396418
|
return;
|
|
395761
396419
|
}
|
|
395762
|
-
await fs27.promises.mkdir(
|
|
396420
|
+
await fs27.promises.mkdir(path49.dirname(absoluteFilePath), {
|
|
395763
396421
|
recursive: true
|
|
395764
396422
|
});
|
|
395765
396423
|
return fs27.promises.writeFile(absoluteFilePath, await file.download());
|
|
@@ -396003,9 +396661,9 @@ var init_git_source = __esm(() => {
|
|
|
396003
396661
|
// src/service/package_sources/local_source.ts
|
|
396004
396662
|
import * as fs29 from "fs";
|
|
396005
396663
|
import * as os8 from "os";
|
|
396006
|
-
import * as
|
|
396664
|
+
import * as path50 from "path";
|
|
396007
396665
|
function isLocalPath(location) {
|
|
396008
|
-
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") ||
|
|
396666
|
+
return location.startsWith("./") || location.startsWith("../") || location.startsWith("~/") || location.startsWith("/") || path50.isAbsolute(location);
|
|
396009
396667
|
}
|
|
396010
396668
|
function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
396011
396669
|
let expanded = location;
|
|
@@ -396014,9 +396672,9 @@ function resolvePackageLocation(location, anchorDir, homeDir) {
|
|
|
396014
396672
|
if (!home) {
|
|
396015
396673
|
throw new Error(`Cannot expand "~" in location "${location}": home directory is not set`);
|
|
396016
396674
|
}
|
|
396017
|
-
expanded =
|
|
396675
|
+
expanded = path50.join(home, location.slice(2));
|
|
396018
396676
|
}
|
|
396019
|
-
return
|
|
396677
|
+
return path50.isAbsolute(expanded) ? expanded : path50.join(anchorDir, expanded);
|
|
396020
396678
|
}
|
|
396021
396679
|
|
|
396022
396680
|
class LocalPackageSource {
|
|
@@ -396054,7 +396712,7 @@ var init_local_source = __esm(() => {
|
|
|
396054
396712
|
|
|
396055
396713
|
// src/service/package_sources/s3_source.ts
|
|
396056
396714
|
import * as fs30 from "fs";
|
|
396057
|
-
import * as
|
|
396715
|
+
import * as path51 from "path";
|
|
396058
396716
|
import { Writable } from "stream";
|
|
396059
396717
|
function isS3URL(location) {
|
|
396060
396718
|
return location.startsWith("s3://");
|
|
@@ -396078,7 +396736,7 @@ class S3PackageSource {
|
|
|
396078
396736
|
const s3Client = this.client();
|
|
396079
396737
|
if (isCompressedFile) {
|
|
396080
396738
|
const zipFilePath = `${absoluteDirPath}.zip`;
|
|
396081
|
-
await fs30.promises.mkdir(
|
|
396739
|
+
await fs30.promises.mkdir(path51.dirname(zipFilePath), {
|
|
396082
396740
|
recursive: true
|
|
396083
396741
|
});
|
|
396084
396742
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -396113,7 +396771,7 @@ class S3PackageSource {
|
|
|
396113
396771
|
return;
|
|
396114
396772
|
}
|
|
396115
396773
|
const absoluteFilePath = safeJoinUnderRoot(absoluteDirPath, relativeFilePath);
|
|
396116
|
-
await fs30.promises.mkdir(
|
|
396774
|
+
await fs30.promises.mkdir(path51.dirname(absoluteFilePath), {
|
|
396117
396775
|
recursive: true
|
|
396118
396776
|
});
|
|
396119
396777
|
const command = new import_client_s33.GetObjectCommand({
|
|
@@ -396140,7 +396798,7 @@ var init_s3_source = __esm(() => {
|
|
|
396140
396798
|
|
|
396141
396799
|
// src/service/package_sources/index.ts
|
|
396142
396800
|
import { Storage as Storage2 } from "@google-cloud/storage";
|
|
396143
|
-
import * as
|
|
396801
|
+
import * as path52 from "path";
|
|
396144
396802
|
|
|
396145
396803
|
class PackageSources {
|
|
396146
396804
|
resolveLocalPath;
|
|
@@ -396207,7 +396865,7 @@ class PackageSources {
|
|
|
396207
396865
|
} else if (packageLocation.startsWith("s3://")) {
|
|
396208
396866
|
await this.s3.fetch(packageLocation, targetPath, opts);
|
|
396209
396867
|
}
|
|
396210
|
-
if (packageLocation.startsWith("/") ||
|
|
396868
|
+
if (packageLocation.startsWith("/") || path52.isAbsolute(packageLocation)) {
|
|
396211
396869
|
await this.local.fetch(packageLocation, targetPath, opts);
|
|
396212
396870
|
}
|
|
396213
396871
|
}
|
|
@@ -396231,7 +396889,7 @@ var init_package_sources = __esm(() => {
|
|
|
396231
396889
|
// src/service/environment_store.ts
|
|
396232
396890
|
import crypto7 from "crypto";
|
|
396233
396891
|
import * as fs31 from "fs";
|
|
396234
|
-
import * as
|
|
396892
|
+
import * as path53 from "path";
|
|
396235
396893
|
function codesField(message) {
|
|
396236
396894
|
const codes = codesOfLines(message);
|
|
396237
396895
|
return codes.length > 0 ? { codes } : {};
|
|
@@ -396338,7 +396996,7 @@ class EnvironmentStore {
|
|
|
396338
396996
|
const storageConfig = {
|
|
396339
396997
|
type: "duckdb",
|
|
396340
396998
|
duckdb: {
|
|
396341
|
-
path:
|
|
396999
|
+
path: path53.join(serverRootPath, "publisher.db")
|
|
396342
397000
|
}
|
|
396343
397001
|
};
|
|
396344
397002
|
this.storageManager = deps.storageManager ?? new StorageManager(storageConfig);
|
|
@@ -397020,7 +397678,7 @@ class EnvironmentStore {
|
|
|
397020
397678
|
const reInit = settings.get("initializeStorage");
|
|
397021
397679
|
await fs31.promises.mkdir(this.serverRootPath, { recursive: true });
|
|
397022
397680
|
if (reInit) {
|
|
397023
|
-
const uploadDocsPath =
|
|
397681
|
+
const uploadDocsPath = path53.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
397024
397682
|
logger.info(`Reinitialization mode: Cleaning up upload documents path ${uploadDocsPath}`);
|
|
397025
397683
|
try {
|
|
397026
397684
|
await fs31.promises.rm(uploadDocsPath, {
|
|
@@ -397037,7 +397695,7 @@ class EnvironmentStore {
|
|
|
397037
397695
|
} else {
|
|
397038
397696
|
logger.info(`Using existing publisher path`);
|
|
397039
397697
|
}
|
|
397040
|
-
const uploadDocsPath =
|
|
397698
|
+
const uploadDocsPath = path53.join(this.serverRootPath, PUBLISHER_DATA_DIR);
|
|
397041
397699
|
await fs31.promises.mkdir(uploadDocsPath, { recursive: true });
|
|
397042
397700
|
}
|
|
397043
397701
|
async listEnvironments(skipInitializationCheck = false, options = {}) {
|
|
@@ -397461,7 +398119,7 @@ class EnvironmentStore {
|
|
|
397461
398119
|
const isInPlace = this.inPlaceEnvs.has(environmentName) && isLocalPath(_package.location) && !isLocalArchive;
|
|
397462
398120
|
if (isInPlace) {
|
|
397463
398121
|
await clearMountTarget(absolutePackagePath);
|
|
397464
|
-
const absoluteSourcePath =
|
|
398122
|
+
const absoluteSourcePath = path53.resolve(sourcePath);
|
|
397465
398123
|
const linkType = process.platform === "win32" ? "junction" : "dir";
|
|
397466
398124
|
try {
|
|
397467
398125
|
await fs31.promises.symlink(absoluteSourcePath, absolutePackagePath, linkType);
|
|
@@ -397591,7 +398249,7 @@ var init_environment_store = __esm(() => {
|
|
|
397591
398249
|
|
|
397592
398250
|
// src/controller/watch-mode.controller.ts
|
|
397593
398251
|
import { EventEmitter as EventEmitter3 } from "events";
|
|
397594
|
-
import
|
|
398252
|
+
import path54 from "path";
|
|
397595
398253
|
|
|
397596
398254
|
class WatchModeController {
|
|
397597
398255
|
environmentStore;
|
|
@@ -397635,7 +398293,7 @@ class WatchModeController {
|
|
|
397635
398293
|
ignored: (filePath, stats) => {
|
|
397636
398294
|
if (!stats?.isFile())
|
|
397637
398295
|
return false;
|
|
397638
|
-
const ext =
|
|
398296
|
+
const ext = path54.extname(filePath).toLowerCase();
|
|
397639
398297
|
return !MODEL_EXTS.has(ext) && !ASSET_EXTS.has(ext);
|
|
397640
398298
|
},
|
|
397641
398299
|
ignoreInitial: true
|
|
@@ -397655,12 +398313,12 @@ class WatchModeController {
|
|
|
397655
398313
|
};
|
|
397656
398314
|
const onEvent = (kind) => async (filePath) => {
|
|
397657
398315
|
logger.info(`Watch ${kind}: ${filePath}; environment=${watchName}`);
|
|
397658
|
-
const rel =
|
|
397659
|
-
const segments = rel.split(
|
|
398316
|
+
const rel = path54.relative(this.watchingPath ?? "", filePath);
|
|
398317
|
+
const segments = rel.split(path54.sep);
|
|
397660
398318
|
const pkgName = segments.length > 1 && segments[0] && !segments[0].startsWith("..") ? segments[0] : null;
|
|
397661
398319
|
if (!pkgName)
|
|
397662
398320
|
return;
|
|
397663
|
-
const ext =
|
|
398321
|
+
const ext = path54.extname(filePath).toLowerCase();
|
|
397664
398322
|
if (MODEL_EXTS.has(ext)) {
|
|
397665
398323
|
const recompiled = await reloadPackage(pkgName);
|
|
397666
398324
|
if (!recompiled)
|
|
@@ -397733,7 +398391,7 @@ var init_watch_mode_controller = __esm(() => {
|
|
|
397733
398391
|
// src/mcp_config.ts
|
|
397734
398392
|
import * as fs32 from "fs";
|
|
397735
398393
|
import * as os9 from "os";
|
|
397736
|
-
import * as
|
|
398394
|
+
import * as path55 from "path";
|
|
397737
398395
|
function malloyServer(endpoint) {
|
|
397738
398396
|
return { type: "http", url: endpoint };
|
|
397739
398397
|
}
|
|
@@ -397756,11 +398414,11 @@ function mcpEndpoint(host, port) {
|
|
|
397756
398414
|
return `http://${host}:${port}/mcp`;
|
|
397757
398415
|
}
|
|
397758
398416
|
function findGitWorkTreeRoot(dir) {
|
|
397759
|
-
let current =
|
|
398417
|
+
let current = path55.resolve(dir);
|
|
397760
398418
|
for (;; ) {
|
|
397761
|
-
if (fs32.existsSync(
|
|
398419
|
+
if (fs32.existsSync(path55.join(current, ".git")))
|
|
397762
398420
|
return current;
|
|
397763
|
-
const parent =
|
|
398421
|
+
const parent = path55.dirname(current);
|
|
397764
398422
|
if (parent === current)
|
|
397765
398423
|
return;
|
|
397766
398424
|
current = parent;
|
|
@@ -397783,7 +398441,7 @@ function mcpConfigEnabled() {
|
|
|
397783
398441
|
}
|
|
397784
398442
|
function ensureMcpConfig(options) {
|
|
397785
398443
|
const { dir, endpoint, requestedPort, boundPort, homeDir } = options;
|
|
397786
|
-
const file =
|
|
398444
|
+
const file = path55.join(dir, MCP_CONFIG_FILENAME);
|
|
397787
398445
|
try {
|
|
397788
398446
|
const existing = (() => {
|
|
397789
398447
|
try {
|
|
@@ -397810,18 +398468,18 @@ function ensureMcpConfig(options) {
|
|
|
397810
398468
|
try {
|
|
397811
398469
|
return fs32.realpathSync(p);
|
|
397812
398470
|
} catch {
|
|
397813
|
-
return
|
|
398471
|
+
return path55.resolve(p);
|
|
397814
398472
|
}
|
|
397815
398473
|
};
|
|
397816
398474
|
if (realish(dir) === realish(homeDir ?? os9.homedir())) {
|
|
397817
398475
|
return { action: "skipped-home", dir, endpoint, staleConfig };
|
|
397818
398476
|
}
|
|
397819
|
-
if (
|
|
398477
|
+
if (path55.resolve(dir) === path55.parse(path55.resolve(dir)).root) {
|
|
397820
398478
|
return { action: "skipped-root", dir, endpoint, staleConfig };
|
|
397821
398479
|
}
|
|
397822
398480
|
const gitRoot = findGitWorkTreeRoot(dir);
|
|
397823
398481
|
if (gitRoot !== undefined) {
|
|
397824
|
-
const rootCandidate =
|
|
398482
|
+
const rootCandidate = path55.join(gitRoot, MCP_CONFIG_FILENAME);
|
|
397825
398483
|
return {
|
|
397826
398484
|
action: "skipped-git",
|
|
397827
398485
|
dir,
|
|
@@ -400334,7 +400992,7 @@ function scrubForEgress(text) {
|
|
|
400334
400992
|
var PROVIDER_FAILURE_COOLDOWN_MS = 60000;
|
|
400335
400993
|
|
|
400336
400994
|
// src/retrieval/index/schema_index.ts
|
|
400337
|
-
import { createHash as
|
|
400995
|
+
import { createHash as createHash20 } from "crypto";
|
|
400338
400996
|
function recordMembers(columns) {
|
|
400339
400997
|
const records = new Set(columns.filter((c) => isRecordColumnType(c.type)).map((c) => c.name));
|
|
400340
400998
|
const members = new Set;
|
|
@@ -400377,7 +401035,7 @@ function tableIndexText(entity) {
|
|
|
400377
401035
|
}
|
|
400378
401036
|
function schemaFingerprint(tables) {
|
|
400379
401037
|
const canonical = tables.map((t) => `${t.resource}\x00${t.columns.map((c) => `${c.name}:${c.type ?? ""}`).join(",")}`).sort().join("\x01");
|
|
400380
|
-
return
|
|
401038
|
+
return createHash20("sha256").update(canonical).digest("hex");
|
|
400381
401039
|
}
|
|
400382
401040
|
function rankLexically(tables, query, limit, cache) {
|
|
400383
401041
|
const sanitized = sanitizeLunrQuery(query);
|
|
@@ -400695,8 +401353,8 @@ var init_registry3 = __esm(() => {
|
|
|
400695
401353
|
});
|
|
400696
401354
|
|
|
400697
401355
|
// src/retrieval/model/package_entities.ts
|
|
400698
|
-
import
|
|
400699
|
-
import { fileURLToPath as
|
|
401356
|
+
import path56 from "path";
|
|
401357
|
+
import { fileURLToPath as fileURLToPath23 } from "url";
|
|
400700
401358
|
import { parseAnnotation as parseAnnotation3 } from "@malloydata/malloy-tag";
|
|
400701
401359
|
function truncateDoc(doc, max) {
|
|
400702
401360
|
if (doc.length <= max)
|
|
@@ -400795,7 +401453,7 @@ function makeSourceTextReader(pkg) {
|
|
|
400795
401453
|
let text;
|
|
400796
401454
|
try {
|
|
400797
401455
|
if (url.startsWith("file:") && packagePath) {
|
|
400798
|
-
const relative =
|
|
401456
|
+
const relative = path56.relative(packagePath, fileURLToPath23(url)).split(path56.sep).join("/");
|
|
400799
401457
|
text = relative && !relative.startsWith("..") ? pkg.getModel?.(relative)?.getCompiledSourceText?.() : undefined;
|
|
400800
401458
|
}
|
|
400801
401459
|
} catch {
|
|
@@ -401719,7 +402377,7 @@ var init_response2 = __esm(() => {
|
|
|
401719
402377
|
|
|
401720
402378
|
// src/retrieval/model/catalog.ts
|
|
401721
402379
|
import { isSourceDef as isSourceDef21 } from "@malloydata/malloy";
|
|
401722
|
-
import { createHash as
|
|
402380
|
+
import { createHash as createHash21 } from "crypto";
|
|
401723
402381
|
function byText(a, b) {
|
|
401724
402382
|
return a < b ? -1 : a > b ? 1 : 0;
|
|
401725
402383
|
}
|
|
@@ -402650,7 +403308,7 @@ function readDefinitionOf(modelDef, name) {
|
|
|
402650
403308
|
const kept = value.filter((v) => !isOtherNote(v));
|
|
402651
403309
|
return key === "fields" ? kept.map((f) => isTableColumn(f) ? { name: f.name } : f).sort((a, b) => compareFieldNames(a, b)) : kept;
|
|
402652
403310
|
});
|
|
402653
|
-
return
|
|
403311
|
+
return createHash21("sha256").update(text, "utf8").digest("hex");
|
|
402654
403312
|
}
|
|
402655
403313
|
function isSecureGiven(g) {
|
|
402656
403314
|
return (g.annotations ?? []).some((a) => /secure/i.test(a));
|
|
@@ -402822,7 +403480,7 @@ var init_catalog_store = __esm(() => {
|
|
|
402822
403480
|
});
|
|
402823
403481
|
|
|
402824
403482
|
// src/retrieval/llm/prompts/source_summary.ts
|
|
402825
|
-
import { createHash as
|
|
403483
|
+
import { createHash as createHash22 } from "crypto";
|
|
402826
403484
|
function undocumentedOneLine(sourceName) {
|
|
402827
403485
|
return `The \`${sourceName}\` source.`;
|
|
402828
403486
|
}
|
|
@@ -402842,7 +403500,7 @@ function renderSourceSummaryUserPrompt(input) {
|
|
|
402842
403500
|
`);
|
|
402843
403501
|
}
|
|
402844
403502
|
function sourceSummaryPromptHash(instructions) {
|
|
402845
|
-
return
|
|
403503
|
+
return createHash22("sha256").update(instructions).update("\x00").update(renderSourceSummaryUserPrompt({ source: "", doc: "", fields: "" })).digest("hex");
|
|
402846
403504
|
}
|
|
402847
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:
|
|
402848
403506
|
{"summary": "<prose>", "one_line_summary": "<one sentence>"}`;
|
|
@@ -403000,7 +403658,7 @@ var init_llm_calls = __esm(() => {
|
|
|
403000
403658
|
});
|
|
403001
403659
|
|
|
403002
403660
|
// src/retrieval/index/source_summaries.ts
|
|
403003
|
-
import { createHash as
|
|
403661
|
+
import { createHash as createHash23 } from "crypto";
|
|
403004
403662
|
function resolveSourceSummarySettings(pkg, chatSlot) {
|
|
403005
403663
|
const retrieval = pkg?.getRetrievalSettings?.() ?? DEFAULT_PACKAGE_RETRIEVAL;
|
|
403006
403664
|
if (sourceSummaryConfigOf(retrieval).enabled === false)
|
|
@@ -403197,7 +403855,7 @@ function boundedPrompt(name, doc, own, resolve, maxPromptChars) {
|
|
|
403197
403855
|
}
|
|
403198
403856
|
}
|
|
403199
403857
|
function sourceSummaryInputHash(input, settings) {
|
|
403200
|
-
return
|
|
403858
|
+
return createHash23("sha256").update(settings.promptHash).update("\x00").update(settings.modelId).update("\x00").update(input.prompt).digest("hex");
|
|
403201
403859
|
}
|
|
403202
403860
|
function currentSummaryHashes(entities, settings, hashesCache) {
|
|
403203
403861
|
const frozen = Object.isFrozen(entities);
|
|
@@ -403524,9 +404182,9 @@ var init_derived_text = __esm(() => {
|
|
|
403524
404182
|
});
|
|
403525
404183
|
|
|
403526
404184
|
// src/retrieval/llm/llm_cache.ts
|
|
403527
|
-
import { createHash as
|
|
404185
|
+
import { createHash as createHash24 } from "crypto";
|
|
403528
404186
|
function sha256(text) {
|
|
403529
|
-
return
|
|
404187
|
+
return createHash24("sha256").update(text).digest("hex");
|
|
403530
404188
|
}
|
|
403531
404189
|
async function generateCached(args) {
|
|
403532
404190
|
const { db, table, environmentName, packageName } = args;
|
|
@@ -404299,7 +404957,7 @@ var init_vectors = __esm(() => {
|
|
|
404299
404957
|
});
|
|
404300
404958
|
|
|
404301
404959
|
// src/retrieval/index/values_index.ts
|
|
404302
|
-
import { createHash as
|
|
404960
|
+
import { createHash as createHash25 } from "crypto";
|
|
404303
404961
|
function partitionKeyPart(raw, type) {
|
|
404304
404962
|
const v = Array.isArray(raw) && raw.length === 1 ? raw[0] : raw;
|
|
404305
404963
|
if (v === null || v === undefined || Array.isArray(v))
|
|
@@ -404830,14 +405488,14 @@ async function connectionsDigest(read) {
|
|
|
404830
405488
|
try {
|
|
404831
405489
|
const environment = await read.environmentStore.getEnvironment(parseEnvironmentName(read.environmentName));
|
|
404832
405490
|
const text = JSON.stringify(environment.listApiConnections(), (key, value) => key && CREDENTIAL_KEY.test(key) ? undefined : value);
|
|
404833
|
-
return
|
|
405491
|
+
return createHash25("sha256").update(text, "utf8").digest("hex");
|
|
404834
405492
|
} catch (error) {
|
|
404835
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) });
|
|
404836
405494
|
return `unknown-${Date.now()}`;
|
|
404837
405495
|
}
|
|
404838
405496
|
}
|
|
404839
405497
|
function readKeyOf(readDefinition, node, cap, partitionKey, connections) {
|
|
404840
|
-
return
|
|
405498
|
+
return createHash25("sha256").update(JSON.stringify([
|
|
404841
405499
|
readDefinition,
|
|
404842
405500
|
node.modelPaths[0],
|
|
404843
405501
|
node.source,
|
|
@@ -407112,7 +407770,7 @@ var init_judge2 = __esm(() => {
|
|
|
407112
407770
|
});
|
|
407113
407771
|
|
|
407114
407772
|
// src/retrieval/search/pages.ts
|
|
407115
|
-
import { createHash as
|
|
407773
|
+
import { createHash as createHash26 } from "node:crypto";
|
|
407116
407774
|
function pageAt(cards, offset, options) {
|
|
407117
407775
|
const room = options.maxChars - options.reserveChars;
|
|
407118
407776
|
let used = 2;
|
|
@@ -407204,7 +407862,7 @@ function resultKey(request) {
|
|
|
407204
407862
|
givens: request.givens ?? null,
|
|
407205
407863
|
filterParams: request.filterParams ?? null
|
|
407206
407864
|
};
|
|
407207
|
-
return
|
|
407865
|
+
return createHash26("sha256").update(canonicalJson2(normal)).digest("hex");
|
|
407208
407866
|
}
|
|
407209
407867
|
function canonicalJson2(value) {
|
|
407210
407868
|
if (Array.isArray(value)) {
|
|
@@ -441192,7 +441850,7 @@ var init_lossless_widening = __esm(() => {
|
|
|
441192
441850
|
});
|
|
441193
441851
|
|
|
441194
441852
|
// src/service/materialization/run/storage_table_load.ts
|
|
441195
|
-
import
|
|
441853
|
+
import path57 from "path";
|
|
441196
441854
|
function readerSql(uri, format, options = {}) {
|
|
441197
441855
|
const path = `'${escapeSQL(uri)}'`;
|
|
441198
441856
|
const args = [];
|
|
@@ -441241,8 +441899,8 @@ function assertUnderDataPath(uri, dataPath) {
|
|
|
441241
441899
|
throw outside();
|
|
441242
441900
|
}
|
|
441243
441901
|
if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(uri)) {
|
|
441244
|
-
const resolved =
|
|
441245
|
-
if (!resolved.startsWith(`${
|
|
441902
|
+
const resolved = path57.resolve(uri);
|
|
441903
|
+
if (!resolved.startsWith(`${path57.resolve(root)}${path57.sep}`)) {
|
|
441246
441904
|
throw outside();
|
|
441247
441905
|
}
|
|
441248
441906
|
}
|
|
@@ -441633,7 +442291,7 @@ function objectUnreadable(error, uris, byName = false) {
|
|
|
441633
442291
|
logInternalFailure("Load could not read an object", error, "warn");
|
|
441634
442292
|
const said = error.message.split(ECHOED_SQL)[0];
|
|
441635
442293
|
const object = uris.findIndex((uri) => said.includes(uri));
|
|
441636
|
-
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}]`]));
|
|
441637
442295
|
if (byName)
|
|
441638
442296
|
return new LoadRefusalError("OBJECT_UNREADABLE", words);
|
|
441639
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 });
|
|
@@ -441986,7 +442644,7 @@ var init_storage_table_load = __esm(() => {
|
|
|
441986
442644
|
});
|
|
441987
442645
|
|
|
441988
442646
|
// src/service/catalog_admin.ts
|
|
441989
|
-
import { createHash as
|
|
442647
|
+
import { createHash as createHash27, randomUUID as randomUUID6 } from "crypto";
|
|
441990
442648
|
async function withLoadSlot(fn) {
|
|
441991
442649
|
const slot = loadSlots.tryAcquire();
|
|
441992
442650
|
if (!slot) {
|
|
@@ -442848,7 +443506,7 @@ function idempotencyKeyDigest(key) {
|
|
|
442848
443506
|
if (key === "" || key.length > MAX_IDEMPOTENCY_KEY) {
|
|
442849
443507
|
throw badRequest(`'Idempotency-Key' must be 1 to ${MAX_IDEMPOTENCY_KEY} characters.`);
|
|
442850
443508
|
}
|
|
442851
|
-
return
|
|
443509
|
+
return createHash27("sha256").update(key).digest("hex");
|
|
442852
443510
|
}
|
|
442853
443511
|
function decodeCursor(after) {
|
|
442854
443512
|
const id = /^[A-Za-z0-9_-]+$/.test(after) ? Buffer.from(after, "base64url").toString() : "";
|
|
@@ -450286,7 +450944,7 @@ var require_ip_address = __commonJS(function(exports) {
|
|
|
450286
450944
|
import { isIPv6 } from "node:net";
|
|
450287
450945
|
import { isIPv6 as isIPv62 } from "node:net";
|
|
450288
450946
|
import { Buffer as Buffer4 } from "node:buffer";
|
|
450289
|
-
import { createHash as
|
|
450947
|
+
import { createHash as createHash28 } from "node:crypto";
|
|
450290
450948
|
import { isIP as isIP2 } from "node:net";
|
|
450291
450949
|
function ipKeyGenerator(ip, ipv6Subnet = 56) {
|
|
450292
450950
|
if (isIPv6(ip)) {
|
|
@@ -450384,7 +451042,7 @@ var import_ip_address, import_debug2, ipv4CompatibleSubnet, MemoryStore = class
|
|
|
450384
451042
|
}
|
|
450385
451043
|
return resetSeconds;
|
|
450386
451044
|
}, getPartitionKey = (key) => {
|
|
450387
|
-
const hash =
|
|
451045
|
+
const hash = createHash28("sha256");
|
|
450388
451046
|
hash.update(key);
|
|
450389
451047
|
const partitionKey = hash.digest("hex").slice(0, 12);
|
|
450390
451048
|
return Buffer4.from(partitionKey).toString("base64");
|
|
@@ -451224,9 +451882,9 @@ var init_server_old = __esm(() => {
|
|
|
451224
451882
|
});
|
|
451225
451883
|
|
|
451226
451884
|
// src/authorize_bypass_header.ts
|
|
451227
|
-
import { createHash as
|
|
451885
|
+
import { createHash as createHash29, timingSafeEqual } from "node:crypto";
|
|
451228
451886
|
var BYPASS_AUTHORIZE_HEADER = "x-publisher-bypass-authorize", secretsMatch = (presented, configured) => {
|
|
451229
|
-
const digest = (value) =>
|
|
451887
|
+
const digest = (value) => createHash29("sha256").update(value, "utf8").digest();
|
|
451230
451888
|
return timingSafeEqual(digest(presented), digest(configured));
|
|
451231
451889
|
}, readBypassAuthorize = (req) => {
|
|
451232
451890
|
const configured = settings.get("authorize.bypassSecret");
|
|
@@ -451704,8 +452362,8 @@ var init_api = __esm(() => {
|
|
|
451704
452362
|
|
|
451705
452363
|
// src/routes/data_apps.ts
|
|
451706
452364
|
import * as fsp from "fs/promises";
|
|
451707
|
-
import * as
|
|
451708
|
-
import { pathToFileURL as
|
|
452365
|
+
import * as path58 from "path";
|
|
452366
|
+
import { pathToFileURL as pathToFileURL28 } from "url";
|
|
451709
452367
|
async function serveFromPackage(environmentStore, req, res) {
|
|
451710
452368
|
const subPathRaw = req.params["0"] ?? "";
|
|
451711
452369
|
try {
|
|
@@ -451714,7 +452372,7 @@ async function serveFromPackage(environmentStore, req, res) {
|
|
|
451714
452372
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, {
|
|
451715
452373
|
versionId: VersionRef.parse(staticVersionId)
|
|
451716
452374
|
});
|
|
451717
|
-
const publicRoot =
|
|
452375
|
+
const publicRoot = path58.join(pkg.getPackagePath(), "public");
|
|
451718
452376
|
let subPath = subPathRaw;
|
|
451719
452377
|
if (subPath === "" || subPath.endsWith("/")) {
|
|
451720
452378
|
subPath = subPath + "index.html";
|
|
@@ -451782,7 +452440,7 @@ function registerDataAppListRoute(app, apiPrefix, environmentStore) {
|
|
|
451782
452440
|
app.get(`${apiPrefix}${DATA_APPS_ROUTE}`, apiRoute(async (req) => {
|
|
451783
452441
|
const environment = await environmentStore.getEnvironment(parseEnvironmentName(req.params.environmentName), false);
|
|
451784
452442
|
const pkg = await environment.getPackage(parsePackageName(req.params.packageName), false, { versionId: versionRefOf(req) });
|
|
451785
|
-
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);
|
|
451786
452444
|
}));
|
|
451787
452445
|
}
|
|
451788
452446
|
function stripNonTagText(input) {
|
|
@@ -451797,7 +452455,7 @@ function stripNonTagText(input) {
|
|
|
451797
452455
|
async function servedPublic(publicRoot) {
|
|
451798
452456
|
let real;
|
|
451799
452457
|
try {
|
|
451800
|
-
real = await confinedPackagePath(
|
|
452458
|
+
real = await confinedPackagePath(path58.dirname(publicRoot), pathToFileURL28(publicRoot));
|
|
451801
452459
|
} catch {
|
|
451802
452460
|
return { kind: "outside" };
|
|
451803
452461
|
}
|
|
@@ -451809,11 +452467,11 @@ async function servedPublic(publicRoot) {
|
|
|
451809
452467
|
async function insidePublic(publicRoot, realPublic, file) {
|
|
451810
452468
|
let real;
|
|
451811
452469
|
try {
|
|
451812
|
-
real = await confinedPackagePath(
|
|
452470
|
+
real = await confinedPackagePath(path58.dirname(publicRoot), pathToFileURL28(file));
|
|
451813
452471
|
} catch {
|
|
451814
452472
|
return;
|
|
451815
452473
|
}
|
|
451816
|
-
return stepsOutside(
|
|
452474
|
+
return stepsOutside(path58.relative(realPublic, real)) ? undefined : real;
|
|
451817
452475
|
}
|
|
451818
452476
|
async function listPackageDataApps(environmentName, packageName, publicRoot, versionId) {
|
|
451819
452477
|
const out = [];
|
|
@@ -451833,14 +452491,14 @@ async function listPackageDataApps(environmentName, packageName, publicRoot, ver
|
|
|
451833
452491
|
for (const entry of entries) {
|
|
451834
452492
|
if (entry.name.startsWith(".") || entry.name === "node_modules")
|
|
451835
452493
|
continue;
|
|
451836
|
-
const full =
|
|
452494
|
+
const full = path58.join(dir, entry.name);
|
|
451837
452495
|
const real = await insidePublic(publicRoot, realPublic, full);
|
|
451838
452496
|
if (real === undefined)
|
|
451839
452497
|
continue;
|
|
451840
452498
|
if (entry.isDirectory()) {
|
|
451841
452499
|
await walk(full, real, depth + 1);
|
|
451842
452500
|
} else if (entry.isFile() && (entry.name.endsWith(".html") || entry.name.endsWith(".htm"))) {
|
|
451843
|
-
const rel =
|
|
452501
|
+
const rel = path58.relative(publicRoot, full).replace(/\\/g, "/");
|
|
451844
452502
|
let title = rel;
|
|
451845
452503
|
let fit;
|
|
451846
452504
|
try {
|
|
@@ -452019,9 +452677,9 @@ var init_spa_fallback = __esm(() => {
|
|
|
452019
452677
|
});
|
|
452020
452678
|
|
|
452021
452679
|
// src/routes/spa.ts
|
|
452022
|
-
import * as
|
|
452680
|
+
import * as path59 from "path";
|
|
452023
452681
|
function registerSpaFallback(app, apiPrefix, appRoot, environmentStore) {
|
|
452024
|
-
const SPA_INDEX =
|
|
452682
|
+
const SPA_INDEX = path59.resolve(appRoot, "index.html");
|
|
452025
452683
|
const escapeHtml = (value) => value.replace(/[<>&]/g, (c) => ({ "<": "<", ">": ">", "&": "&" })[c] ?? c);
|
|
452026
452684
|
const loadedPackage = (environmentName, packageName) => environmentStore.getLoadedEnvironments().find((environment) => environment.getEnvironmentName() === environmentName)?.peekPackage(packageName);
|
|
452027
452685
|
const loadedRoutes = {
|
|
@@ -452083,7 +452741,7 @@ var init_spa = __esm(() => {
|
|
|
452083
452741
|
});
|
|
452084
452742
|
|
|
452085
452743
|
// src/routes/main_app.ts
|
|
452086
|
-
import * as
|
|
452744
|
+
import * as path60 from "path";
|
|
452087
452745
|
function createMainApp(options) {
|
|
452088
452746
|
const { controllers } = options;
|
|
452089
452747
|
const { environmentStore } = controllers;
|
|
@@ -452097,7 +452755,7 @@ function createMainApp(options) {
|
|
|
452097
452755
|
registerDataAppStaticRoutes(app, environmentStore, options.dataAppRuntimePath);
|
|
452098
452756
|
if (options.consoleRoot) {
|
|
452099
452757
|
app.use("/", import_express2.default.static(options.consoleRoot));
|
|
452100
|
-
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")));
|
|
452101
452759
|
}
|
|
452102
452760
|
if (options.proxyConsoleToDevServer) {
|
|
452103
452761
|
app.use(import_http_proxy_middleware.createProxyMiddleware({
|
|
@@ -452351,7 +453009,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452351
453009
|
init.body = Readable3.toWeb(incoming);
|
|
452352
453010
|
}
|
|
452353
453011
|
return new Request$1(url, init);
|
|
452354
|
-
}, getRequestCache, requestCache, incomingKey,
|
|
453012
|
+
}, getRequestCache, requestCache, incomingKey, urlKey2, methodKey, headersKey, abortControllerKey, getAbortController, abortRequest, bodyBufferKey, bodyReadPromiseKey, bodyConsumedDirectlyKey, bodyLockReaderKey, abortReasonKey, newBodyUnusableError = () => {
|
|
452355
453013
|
return /* @__PURE__ */ new TypeError("Body is unusable");
|
|
452356
453014
|
}, rejectBodyUnusable = () => {
|
|
452357
453015
|
return Promise.reject(newBodyUnusableError());
|
|
@@ -452536,7 +453194,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452536
453194
|
if (incoming instanceof Http2ServerRequest)
|
|
452537
453195
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
452538
453196
|
try {
|
|
452539
|
-
req[
|
|
453197
|
+
req[urlKey2] = new URL(incomingUrl).href;
|
|
452540
453198
|
} catch (e) {
|
|
452541
453199
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
452542
453200
|
}
|
|
@@ -452553,7 +453211,7 @@ var RequestError, nonJoinedHeaders, validHeaderName, isHttpWhitespace = (code) =
|
|
|
452553
453211
|
} else
|
|
452554
453212
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
452555
453213
|
try {
|
|
452556
|
-
req[
|
|
453214
|
+
req[urlKey2] = buildUrl(scheme, host, incomingUrl);
|
|
452557
453215
|
} catch (e) {
|
|
452558
453216
|
if (e instanceof RequestError)
|
|
452559
453217
|
throw e;
|
|
@@ -453056,7 +453714,7 @@ var init_dist6 = __esm(() => {
|
|
|
453056
453714
|
getRequestCache = Symbol("getRequestCache");
|
|
453057
453715
|
requestCache = Symbol("requestCache");
|
|
453058
453716
|
incomingKey = Symbol("incomingKey");
|
|
453059
|
-
|
|
453717
|
+
urlKey2 = Symbol("urlKey");
|
|
453060
453718
|
methodKey = Symbol("methodKey");
|
|
453061
453719
|
headersKey = Symbol("headersKey");
|
|
453062
453720
|
abortControllerKey = Symbol("abortControllerKey");
|
|
@@ -453074,7 +453732,7 @@ var init_dist6 = __esm(() => {
|
|
|
453074
453732
|
return this[methodKey];
|
|
453075
453733
|
},
|
|
453076
453734
|
get url() {
|
|
453077
|
-
return this[
|
|
453735
|
+
return this[urlKey2];
|
|
453078
453736
|
},
|
|
453079
453737
|
get headers() {
|
|
453080
453738
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
@@ -453110,14 +453768,14 @@ var init_dist6 = __esm(() => {
|
|
|
453110
453768
|
} });
|
|
453111
453769
|
init.duplex = "half";
|
|
453112
453770
|
}
|
|
453113
|
-
const req = new Request$1(this[
|
|
453771
|
+
const req = new Request$1(this[urlKey2], init);
|
|
453114
453772
|
if (method === "TRACE")
|
|
453115
453773
|
Object.defineProperty(req, "method", { get() {
|
|
453116
453774
|
return "TRACE";
|
|
453117
453775
|
} });
|
|
453118
453776
|
return this[requestCache] = req;
|
|
453119
453777
|
}
|
|
453120
|
-
return this[requestCache] = newRequestFromIncoming(this.method, this[
|
|
453778
|
+
return this[requestCache] = newRequestFromIncoming(this.method, this[urlKey2], this.headers, this[incomingKey], abortController);
|
|
453121
453779
|
},
|
|
453122
453780
|
get body() {
|
|
453123
453781
|
if (!this[bodyConsumedDirectlyKey])
|
|
@@ -481953,8 +482611,8 @@ var init_experimental_dialects = __esm(() => {
|
|
|
481953
482611
|
|
|
481954
482612
|
// src/main_server.ts
|
|
481955
482613
|
import * as http5 from "http";
|
|
481956
|
-
import * as
|
|
481957
|
-
import { fileURLToPath as
|
|
482614
|
+
import * as path61 from "path";
|
|
482615
|
+
import { fileURLToPath as fileURLToPath24 } from "url";
|
|
481958
482616
|
function startMaterializationSchedulerFromEnv(store, service) {
|
|
481959
482617
|
const config = getMaterializationSchedulerConfig();
|
|
481960
482618
|
if (!config)
|
|
@@ -481989,9 +482647,9 @@ async function buildApp(settings) {
|
|
|
481989
482647
|
const MCP_CONFIG_ENABLED = mcpConfigEnabled();
|
|
481990
482648
|
const SHUTDOWN_DRAIN_DURATION_SECONDS = settings.get("shutdown.drainDurationSeconds");
|
|
481991
482649
|
const SHUTDOWN_GRACEFUL_CLOSE_TIMEOUT_SECONDS = settings.get("shutdown.gracefulCloseTimeoutSeconds");
|
|
481992
|
-
const __filename_esm =
|
|
481993
|
-
const ROOT =
|
|
481994
|
-
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"));
|
|
481995
482653
|
const isDevelopment = externalEnv("NODE_ENV") === "development";
|
|
481996
482654
|
checkHeapConfiguration();
|
|
481997
482655
|
const environmentStore = new EnvironmentStore(SERVER_ROOT);
|
|
@@ -482096,7 +482754,7 @@ async function buildApp(settings) {
|
|
|
482096
482754
|
const mcpApp = createMcpApp(appServices);
|
|
482097
482755
|
const app = createMainApp({
|
|
482098
482756
|
controllers: appServices,
|
|
482099
|
-
dataAppRuntimePath:
|
|
482757
|
+
dataAppRuntimePath: path61.join(path61.dirname(__filename_esm), "runtime", "publisher.js"),
|
|
482100
482758
|
consoleRoot: isDevelopment ? undefined : ROOT,
|
|
482101
482759
|
proxyConsoleToDevServer: isDevelopment,
|
|
482102
482760
|
frameAncestors: settings.get("frameAncestors"),
|