@mastra/clickhouse 1.19.0 → 1.20.0-alpha.1

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/index.js CHANGED
@@ -3256,7 +3256,10 @@ CREATE TABLE IF NOT EXISTS ${TABLE_DELETION_REQUESTS} (
3256
3256
  requestedBy String DEFAULT '',
3257
3257
  lastAppliedAt DateTime64(3) DEFAULT 0,
3258
3258
  purgeVerifiedAt DateTime64(3) DEFAULT 0,
3259
- updatedAt DateTime64(3)
3259
+ updatedAt DateTime64(3),
3260
+ -- Bloom-filter skip index so has(predicateValues, id) mutation guards
3261
+ -- can skip granules instead of scanning every request in a tenant scope.
3262
+ INDEX idx_predicateValues predicateValues TYPE bloom_filter(0.01) GRANULARITY 2
3260
3263
  )
3261
3264
  ENGINE = ReplacingMergeTree(updatedAt)
3262
3265
  ORDER BY (organizationId, resourceId, requestId)
@@ -3484,7 +3487,8 @@ const ALL_MIGRATIONS = [
3484
3487
  addBloomIndex(TABLE_METRIC_EVENTS, "idx_experimentId", "experimentId"),
3485
3488
  addBloomIndex(TABLE_METRIC_EVENTS, "idx_runId", "runId"),
3486
3489
  addBloomIndex(TABLE_METRIC_EVENTS, "idx_sessionId", "sessionId"),
3487
- addBloomIndex(TABLE_METRIC_EVENTS, "idx_requestId", "requestId")
3490
+ addBloomIndex(TABLE_METRIC_EVENTS, "idx_requestId", "requestId"),
3491
+ addBloomIndex(TABLE_DELETION_REQUESTS, "idx_predicateValues", "predicateValues")
3488
3492
  ];
