@mastra/clickhouse 1.16.0-alpha.0 → 1.16.0-alpha.2

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # @mastra/clickhouse
2
2
 
3
+ ## 1.16.0-alpha.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Enforce atomic conditional background task state updates so cancellation cannot be overwritten during dispatch. Background task storage is no longer exposed by Cloudflare KV or ClickHouse, which cannot provide the required compare-and-set semantics. ([#22228](https://github.com/mastra-ai/mastra/pull/22228))
8
+
9
+ - Updated dependencies [[`aa3a85d`](https://github.com/mastra-ai/mastra/commit/aa3a85daf094c683bb97efdf4b6a696d2e474af5), [`d29d06f`](https://github.com/mastra-ai/mastra/commit/d29d06fe00bbd35b4571150ea04c59d2ed783c71), [`e6516df`](https://github.com/mastra-ai/mastra/commit/e6516dfcdae4f4ac0e7971d84359a81385ee602f), [`0b2a3d1`](https://github.com/mastra-ai/mastra/commit/0b2a3d1783875c5b97b7b36ab3d03d7360e0dde7), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`57de7d6`](https://github.com/mastra-ai/mastra/commit/57de7d644ba7146edb4e9e6111ec4fa98c3a59e9), [`e8e299c`](https://github.com/mastra-ai/mastra/commit/e8e299cc6abdfc39947e2fec25803493015d3882), [`edfc548`](https://github.com/mastra-ai/mastra/commit/edfc548886bc7bae17b681f8b6b41a47eb32bcd2), [`a8a4871`](https://github.com/mastra-ai/mastra/commit/a8a4871215f51da95c47129602157ce5372f634a), [`5165cdc`](https://github.com/mastra-ai/mastra/commit/5165cdcdcf50e144bb8113278535196cc9b07065), [`6bb5d71`](https://github.com/mastra-ai/mastra/commit/6bb5d7193fe9166b219f0fccae17db7a5ae86e65), [`9ee8120`](https://github.com/mastra-ai/mastra/commit/9ee8120ce17f76b9f617489e05a283353742690a), [`d975e92`](https://github.com/mastra-ai/mastra/commit/d975e924d4936f46c386bd3dee39c671720289f6), [`1cfa878`](https://github.com/mastra-ai/mastra/commit/1cfa8784d8da0dfaa0317e5048bc48b6084a5ea5), [`c118318`](https://github.com/mastra-ai/mastra/commit/c1183181c9804303db4b511c2e2648f8b714712b), [`fc07c64`](https://github.com/mastra-ai/mastra/commit/fc07c6465043e08e99193a6751a01c56ffc2e7a1), [`542dee2`](https://github.com/mastra-ai/mastra/commit/542dee254167f974ff8cbbbfc0ce10f9a2616a7b), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`a58483c`](https://github.com/mastra-ai/mastra/commit/a58483cff1a9d41fce7c931843f48cb0ac450f64), [`895e9df`](https://github.com/mastra-ai/mastra/commit/895e9dfc17d6f34299eca64e317ded9e5f5e5ef8)]:
10
+ - @mastra/core@1.62.0-alpha.8
11
+
12
+ ## 1.16.0-alpha.1
13
+
14
+ ### Patch Changes
15
+
16
+ - Fixed ClickHouse observability discovery refreshable materialized views failing with error 36 when their target tables use a Replicated engine inside a non-Replicated (Atomic) database. The discovery views now refresh in APPEND mode, and existing deployments with the old view definitions are migrated automatically on startup (only the views are recreated; discovery data is kept). Fixes https://github.com/mastra-ai/mastra/issues/21168 ([#22103](https://github.com/mastra-ai/mastra/pull/22103))
17
+
18
+ - Updated dependencies [[`2c85f42`](https://github.com/mastra-ai/mastra/commit/2c85f428e04ccd63ea31a7ec80b5b327afdad555), [`11bbeb9`](https://github.com/mastra-ai/mastra/commit/11bbeb9b108ef2264e05acefc6dafb9cbb342921), [`1a485f3`](https://github.com/mastra-ai/mastra/commit/1a485f3538f5ec64d58bd8b5e1e99de0c695c87b), [`0d37487`](https://github.com/mastra-ai/mastra/commit/0d37487d9f349388a3f1cef6a536cf9dcc4b6273), [`8661d7d`](https://github.com/mastra-ai/mastra/commit/8661d7d7179f0a024456aabdd8679bcecd09ac28), [`575e343`](https://github.com/mastra-ai/mastra/commit/575e343900451021d96110916497d334af7bc252), [`cacb839`](https://github.com/mastra-ai/mastra/commit/cacb8392d9e74189b56d857290b0615f98a2683d), [`b47b26e`](https://github.com/mastra-ai/mastra/commit/b47b26e6fe95cb8a3482be2c5e52de157fe59d0b), [`0d37487`](https://github.com/mastra-ai/mastra/commit/0d37487d9f349388a3f1cef6a536cf9dcc4b6273), [`c46eb09`](https://github.com/mastra-ai/mastra/commit/c46eb09ce4987509af57a0ac582c61241a6dd2f1), [`30ed33e`](https://github.com/mastra-ai/mastra/commit/30ed33ee14084a26019aba15fceadda6d6ddefaf), [`91ad69d`](https://github.com/mastra-ai/mastra/commit/91ad69d64994c89199b0c55399e64ed91c61df2f), [`8dc408d`](https://github.com/mastra-ai/mastra/commit/8dc408d34438f9e13297f792c11a5cfd6cf952e1), [`c92def1`](https://github.com/mastra-ai/mastra/commit/c92def10a13c822972c96f0a4ca6ffc1f4258aed), [`c5eaec5`](https://github.com/mastra-ai/mastra/commit/c5eaec5a860d80d0e3805e67db0414b87ac8cbed), [`e66b2ba`](https://github.com/mastra-ai/mastra/commit/e66b2ba100db63eaeab6e21e1ea34b113f2ec781)]:
19
+ - @mastra/core@1.62.0-alpha.3
20
+
3
21
  ## 1.16.0-alpha.0
4
22
 
5
23
  ### Minor Changes
@@ -3,7 +3,7 @@ name: mastra-clickhouse
3
3
  description: Documentation for @mastra/clickhouse. Use when working with @mastra/clickhouse APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/clickhouse"
6
- version: "1.16.0-alpha.0"
6
+ version: "1.16.0-alpha.2"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.16.0-alpha.0",
2
+ "version": "1.16.0-alpha.2",
3
3
  "package": "@mastra/clickhouse",
4
4
  "exports": {},
5
5
  "modules": {}
package/dist/index.cjs CHANGED
@@ -2,8 +2,8 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _clickhouse_client = require("@clickhouse/client");
3
3
  let _mastra_core_error = require("@mastra/core/error");
4
4
  let _mastra_core_storage = require("@mastra/core/storage");
5
- let _mastra_core_base = require("@mastra/core/base");
6
5
  let _mastra_core_agent = require("@mastra/core/agent");
6
+ let _mastra_core_base = require("@mastra/core/base");
7
7
  let _mastra_core_utils = require("@mastra/core/utils");
8
8
  let _mastra_core_features = require("@mastra/core/features");
9
9
  let _mastra_core_evals = require("@mastra/core/evals");
@@ -745,228 +745,6 @@ var ClickhouseDB = class extends _mastra_core_base.MastraBase {
745
745
  }
746
746
  };
747
747
  //#endregion
748
- //#region src/storage/domains/background-tasks/index.ts
749
- function serializeJson(v) {
750
- if (typeof v === "object" && v != null) return JSON.stringify(v);
751
- return v ?? "";
752
- }
753
- function readNullableDate(val) {
754
- if (val == null || val === "") return void 0;
755
- const d = new Date(val);
756
- if (Number.isNaN(d.getTime()) || d.getTime() === 0) return void 0;
757
- return d;
758
- }
759
- function rowToTask(row) {
760
- const parseJson = (val) => {
761
- if (val == null || val === "") return void 0;
762
- if (typeof val === "string") try {
763
- return JSON.parse(val);
764
- } catch {
765
- return val;
766
- }
767
- return val;
768
- };
769
- return {
770
- id: row.id,
771
- status: row.status,
772
- toolName: row.tool_name,
773
- toolCallId: row.tool_call_id,
774
- args: parseJson(row.args) ?? {},
775
- agentId: row.agent_id,
776
- threadId: row.thread_id || void 0,
777
- resourceId: row.resource_id || void 0,
778
- runId: row.run_id ?? "",
779
- result: parseJson(row.result),
780
- error: parseJson(row.error),
781
- suspendPayload: parseJson(row.suspend_payload),
782
- retryCount: Number(row.retry_count ?? 0),
783
- maxRetries: Number(row.max_retries ?? 0),
784
- timeoutMs: Number(row.timeout_ms ?? 3e5),
785
- createdAt: new Date(row.createdAt),
786
- startedAt: readNullableDate(row.startedAt),
787
- suspendedAt: readNullableDate(row.suspendedAt),
788
- completedAt: readNullableDate(row.completedAt)
789
- };
790
- }
791
- var BackgroundTasksStorageClickhouse = class extends _mastra_core_storage.BackgroundTasksStorage {
792
- client;
793
- #db;
794
- constructor(config) {
795
- super();
796
- const { client, ttl, replication } = resolveClickhouseConfig(config);
797
- this.client = client;
798
- this.#db = new ClickhouseDB({
799
- client,
800
- ttl,
801
- replication
802
- });
803
- }
804
- async init() {
805
- await this.#db.createTable({
806
- tableName: _mastra_core_storage.TABLE_BACKGROUND_TASKS,
807
- schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_BACKGROUND_TASKS]
808
- });
809
- await this.#db.alterTable({
810
- tableName: _mastra_core_storage.TABLE_BACKGROUND_TASKS,
811
- schema: _mastra_core_storage.TABLE_SCHEMAS[_mastra_core_storage.TABLE_BACKGROUND_TASKS],
812
- ifNotExists: ["suspend_payload", "suspendedAt"]
813
- });
814
- }
815
- async dangerouslyClearAll() {
816
- await this.#db.clearTable({ tableName: _mastra_core_storage.TABLE_BACKGROUND_TASKS });
817
- }
818
- async createTask(task) {
819
- await this.client.insert({
820
- table: _mastra_core_storage.TABLE_BACKGROUND_TASKS,
821
- values: [{
822
- id: task.id,
823
- tool_call_id: task.toolCallId,
824
- tool_name: task.toolName,
825
- agent_id: task.agentId,
826
- thread_id: task.threadId ?? "",
827
- resource_id: task.resourceId ?? "",
828
- run_id: task.runId,
829
- status: task.status,
830
- args: serializeJson(task.args),
831
- result: serializeJson(task.result),
832
- error: serializeJson(task.error),
833
- suspend_payload: serializeJson(task.suspendPayload),
834
- retry_count: task.retryCount,
835
- max_retries: task.maxRetries,
836
- timeout_ms: task.timeoutMs,
837
- createdAt: task.createdAt.toISOString(),
838
- startedAt: task.startedAt?.toISOString() ?? "1970-01-01T00:00:00.000Z",
839
- suspendedAt: task.suspendedAt?.toISOString() ?? "1970-01-01T00:00:00.000Z",
840
- completedAt: task.completedAt?.toISOString() ?? "1970-01-01T00:00:00.000Z"
841
- }],
842
- format: "JSONEachRow",
843
- clickhouse_settings: { date_time_input_format: "best_effort" }
844
- });
845
- }
846
- async updateTask(taskId, update) {
847
- const existing = await this.getTask(taskId);
848
- if (!existing) return;
849
- const merged = { ...existing };
850
- if ("status" in update) merged.status = update.status;
851
- if ("result" in update) merged.result = update.result;
852
- if ("error" in update) merged.error = update.error;
853
- if ("suspendPayload" in update) merged.suspendPayload = update.suspendPayload;
854
- if ("retryCount" in update) merged.retryCount = update.retryCount;
855
- if ("startedAt" in update) merged.startedAt = update.startedAt;
856
- if ("suspendedAt" in update) merged.suspendedAt = update.suspendedAt;
857
- if ("completedAt" in update) merged.completedAt = update.completedAt;
858
- await this.createTask(merged);
859
- }
860
- async getTask(taskId) {
861
- const rows = await (await this.client.query({
862
- query: `SELECT * FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} FINAL WHERE id = {var_id:String} LIMIT 1`,
863
- query_params: { var_id: taskId },
864
- format: "JSONEachRow",
865
- clickhouse_settings: { date_time_input_format: "best_effort" }
866
- })).json();
867
- return rows.length > 0 ? rowToTask(rows[0]) : null;
868
- }
869
- buildFilterClause(filter) {
870
- const conditions = [];
871
- const params = {};
872
- if (filter.status) {
873
- const statuses = Array.isArray(filter.status) ? filter.status : [filter.status];
874
- conditions.push(`status IN ({var_statuses:Array(String)})`);
875
- params.var_statuses = statuses;
876
- }
877
- if (filter.agentId) {
878
- conditions.push(`agent_id = {var_agent:String}`);
879
- params.var_agent = filter.agentId;
880
- }
881
- if (filter.threadId) {
882
- conditions.push(`thread_id = {var_thread:String}`);
883
- params.var_thread = filter.threadId;
884
- }
885
- if (filter.runId) {
886
- conditions.push(`run_id = {var_run:String}`);
887
- params.var_run = filter.runId;
888
- }
889
- if (filter.toolName) {
890
- conditions.push(`tool_name = {var_tool:String}`);
891
- params.var_tool = filter.toolName;
892
- }
893
- if (filter.toolCallId) {
894
- conditions.push(`tool_call_id = {var_tool_call:String}`);
895
- params.var_tool_call = filter.toolCallId;
896
- }
897
- const dateCol = filter.dateFilterBy === "startedAt" ? "startedAt" : filter.dateFilterBy === "suspendedAt" ? "suspendedAt" : filter.dateFilterBy === "completedAt" ? "completedAt" : "createdAt";
898
- if (filter.fromDate) {
899
- conditions.push(`${dateCol} >= parseDateTimeBestEffort({var_from_date:String})`);
900
- params.var_from_date = filter.fromDate.toISOString();
901
- }
902
- if (filter.toDate) {
903
- conditions.push(`${dateCol} < parseDateTimeBestEffort({var_to_date:String})`);
904
- params.var_to_date = filter.toDate.toISOString();
905
- }
906
- return {
907
- where: conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "",
908
- params
909
- };
910
- }
911
- async listTasks(filter) {
912
- const { where, params } = this.buildFilterClause(filter);
913
- const countRows = await (await this.client.query({
914
- query: `SELECT count() as count FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} FINAL ${where}`,
915
- query_params: params,
916
- format: "JSONEachRow",
917
- clickhouse_settings: { date_time_input_format: "best_effort" }
918
- })).json();
919
- const total = Number(countRows[0]?.count ?? 0);
920
- let sql = `SELECT * FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} FINAL ${where} ORDER BY ${filter.orderBy === "startedAt" ? "startedAt" : filter.orderBy === "suspendedAt" ? "suspendedAt" : filter.orderBy === "completedAt" ? "completedAt" : "createdAt"} ${filter.orderDirection === "desc" ? "DESC" : "ASC"}`;
921
- if (filter.perPage != null) {
922
- sql += ` LIMIT {var_limit:UInt32}`;
923
- params.var_limit = filter.perPage;
924
- if (filter.page != null) {
925
- sql += ` OFFSET {var_offset:UInt32}`;
926
- params.var_offset = filter.page * filter.perPage;
927
- }
928
- }
929
- return {
930
- tasks: (await (await this.client.query({
931
- query: sql,
932
- query_params: params,
933
- format: "JSONEachRow",
934
- clickhouse_settings: { date_time_input_format: "best_effort" }
935
- })).json()).map(rowToTask),
936
- total
937
- };
938
- }
939
- async deleteTask(taskId) {
940
- await this.client.command({
941
- query: `DELETE FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} WHERE id = {var_id:String}`,
942
- query_params: { var_id: taskId }
943
- });
944
- }
945
- async deleteTasks(filter) {
946
- const { where, params } = this.buildFilterClause(filter);
947
- if (!where) return;
948
- await this.client.command({
949
- query: `DELETE FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} ${where}`,
950
- query_params: params
951
- });
952
- }
953
- async getRunningCount() {
954
- const rows = await (await this.client.query({
955
- query: `SELECT count() as count FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} FINAL WHERE status = 'running'`,
956
- format: "JSONEachRow"
957
- })).json();
958
- return Number(rows[0]?.count ?? 0);
959
- }
960
- async getRunningCountByAgent(agentId) {
961
- const rows = await (await this.client.query({
962
- query: `SELECT count() as count FROM ${_mastra_core_storage.TABLE_BACKGROUND_TASKS} FINAL WHERE status = 'running' AND agent_id = {var_agent:String}`,
963
- query_params: { var_agent: agentId },
964
- format: "JSONEachRow"
965
- })).json();
966
- return Number(rows[0]?.count ?? 0);
967
- }
968
- };
969
- //#endregion
970
748
  //#region src/storage/domains/memory/index.ts