3489
3493
  const ALL_TABLE_NAMES = [
3490
3494
  TABLE_SPAN_EVENTS,
@@ -6770,6 +6774,76 @@ LIMIT ${limit}`,
6770
6774
  query_params: parameters.params
6771
6775
  };
6772
6776
  }
6777
+ function discoveryRegistry(scope) {
6778
+ if (scope === "trace") return TRACE_FIELDS;
6779
+ if (scope === "spans") return SPAN_FIELDS;
6780
+ if (scope === "scores") return SCORE_FIELDS;
6781
+ return FEEDBACK_FIELDS;
6782
+ }
6783
+ function discoverySource(scope) {
6784
+ if (scope === "trace") return "root_scope r";
6785
+ if (scope === "spans") return "current_spans s";
6786
+ if (scope === "scores") return "current_scores s";
6787
+ return "current_feedback s";
6788
+ }
6789
+ function discoveryCollections(scope) {
6790
+ return scope === "trace" ? /* @__PURE__ */ new Set() : /* @__PURE__ */ new Set([scope]);
6791
+ }
6792
+ function compileClickHouseTraceQueryObservedFields(plan) {
6793
+ const parameters = new ParameterBuilder();
6794
+ const ctes = compileClickHouseTraceScope(plan, /* @__PURE__ */ new Set(), parameters);
6795
+ const search = plan.search ? `AND positionCaseInsensitiveUTF8(concat('metadata.', key), ${parameters.add(plan.search, "String")}) > 0` : "";
6796
+ const limit = parameters.add(plan.limit + 1, "UInt64");
6797
+ ctes.push(`metadata_entries AS (
6798
+ SELECT
6799
+ entry.1 AS key,
6800
+ entry.2 AS rawValue,
6801
+ JSONExtractString(entry.2) AS value
6802
+ FROM root_scope r
6803
+ ARRAY JOIN JSONExtractKeysAndValuesRaw(ifNull(r.metadataRaw, '{}')) AS entry
6804
+ )`);
6805
+ return {
6806
+ query: `WITH ${ctes.join(",\n")}
6807
+ SELECT concat('metadata.', key) AS path, count() AS occurrences
6808
+ FROM metadata_entries
6809
+ WHERE JSONType(rawValue) = 'String'
6810
+ AND trim(value) != ''
6811
+ AND key != ''
6812
+ AND position(key, '.') = 0
6813
+ AND length(concat('metadata.', key)) <= ${coreStorage.TRACE_QUERY_MAX_PATH_BYTES}
6814
+ AND length(value) <= ${coreStorage.TRACE_QUERY_MAX_STRING_BYTES}
6815
+ ${search}
6816
+ GROUP BY key
6817
+ ORDER BY occurrences DESC, path ASC
6818
+ LIMIT ${limit}`,
6819
+ query_params: parameters.params
6820
+ };
6821
+ }
6822
+ function compileClickHouseTraceQueryValues(plan) {
6823
+ const parameters = new ParameterBuilder();
6824
+ const ctes = compileClickHouseTraceScope(plan, discoveryCollections(plan.predicateScope), parameters);
6825
+ let field;
6826
+ if (plan.predicateScope === "trace" && plan.path.startsWith("metadata.")) {
6827
+ const key = parameters.add(plan.path.slice(9), "String");
6828
+ field = `coalesce(if(mapContains(r.metadataSearch, ${key}), r.metadataSearch[${key}], NULL), nullIf(trim(JSONExtractString(r.metadataRaw, ${key})), ''))`;
6829
+ } else field = fieldDefinition(discoveryRegistry(plan.predicateScope), plan.path).sql;
6830
+ const search = plan.search ? `AND positionCaseInsensitiveUTF8(value, ${parameters.add(plan.search, "String")}) > 0` : "";
6831
+ const limit = parameters.add(plan.limit + 1, "UInt64");
6832
+ return {
6833
+ query: `WITH ${ctes.join(",\n")}, extracted AS (
6834
+ SELECT toString(${field}) AS value FROM ${discoverySource(plan.predicateScope)}
6835
+ )
6836
+ SELECT value, count() AS count
6837
+ FROM extracted
6838
+ WHERE value IS NOT NULL
6839
+ AND length(value) <= ${coreStorage.TRACE_QUERY_MAX_STRING_BYTES}
6840
+ ${search}
6841
+ GROUP BY value
6842
+ ORDER BY count DESC, value ASC
6843
+ LIMIT ${limit}`,
6844
+ query_params: parameters.params
6845
+ };
6846
+ }
6773
6847
  function asIsoTimestamp(value) {
6774
6848
  return new Date(value).toISOString();
6775
6849
  }
@@ -6796,6 +6870,27 @@ async function runWithClickHouseTraceQueryTimeout(client, timeoutMs, compiled, q
6796
6870
  throw error;
6797
6871
  }
6798
6872
  }
6873
+ async function getTraceQueryObservedFields(client, plan, timeoutMs) {
6874
+ if (plan.predicateScope !== "trace") return {
6875
+ observedFields: [],
6876
+ observedFieldsTruncated: false
6877
+ };
6878
+ const rows = await runWithClickHouseTraceQueryTimeout(client, timeoutMs, compileClickHouseTraceQueryObservedFields(plan));
6879
+ return {
6880
+ observedFields: rows.slice(0, plan.limit).map((row) => coreStorage.createTraceQueryObservedFieldDescriptor(String(row.path), Number(row.occurrences))),
6881
+ observedFieldsTruncated: rows.length > plan.limit
6882
+ };
6883
+ }
6884
+ async function getTraceQueryValues(client, plan, timeoutMs) {
6885
+ const rows = await runWithClickHouseTraceQueryTimeout(client, timeoutMs, compileClickHouseTraceQueryValues(plan));
6886
+ return coreStorage.getTraceQueryValuesResponseSchema.parse({
6887
+ values: rows.slice(0, plan.limit).map((row) => ({
6888
+ value: String(row.value),
6889
+ count: Number(row.count)
6890
+ })),
6891
+ valuesTruncated: rows.length > plan.limit
6892
+ });
6893
+ }
6799
6894
  async function queryTraces(client, plan, timeoutMs) {
6800
6895
  const rows = await runWithClickHouseTraceQueryTimeout(client, timeoutMs, compileClickHouseTraceQuery(plan));
6801
6896
  const visibleRows = rows.slice(0, plan.limit);
@@ -7961,6 +8056,7 @@ var ObservabilityStorageClickhouseVNext = class extends ObservabilityStorage {
7961
8056
  "metrics",
7962
8057
  "logs",
7963
8058
  "trace-query",
8059
+ "trace-query-discovery",
7964
8060
  "thread-query"
7965
8061
  ];
7966
8062
  return [
@@ -7968,6 +8064,7 @@ var ObservabilityStorageClickhouseVNext = class extends ObservabilityStorage {
7968
8064
  "logs",
7969
8065
  "delta-polling",
7970
8066
  "trace-query",
8067
+ "trace-query-discovery",
7971
8068
  "thread-query"
7972
8069
  ];
7973
8070
  }
@@ -8095,6 +8192,30 @@ var ObservabilityStorageClickhouseVNext = class extends ObservabilityStorage {
8095
8192
  }, error);
8096
8193
  }
8097
8194
  }
8195
+ async getTraceQueryObservedFields(plan) {
8196
+ try {
8197
+ return await getTraceQueryObservedFields(this.#client, plan, this.#traceQueryTimeoutMs);
8198
+ } catch (error) {
8199
+ if (error instanceof MastraError || error instanceof coreStorage.TraceQueryExecutionError) throw error;
8200
+ throw new MastraError({
8201
+ id: createStorageErrorId("CLICKHOUSE", "GET_TRACE_QUERY_OBSERVED_FIELDS", "FAILED"),
8202
+ domain: ErrorDomain.STORAGE,
8203
+ category: ErrorCategory.THIRD_PARTY
8204
+ }, error);
8205
+ }
8206
+ }
8207
+ async getTraceQueryValues(plan) {
8208
+ try {
8209
+ return await getTraceQueryValues(this.#client, plan, this.#traceQueryTimeoutMs);
8210
+ } catch (error) {
8211
+ if (error instanceof MastraError || error instanceof coreStorage.TraceQueryExecutionError) throw error;
8212
+ throw new MastraError({
8213
+ id: createStorageErrorId("CLICKHOUSE", "GET_TRACE_QUERY_VALUES", "FAILED"),
8214
+ domain: ErrorDomain.STORAGE,
8215
+ category: ErrorCategory.THIRD_PARTY
8216
+ }, error);
8217
+ }
8218
+ }
8098
8219
  async queryThreads(plan) {
8099
8220
  try {
8100
8221
  return await queryThreads(this.#client, plan, this.#traceQueryTimeoutMs);