971
749
  /**
972
750
  * Serialize metadata object to JSON string for storage in ClickHouse.
@@ -3520,7 +3298,7 @@ function unionDistinctFromSignals(kind, key1Expr, valueExpr, extraJoin = "", ext
3520
3298
  }
3521
3299
  const DISCOVERY_VALUES_MV_DDL = `
3522
3300
  CREATE MATERIALIZED VIEW IF NOT EXISTS ${MV_DISCOVERY_VALUES}
3523
- REFRESH EVERY 1 MINUTE
3301
+ REFRESH EVERY 1 MINUTE APPEND
3524
3302
  TO ${TABLE_DISCOVERY_VALUES}
3525
3303
  AS
3526
3304
  SELECT DISTINCT kind, key1, value FROM (
@@ -3545,7 +3323,7 @@ SELECT DISTINCT kind, key1, value FROM (
3545
3323
  `;
3546
3324
  const DISCOVERY_PAIRS_MV_DDL = `
3547
3325
  CREATE MATERIALIZED VIEW IF NOT EXISTS ${MV_DISCOVERY_PAIRS}
3548
- REFRESH EVERY 5 MINUTE
3326
+ REFRESH EVERY 5 MINUTE APPEND
3549
3327
  TO ${TABLE_DISCOVERY_PAIRS}
3550
3328
  AS
3551
3329
  SELECT DISTINCT kind, key1, key2, value FROM (
@@ -7083,6 +6861,12 @@ async function filterAppliedRetention(client, entries) {
7083
6861
  * Init's subsequent `CREATE TABLE IF NOT EXISTS` and discovery MV bootstrap
7084
6862
  * recreate both with the current definitions.
7085
6863
  *
6864
+ * Separately, a refreshable MV whose stored definition lacks the `APPEND`
6865
+ * modifier (created by older releases) is dropped — keeping its target
6866
+ * table — so the MV bootstrap recreates it with the current APPEND
6867
+ * definition. Non-APPEND refreshes swap the target table atomically, which
6868
+ * fails when the target is Replicated inside a non-Replicated database.
6869
+ *
7086
6870
  * Silently returns if `system.tables` can't be queried — the rest of init
7087
6871
  * will still run and leave any existing tables untouched.
7088
6872
  */
@@ -7097,13 +6881,20 @@ async function assertExistingTablesCompatibleWithReplication(client, replication
7097
6881
  }
7098
6882
  async function reconcileDiscoveryTables(client, replication) {
7099
6883
  let engines;
6884
+ let mvCreateQueries;
7100
6885
  try {
7101
6886
  const rows = await (await client.query({
7102
- query: `SELECT name, engine FROM system.tables WHERE database = currentDatabase() AND name IN ({tables:Array(String)})`,
7103
- query_params: { tables: [TABLE_DISCOVERY_VALUES, TABLE_DISCOVERY_PAIRS] },
6887
+ query: `SELECT name, engine, create_table_query FROM system.tables WHERE database = currentDatabase() AND name IN ({tables:Array(String)})`,
6888
+ query_params: { tables: [
6889
+ TABLE_DISCOVERY_VALUES,
6890
+ TABLE_DISCOVERY_PAIRS,
6891
+ MV_DISCOVERY_VALUES,
6892
+ MV_DISCOVERY_PAIRS
6893
+ ] },
7104
6894
  format: "JSONEachRow"
7105
6895
  })).json();
7106
6896
  engines = new Map(rows.map((r) => [r.name, r.engine]));
6897
+ mvCreateQueries = new Map(rows.map((r) => [r.name, r.create_table_query]));
7107
6898
  } catch {
7108
6899
  return;
7109
6900
  }
@@ -7116,9 +6907,13 @@ async function reconcileDiscoveryTables(client, replication) {
7116
6907
  }];
7117
6908
  for (const { table, mv } of targets) {
7118
6909
  const engine = engines.get(table);
7119
- if (!engine || isReplacingMergeTreeEngine(engine)) continue;
7120
- await client.command({ query: addOnClusterToDDL(`DROP VIEW IF EXISTS ${mv}`, replication) });
7121
- await client.command({ query: addOnClusterToDDL(`DROP TABLE IF EXISTS ${table}`, replication) });
6910
+ if (engine && !isReplacingMergeTreeEngine(engine)) {
6911
+ await client.command({ query: addOnClusterToDDL(`DROP VIEW IF EXISTS ${mv}`, replication) });
6912
+ await client.command({ query: addOnClusterToDDL(`DROP TABLE IF EXISTS ${table}`, replication) });
6913
+ continue;
6914
+ }
6915
+ const createQuery = mvCreateQueries.get(mv);
6916
+ if (createQuery && /REFRESH EVERY/i.test(createQuery) && !/\bAPPEND\b/i.test(createQuery)) await client.command({ query: addOnClusterToDDL(`DROP VIEW IF EXISTS ${mv}`, replication) });
7122
6917
  }
7123
6918
  }
7124
6919
  async function queryNamesByTable(client, query, tables) {
@@ -8601,8 +8396,7 @@ var ClickhouseStore = class extends _mastra_core_storage.MastraCompositeStore {
8601
8396
  workflows,
8602
8397
  scores,
8603
8398
  memory,
8604
- observability,
8605
- backgroundTasks: new BackgroundTasksStorageClickhouse(domainConfig)
8399
+ observability
8606
8400
  };
8607
8401
  }
8608
8402
  async optimizeTable({ tableName }) {
@@ -8688,7 +8482,6 @@ var ClickhouseStoreVNext = class extends ClickhouseStore {
8688
8482
  }
8689
8483
  };
8690
8484
  //#endregion
8691
- exports.BackgroundTasksStorageClickhouse = BackgroundTasksStorageClickhouse;
8692
8485
  exports.COLUMN_TYPES = COLUMN_TYPES;
8693
8486
  exports.ClickhouseStore = ClickhouseStore;
8694
8487
  exports.ClickhouseStoreVNext = ClickhouseStoreVNext;