@mastra/pg 1.12.1-alpha.0 → 1.13.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +81 -0
  2. package/dist/docs/SKILL.md +1 -1
  3. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  4. package/dist/docs/references/reference-storage-composite.md +1 -1
  5. package/dist/docs/references/reference-storage-postgresql.md +1 -1
  6. package/dist/index.cjs +3851 -157
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.js +3850 -159
  9. package/dist/index.js.map +1 -1
  10. package/dist/storage/domains/agents/index.d.ts.map +1 -1
  11. package/dist/storage/domains/background-tasks/index.d.ts.map +1 -1
  12. package/dist/storage/domains/blobs/index.d.ts +1 -0
  13. package/dist/storage/domains/blobs/index.d.ts.map +1 -1
  14. package/dist/storage/domains/mcp-clients/index.d.ts +2 -0
  15. package/dist/storage/domains/mcp-clients/index.d.ts.map +1 -1
  16. package/dist/storage/domains/mcp-servers/index.d.ts +2 -0
  17. package/dist/storage/domains/mcp-servers/index.d.ts.map +1 -1
  18. package/dist/storage/domains/observability/v-next/ddl.d.ts +55 -0
  19. package/dist/storage/domains/observability/v-next/ddl.d.ts.map +1 -0
  20. package/dist/storage/domains/observability/v-next/discovery.d.ts +52 -0
  21. package/dist/storage/domains/observability/v-next/discovery.d.ts.map +1 -0
  22. package/dist/storage/domains/observability/v-next/feedback.d.ts +17 -0
  23. package/dist/storage/domains/observability/v-next/feedback.d.ts.map +1 -0
  24. package/dist/storage/domains/observability/v-next/filters.d.ts +29 -0
  25. package/dist/storage/domains/observability/v-next/filters.d.ts.map +1 -0
  26. package/dist/storage/domains/observability/v-next/helpers.d.ts +33 -0
  27. package/dist/storage/domains/observability/v-next/helpers.d.ts.map +1 -0
  28. package/dist/storage/domains/observability/v-next/index.d.ts +104 -0
  29. package/dist/storage/domains/observability/v-next/index.d.ts.map +1 -0
  30. package/dist/storage/domains/observability/v-next/listing.d.ts +53 -0
  31. package/dist/storage/domains/observability/v-next/listing.d.ts.map +1 -0
  32. package/dist/storage/domains/observability/v-next/logs.d.ts +8 -0
  33. package/dist/storage/domains/observability/v-next/logs.d.ts.map +1 -0
  34. package/dist/storage/domains/observability/v-next/metrics.d.ts +19 -0
  35. package/dist/storage/domains/observability/v-next/metrics.d.ts.map +1 -0
  36. package/dist/storage/domains/observability/v-next/olap.d.ts +93 -0
  37. package/dist/storage/domains/observability/v-next/olap.d.ts.map +1 -0
  38. package/dist/storage/domains/observability/v-next/partitioning.d.ts +76 -0
  39. package/dist/storage/domains/observability/v-next/partitioning.d.ts.map +1 -0
  40. package/dist/storage/domains/observability/v-next/pg-errors.d.ts +25 -0
  41. package/dist/storage/domains/observability/v-next/pg-errors.d.ts.map +1 -0
  42. package/dist/storage/domains/observability/v-next/polling.d.ts +28 -0
  43. package/dist/storage/domains/observability/v-next/polling.d.ts.map +1 -0
  44. package/dist/storage/domains/observability/v-next/scores.d.ts +17 -0
  45. package/dist/storage/domains/observability/v-next/scores.d.ts.map +1 -0
  46. package/dist/storage/domains/observability/v-next/signal-schema.d.ts +776 -0
  47. package/dist/storage/domains/observability/v-next/signal-schema.d.ts.map +1 -0
  48. package/dist/storage/domains/observability/v-next/sql.d.ts +31 -0
  49. package/dist/storage/domains/observability/v-next/sql.d.ts.map +1 -0
  50. package/dist/storage/domains/observability/v-next/traces.d.ts +16 -0
  51. package/dist/storage/domains/observability/v-next/traces.d.ts.map +1 -0
  52. package/dist/storage/domains/observability/v-next/tracing.d.ts +19 -0
  53. package/dist/storage/domains/observability/v-next/tracing.d.ts.map +1 -0
  54. package/dist/storage/domains/skills/index.d.ts +2 -0
  55. package/dist/storage/domains/skills/index.d.ts.map +1 -1
  56. package/dist/storage/domains/tool-provider-connections/index.d.ts +20 -0
  57. package/dist/storage/domains/tool-provider-connections/index.d.ts.map +1 -0
  58. package/dist/storage/domains/workspaces/index.d.ts +2 -0
  59. package/dist/storage/domains/workspaces/index.d.ts.map +1 -1
  60. package/dist/storage/index.d.ts +89 -1
  61. package/dist/storage/index.d.ts.map +1 -1
  62. package/dist/storage/pool-config.d.ts +7 -2
  63. package/dist/storage/pool-config.d.ts.map +1 -1
  64. package/package.json +8 -6
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
2
- import { createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, FavoritesStorage, TABLE_FAVORITES, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, NotificationsStorage, TABLE_NOTIFICATIONS, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1, getSqlType } from '@mastra/core/storage';
2
+ import { BRANCH_SPAN_TYPES, createVectorErrorId, AgentsStorage, TABLE_AGENTS, TABLE_AGENT_VERSIONS, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, BackgroundTasksStorage, TABLE_BACKGROUND_TASKS, BlobStore, TABLE_SKILL_BLOBS, ChannelsStorage, TABLE_CHANNEL_INSTALLATIONS, TABLE_CHANNEL_CONFIG, DatasetsStorage, TABLE_DATASETS, TABLE_DATASET_ITEMS, TABLE_DATASET_VERSIONS, DATASETS_SCHEMA, TABLE_CONFIGS, DATASET_ITEMS_SCHEMA, DATASET_VERSIONS_SCHEMA, ensureDate, safelyParseJSON, ExperimentsStorage, TABLE_EXPERIMENTS, TABLE_EXPERIMENT_RESULTS, EXPERIMENTS_SCHEMA, EXPERIMENT_RESULTS_SCHEMA, FavoritesStorage, TABLE_FAVORITES, MCPClientsStorage, TABLE_MCP_CLIENTS, TABLE_MCP_CLIENT_VERSIONS, MCPServersStorage, TABLE_MCP_SERVERS, TABLE_MCP_SERVER_VERSIONS, MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, NotificationsStorage, TABLE_NOTIFICATIONS, ObservabilityStorage, TABLE_SPANS, listTracesArgsSchema, toTraceSpans, PromptBlocksStorage, TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS, SchedulesStorage, TABLE_SCHEDULES, TABLE_SCHEDULE_TRIGGERS, ScorerDefinitionsStorage, TABLE_SCORER_DEFINITIONS, TABLE_SCORER_DEFINITION_VERSIONS, ScoresStorage, TABLE_SCORERS, SkillsStorage, TABLE_SKILLS, TABLE_SKILL_VERSIONS, ToolProviderConnectionsStorage, TABLE_TOOL_PROVIDER_CONNECTIONS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, WorkspacesStorage, TABLE_WORKSPACES, TABLE_WORKSPACE_VERSIONS, MastraCompositeStore, TraceStatus, getDefaultValue, listBranchesArgsSchema, listLogsArgsSchema, listMetricsArgsSchema, listScoresArgsSchema, listFeedbackArgsSchema, transformScoreRow as transformScoreRow$1, getSqlType, EntityType, METRIC_DISTINCT_COLUMNS } from '@mastra/core/storage';
3
3
  import { parseSqlIdentifier, parseFieldKey } from '@mastra/core/utils';
4
4
  import { MastraVector, validateTopK, validateUpsertInput } from '@mastra/core/vector';
5
5
  import { Mutex } from 'async-mutex';
@@ -11,6 +11,7 @@ import { MastraBase } from '@mastra/core/base';
11
11
  import { randomUUID } from 'crypto';
12
12
  import { createRequire } from 'module';
13
13
  import { MessageList } from '@mastra/core/agent';
14
+ import { coreFeatures } from '@mastra/core/features';
14
15
  import { saveScorePayloadSchema } from '@mastra/core/evals';
15
16
  import { parse } from 'pg-connection-string';
16
17
 
@@ -3529,7 +3530,15 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3529
3530
  await this.#db.alterTable({
3530
3531
  tableName: TABLE_AGENT_VERSIONS,
3531
3532
  schema: TABLE_SCHEMAS[TABLE_AGENT_VERSIONS],
3532
- ifNotExists: ["mcpClients", "requestContextSchema", "workspace", "skills", "skillsFormat", "browser"]
3533
+ ifNotExists: [
3534
+ "mcpClients",
3535
+ "requestContextSchema",
3536
+ "workspace",
3537
+ "skills",
3538
+ "skillsFormat",
3539
+ "browser",
3540
+ "toolProviders"
3541
+ ]
3533
3542
  });
3534
3543
  await this.#migrateToolsToJsonbFormat();
3535
3544
  await this.createDefaultIndexes();
@@ -3582,9 +3591,9 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3582
3591
  await this.#db.client.none(
3583
3592
  `INSERT INTO ${fullVersionsTableName}
3584
3593
  (id, "agentId", "versionNumber", name, description, instructions, model, tools,
3585
- "defaultOptions", workflows, agents, "integrationTools", "inputProcessors",
3594
+ "defaultOptions", workflows, agents, "integrationTools", "toolProviders", "inputProcessors",
3586
3595
  "outputProcessors", memory, scorers, "changedFields", "changeMessage", "createdAt")
3587
- VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19)
3596
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20)
3588
3597
  ON CONFLICT (id) DO NOTHING`,
3589
3598
  [
3590
3599
  versionId,
@@ -3599,6 +3608,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
3599
3608
  row.workflows ? JSON.stringify(row.workflows) : null,
3600
3609
  row.agents ? JSON.stringify(row.agents) : null,
3601
3610
  row.integrationTools ? JSON.stringify(row.integrationTools) : null,
3611
+ row.toolProviders ? JSON.stringify(row.toolProviders) : null,
3602
3612
  row.inputProcessors ? JSON.stringify(row.inputProcessors) : null,
3603
3613
  row.outputProcessors ? JSON.stringify(row.outputProcessors) : null,
3604
3614
  row.memory ? JSON.stringify(row.memory) : null,
@@ -4051,13 +4061,13 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
4051
4061
  `INSERT INTO ${tableName} (
4052
4062
  id, "agentId", "versionNumber",
4053
4063
  name, description, instructions, model, tools,
4054
- "defaultOptions", workflows, agents, "integrationTools",
4064
+ "defaultOptions", workflows, agents, "integrationTools", "toolProviders",
4055
4065
  "inputProcessors", "outputProcessors", memory, scorers,
4056
4066
  "mcpClients", "requestContextSchema", workspace, skills, "skillsFormat",
4057
4067
  browser,
4058
4068
  "changedFields", "changeMessage",
4059
4069
  "createdAt", "createdAtZ"
4060
- ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26)`,
4070
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27)`,
4061
4071
  [
4062
4072
  input.id,
4063
4073
  input.agentId,
@@ -4071,6 +4081,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
4071
4081
  input.workflows ? JSON.stringify(input.workflows) : null,
4072
4082
  input.agents ? JSON.stringify(input.agents) : null,
4073
4083
  input.integrationTools ? JSON.stringify(input.integrationTools) : null,
4084
+ input.toolProviders ? JSON.stringify(input.toolProviders) : null,
4074
4085
  input.inputProcessors ? JSON.stringify(input.inputProcessors) : null,
4075
4086
  input.outputProcessors ? JSON.stringify(input.outputProcessors) : null,
4076
4087
  input.memory ? JSON.stringify(input.memory) : null,
@@ -4321,6 +4332,7 @@ var AgentsPG = class _AgentsPG extends AgentsStorage {
4321
4332
  workflows: parseJsonResilient(row.workflows),
4322
4333
  agents: parseJsonResilient(row.agents),
4323
4334
  integrationTools: parseJsonResilient(row.integrationTools),
4335
+ toolProviders: parseJsonResilient(row.toolProviders),
4324
4336
  inputProcessors: parseJsonResilient(row.inputProcessors),
4325
4337
  outputProcessors: parseJsonResilient(row.outputProcessors),
4326
4338
  memory: parseJsonResilient(row.memory),
@@ -4359,6 +4371,10 @@ function parseJson(v) {
4359
4371
  return v ?? void 0;
4360
4372
  }
4361
4373
  function rowToTask(row) {
4374
+ const createdAt = row.createdAtZ || row.createdAt;
4375
+ const startedAt = row.startedAtZ || row.startedAt;
4376
+ const suspendedAt = row.suspendedAtZ || row.suspendedAt;
4377
+ const completedAt = row.completedAtZ || row.completedAt;
4362
4378
  return {
4363
4379
  id: row.id,
4364
4380
  status: row.status,
@@ -4375,10 +4391,10 @@ function rowToTask(row) {
4375
4391
  retryCount: Number(row.retry_count),
4376
4392
  maxRetries: Number(row.max_retries),
4377
4393
  timeoutMs: Number(row.timeout_ms),
4378
- createdAt: new Date(row.createdAtZ || row.createdAt),
4379
- startedAt: row.startedAtZ || row.startedAt ? new Date(row.startedAtZ || row.startedAt) : void 0,
4380
- suspendedAt: row.suspendedAtZ || row.suspendedAt ? new Date(row.suspendedAtZ || row.suspendedAt) : void 0,
4381
- completedAt: row.completedAtZ || row.completedAt ? new Date(row.completedAtZ || row.completedAt) : void 0
4394
+ createdAt: createdAt instanceof Date ? createdAt : new Date(createdAt),
4395
+ startedAt: startedAt ? startedAt instanceof Date ? startedAt : new Date(startedAt) : void 0,
4396
+ suspendedAt: suspendedAt ? suspendedAt instanceof Date ? suspendedAt : new Date(suspendedAt) : void 0,
4397
+ completedAt: completedAt ? completedAt instanceof Date ? completedAt : new Date(completedAt) : void 0
4382
4398
  };
4383
4399
  }
4384
4400
  var BackgroundTasksPG = class _BackgroundTasksPG extends BackgroundTasksStorage {
@@ -4496,9 +4512,13 @@ var BackgroundTasksPG = class _BackgroundTasksPG extends BackgroundTasksStorage
4496
4512
  max_retries: task.maxRetries,
4497
4513
  timeout_ms: task.timeoutMs,
4498
4514
  createdAt: task.createdAt.toISOString(),
4515
+ createdAtZ: task.createdAt.toISOString(),
4499
4516
  startedAt: task.startedAt?.toISOString() ?? null,
4517
+ startedAtZ: task.startedAt?.toISOString() ?? null,
4500
4518
  suspendedAt: task.suspendedAt?.toISOString() ?? null,
4501
- completedAt: task.completedAt?.toISOString() ?? null
4519
+ suspendedAtZ: task.suspendedAt?.toISOString() ?? null,
4520
+ completedAt: task.completedAt?.toISOString() ?? null,
4521
+ completedAtZ: task.completedAt?.toISOString() ?? null
4502
4522
  }
4503
4523
  });
4504
4524
  }
@@ -4675,6 +4695,16 @@ var BlobsPG = class extends BlobStore {
4675
4695
  this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
4676
4696
  this.#schema = schemaName || "public";
4677
4697
  }
4698
+ static getExportDDL(schemaName) {
4699
+ return [
4700
+ generateTableSQL({
4701
+ tableName: TABLE_SKILL_BLOBS,
4702
+ schema: TABLE_SCHEMAS[TABLE_SKILL_BLOBS],
4703
+ schemaName,
4704
+ includeAllConstraints: true
4705
+ })
4706
+ ];
4707
+ }
4678
4708
  async init() {
4679
4709
  await this.#db.createTable({
4680
4710
  tableName: TABLE_SKILL_BLOBS,
@@ -6753,16 +6783,39 @@ var MCPClientsPG = class _MCPClientsPG extends MCPClientsStorage {
6753
6783
  this.#skipDefaultIndexes = skipDefaultIndexes;
6754
6784
  this.#indexes = indexes?.filter((idx) => _MCPClientsPG.MANAGED_TABLES.includes(idx.table));
6755
6785
  }
6756
- getDefaultIndexDefinitions() {
6786
+ static getDefaultIndexDefs(schemaPrefix) {
6757
6787
  return [
6758
6788
  {
6759
- name: "idx_mcp_client_versions_client_version",
6789
+ name: `${schemaPrefix}idx_mcp_client_versions_client_version`,
6760
6790
  table: TABLE_MCP_CLIENT_VERSIONS,
6761
6791
  columns: ["mcpClientId", "versionNumber"],
6762
6792
  unique: true
6763
6793
  }
6764
6794
  ];
6765
6795
  }
6796
+ static getExportDDL(schemaName) {
6797
+ const statements = [];
6798
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
6799
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
6800
+ for (const tableName of _MCPClientsPG.MANAGED_TABLES) {
6801
+ statements.push(
6802
+ generateTableSQL({
6803
+ tableName,
6804
+ schema: TABLE_SCHEMAS[tableName],
6805
+ schemaName,
6806
+ includeAllConstraints: true
6807
+ })
6808
+ );
6809
+ }
6810
+ for (const idx of _MCPClientsPG.getDefaultIndexDefs(schemaPrefix)) {
6811
+ statements.push(generateIndexSQL(idx, schemaName));
6812
+ }
6813
+ return statements;
6814
+ }
6815
+ getDefaultIndexDefinitions() {
6816
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
6817
+ return _MCPClientsPG.getDefaultIndexDefs(schemaPrefix);
6818
+ }
6766
6819
  async createDefaultIndexes() {
6767
6820
  if (this.#skipDefaultIndexes) {
6768
6821
  return;
@@ -7366,16 +7419,39 @@ var MCPServersPG = class _MCPServersPG extends MCPServersStorage {
7366
7419
  this.#skipDefaultIndexes = skipDefaultIndexes;
7367
7420
  this.#indexes = indexes?.filter((idx) => _MCPServersPG.MANAGED_TABLES.includes(idx.table));
7368
7421
  }
7369
- getDefaultIndexDefinitions() {
7422
+ static getDefaultIndexDefs(schemaPrefix) {
7370
7423
  return [
7371
7424
  {
7372
- name: "idx_mcp_server_versions_server_version",
7425
+ name: `${schemaPrefix}idx_mcp_server_versions_server_version`,
7373
7426
  table: TABLE_MCP_SERVER_VERSIONS,
7374
7427
  columns: ["mcpServerId", "versionNumber"],
7375
7428
  unique: true
7376
7429
  }
7377
7430
  ];
7378
7431
  }
7432
+ static getExportDDL(schemaName) {
7433
+ const statements = [];
7434
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
7435
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
7436
+ for (const tableName of _MCPServersPG.MANAGED_TABLES) {
7437
+ statements.push(
7438
+ generateTableSQL({
7439
+ tableName,
7440
+ schema: TABLE_SCHEMAS[tableName],
7441
+ schemaName,
7442
+ includeAllConstraints: true
7443
+ })
7444
+ );
7445
+ }
7446
+ for (const idx of _MCPServersPG.getDefaultIndexDefs(schemaPrefix)) {
7447
+ statements.push(generateIndexSQL(idx, schemaName));
7448
+ }
7449
+ return statements;
7450
+ }
7451
+ getDefaultIndexDefinitions() {
7452
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
7453
+ return _MCPServersPG.getDefaultIndexDefs(schemaPrefix);
7454
+ }
7379
7455
  async createDefaultIndexes() {
7380
7456
  if (this.#skipDefaultIndexes) {
7381
7457
  return;
@@ -11438,135 +11514,3374 @@ var ObservabilityPG = class _ObservabilityPG extends ObservabilityStorage {
11438
11514
  }
11439
11515
  }
11440
11516
  };
11441
- var SNAPSHOT_FIELDS3 = ["name", "description", "content", "rules", "requestContextSchema"];
11442
- var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
11443
- #db;
11444
- #schema;
11445
- #skipDefaultIndexes;
11446
- #indexes;
11447
- static MANAGED_TABLES = [TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS];
11448
- constructor(config) {
11449
- super();
11450
- const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
11451
- this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
11452
- this.#schema = schemaName || "public";
11453
- this.#skipDefaultIndexes = skipDefaultIndexes;
11454
- this.#indexes = indexes?.filter((idx) => _PromptBlocksPG.MANAGED_TABLES.includes(idx.table));
11455
- }
11456
- /**
11457
- * Returns default index definitions for the prompt blocks domain tables.
11458
- * @param schemaPrefix - Prefix for index names (e.g. "my_schema_" or "")
11459
- */
11460
- static getDefaultIndexDefs(schemaPrefix) {
11461
- return [
11462
- {
11463
- name: `${schemaPrefix}idx_prompt_block_versions_block_version`,
11464
- table: TABLE_PROMPT_BLOCK_VERSIONS,
11465
- columns: ["blockId", "versionNumber"],
11466
- unique: true
11517
+
11518
+ // src/storage/domains/observability/v-next/signal-schema.ts
11519
+ var CURSOR_ID_COLUMN = { name: "cursorId", type: "bigserial" };
11520
+ var XACT_ID_COLUMN = {
11521
+ name: "xactId",
11522
+ type: "xid8",
11523
+ defaultSql: "pg_current_xact_id()"
11524
+ };
11525
+ var COMMON_CONTEXT_COLUMNS = [
11526
+ { name: "traceId", type: "text", nullable: true },
11527
+ { name: "spanId", type: "text", nullable: true },
11528
+ { name: "experimentId", type: "text", nullable: true },
11529
+ { name: "entityType", type: "text", nullable: true },
11530
+ { name: "entityId", type: "text", nullable: true },
11531
+ { name: "entityName", type: "text", nullable: true },
11532
+ { name: "entityVersionId", type: "text", nullable: true },
11533
+ { name: "parentEntityType", type: "text", nullable: true },
11534
+ { name: "parentEntityId", type: "text", nullable: true },
11535
+ { name: "parentEntityName", type: "text", nullable: true },
11536
+ { name: "parentEntityVersionId", type: "text", nullable: true },
11537
+ { name: "rootEntityType", type: "text", nullable: true },
11538
+ { name: "rootEntityId", type: "text", nullable: true },
11539
+ { name: "rootEntityName", type: "text", nullable: true },
11540
+ { name: "rootEntityVersionId", type: "text", nullable: true },
11541
+ { name: "userId", type: "text", nullable: true },
11542
+ { name: "organizationId", type: "text", nullable: true },
11543
+ { name: "resourceId", type: "text", nullable: true },
11544
+ { name: "runId", type: "text", nullable: true },
11545
+ { name: "sessionId", type: "text", nullable: true },
11546
+ { name: "threadId", type: "text", nullable: true },
11547
+ { name: "requestId", type: "text", nullable: true },
11548
+ { name: "environment", type: "text", nullable: true },
11549
+ { name: "executionSource", type: "text", nullable: true },
11550
+ { name: "serviceName", type: "text", nullable: true }
11551
+ ];
11552
+ var SPAN_EVENT_COLUMNS = [
11553
+ CURSOR_ID_COLUMN,
11554
+ XACT_ID_COLUMN,
11555
+ { name: "traceId", type: "text" },
11556
+ { name: "spanId", type: "text" },
11557
+ { name: "parentSpanId", type: "text", nullable: true },
11558
+ { name: "experimentId", type: "text", nullable: true },
11559
+ { name: "entityType", type: "text", nullable: true },
11560
+ { name: "entityId", type: "text", nullable: true },
11561
+ { name: "entityName", type: "text", nullable: true },
11562
+ { name: "entityVersionId", type: "text", nullable: true },
11563
+ { name: "parentEntityType", type: "text", nullable: true },
11564
+ { name: "parentEntityId", type: "text", nullable: true },
11565
+ { name: "parentEntityName", type: "text", nullable: true },
11566
+ { name: "parentEntityVersionId", type: "text", nullable: true },
11567
+ { name: "rootEntityType", type: "text", nullable: true },
11568
+ { name: "rootEntityId", type: "text", nullable: true },
11569
+ { name: "rootEntityName", type: "text", nullable: true },
11570
+ { name: "rootEntityVersionId", type: "text", nullable: true },
11571
+ { name: "userId", type: "text", nullable: true },
11572
+ { name: "organizationId", type: "text", nullable: true },
11573
+ { name: "resourceId", type: "text", nullable: true },
11574
+ { name: "runId", type: "text", nullable: true },
11575
+ { name: "sessionId", type: "text", nullable: true },
11576
+ { name: "threadId", type: "text", nullable: true },
11577
+ { name: "requestId", type: "text", nullable: true },
11578
+ { name: "environment", type: "text", nullable: true },
11579
+ { name: "executionSource", type: "text", nullable: true },
11580
+ { name: "serviceName", type: "text", nullable: true },
11581
+ { name: "name", type: "text" },
11582
+ { name: "spanType", type: "text" },
11583
+ { name: "isEvent", type: "boolean", defaultSql: "false" },
11584
+ { name: "startedAt", type: "timestamptz" },
11585
+ { name: "endedAt", type: "timestamptz" },
11586
+ { name: "tags", type: "text[]", defaultSql: "'{}'" },
11587
+ { name: "metadataSearch", type: "jsonb", defaultSql: "'{}'::jsonb" },
11588
+ { name: "attributes", type: "jsonb", nullable: true },
11589
+ { name: "scope", type: "jsonb", nullable: true },
11590
+ { name: "links", type: "jsonb", nullable: true },
11591
+ { name: "input", type: "jsonb", nullable: true },
11592
+ { name: "output", type: "jsonb", nullable: true },
11593
+ { name: "error", type: "jsonb", nullable: true },
11594
+ { name: "metadataRaw", type: "jsonb", nullable: true },
11595
+ { name: "requestContext", type: "jsonb", nullable: true }
11596
+ ];
11597
+ var METRIC_EVENT_COLUMNS = [
11598
+ CURSOR_ID_COLUMN,
11599
+ XACT_ID_COLUMN,
11600
+ { name: "metricId", type: "text" },
11601
+ { name: "timestamp", type: "timestamptz" },
11602
+ { name: "name", type: "text" },
11603
+ { name: "value", type: "double precision" },
11604
+ ...COMMON_CONTEXT_COLUMNS,
11605
+ { name: "provider", type: "text", nullable: true },
11606
+ { name: "model", type: "text", nullable: true },
11607
+ { name: "estimatedCost", type: "double precision", nullable: true },
11608
+ { name: "costUnit", type: "text", nullable: true },
11609
+ { name: "tags", type: "text[]", defaultSql: "'{}'" },
11610
+ { name: "labels", type: "jsonb", defaultSql: "'{}'::jsonb" },
11611
+ { name: "costMetadata", type: "jsonb", nullable: true },
11612
+ { name: "metadata", type: "jsonb", nullable: true },
11613
+ { name: "scope", type: "jsonb", nullable: true }
11614
+ ];
11615
+ var LOG_EVENT_COLUMNS = [
11616
+ CURSOR_ID_COLUMN,
11617
+ XACT_ID_COLUMN,
11618
+ { name: "logId", type: "text" },
11619
+ { name: "timestamp", type: "timestamptz" },
11620
+ { name: "level", type: "text" },
11621
+ { name: "message", type: "text" },
11622
+ ...COMMON_CONTEXT_COLUMNS,
11623
+ { name: "tags", type: "text[]", defaultSql: "'{}'" },
11624
+ { name: "data", type: "jsonb", nullable: true },
11625
+ { name: "metadata", type: "jsonb", nullable: true },
11626
+ { name: "scope", type: "jsonb", nullable: true }
11627
+ ];
11628
+ var SCORE_EVENT_COLUMNS = [
11629
+ CURSOR_ID_COLUMN,
11630
+ XACT_ID_COLUMN,
11631
+ { name: "scoreId", type: "text" },
11632
+ { name: "timestamp", type: "timestamptz" },
11633
+ { name: "scorerId", type: "text" },
11634
+ { name: "scorerVersion", type: "text", nullable: true },
11635
+ { name: "scoreSource", type: "text", nullable: true },
11636
+ { name: "score", type: "double precision" },
11637
+ { name: "reason", type: "text", nullable: true },
11638
+ ...COMMON_CONTEXT_COLUMNS,
11639
+ { name: "scoreTraceId", type: "text", nullable: true },
11640
+ { name: "tags", type: "text[]", defaultSql: "'{}'" },
11641
+ { name: "metadata", type: "jsonb", nullable: true },
11642
+ { name: "scope", type: "jsonb", nullable: true }
11643
+ ];
11644
+ var FEEDBACK_EVENT_COLUMNS = [
11645
+ CURSOR_ID_COLUMN,
11646
+ XACT_ID_COLUMN,
11647
+ { name: "feedbackId", type: "text" },
11648
+ { name: "timestamp", type: "timestamptz" },
11649
+ { name: "feedbackSource", type: "text" },
11650
+ { name: "feedbackType", type: "text" },
11651
+ { name: "valueString", type: "text", nullable: true },
11652
+ { name: "valueNumber", type: "double precision", nullable: true },
11653
+ { name: "comment", type: "text", nullable: true },
11654
+ { name: "feedbackUserId", type: "text", nullable: true },
11655
+ { name: "sourceId", type: "text", nullable: true },
11656
+ ...COMMON_CONTEXT_COLUMNS,
11657
+ { name: "tags", type: "text[]", defaultSql: "'{}'" },
11658
+ { name: "metadata", type: "jsonb", nullable: true },
11659
+ { name: "scope", type: "jsonb", nullable: true }
11660
+ ];
11661
+ var SPAN_LIGHT_SELECT_COLUMN_NAMES = [
11662
+ "cursorId",
11663
+ "xactId",
11664
+ "traceId",
11665
+ "spanId",
11666
+ "parentSpanId",
11667
+ "name",
11668
+ "entityType",
11669
+ "entityId",
11670
+ "entityName",
11671
+ "spanType",
11672
+ "error",
11673
+ "isEvent",
11674
+ "startedAt",
11675
+ "endedAt"
11676
+ ];
11677
+ function quotedColumnName(name) {
11678
+ return `"${name}"`;
11679
+ }
11680
+ function columnDefinition(column) {
11681
+ const nullable = column.nullable ? "" : " NOT NULL";
11682
+ const defaultSql = column.defaultSql ? ` DEFAULT ${column.defaultSql}` : "";
11683
+ return ` ${quotedColumnName(column.name)} ${column.type}${nullable}${defaultSql}`;
11684
+ }
11685
+ function buildColumnDefinitions(columns) {
11686
+ return columns.map(columnDefinition).join(",\n");
11687
+ }
11688
+ function buildSelectColumns(columns) {
11689
+ return `
11690
+ ${columns.map((column) => quotedColumnName(column.name)).join(",\n ")}
11691
+ `;
11692
+ }
11693
+ function buildNamedSelectColumns(columnNames) {
11694
+ return `
11695
+ ${columnNames.map(quotedColumnName).join(",\n ")}
11696
+ `;
11697
+ }
11698
+ function columnNamesByType(columns, type) {
11699
+ return columns.filter((column) => column.type === type).map((column) => column.name);
11700
+ }
11701
+ function typedColumnNames(columns) {
11702
+ return new Set(
11703
+ columns.filter((column) => !["bigserial", "jsonb", "text[]", "xid8"].includes(column.type)).map((column) => column.name)
11704
+ );
11705
+ }
11706
+ var ALL_EVENT_COLUMNS = [
11707
+ ...SPAN_EVENT_COLUMNS,
11708
+ ...METRIC_EVENT_COLUMNS,
11709
+ ...LOG_EVENT_COLUMNS,
11710
+ ...SCORE_EVENT_COLUMNS,
11711
+ ...FEEDBACK_EVENT_COLUMNS
11712
+ ];
11713
+ var JSONB_COLUMNS = new Set(columnNamesByType(ALL_EVENT_COLUMNS, "jsonb"));
11714
+ var TEXT_ARRAY_COLUMNS = new Set(columnNamesByType(ALL_EVENT_COLUMNS, "text[]"));
11715
+ var METRIC_TYPED_COLUMNS = typedColumnNames(METRIC_EVENT_COLUMNS);
11716
+ var SCORE_TYPED_COLUMNS = typedColumnNames(SCORE_EVENT_COLUMNS);
11717
+ var FEEDBACK_TYPED_COLUMNS = typedColumnNames(FEEDBACK_EVENT_COLUMNS);
11718
+
11719
+ // src/storage/domains/observability/v-next/ddl.ts
11720
+ var TABLE_SPAN_EVENTS = "mastra_span_events";
11721
+ var TABLE_METRIC_EVENTS = "mastra_metric_events";
11722
+ var TABLE_LOG_EVENTS = "mastra_log_events";
11723
+ var TABLE_SCORE_EVENTS = "mastra_score_events";
11724
+ var TABLE_FEEDBACK_EVENTS = "mastra_feedback_events";
11725
+ var TABLE_DISCOVERY = "mastra_observability_discovery";
11726
+ var ALL_SIGNAL_TABLES = [
11727
+ TABLE_SPAN_EVENTS,
11728
+ TABLE_METRIC_EVENTS,
11729
+ TABLE_LOG_EVENTS,
11730
+ TABLE_SCORE_EVENTS,
11731
+ TABLE_FEEDBACK_EVENTS
11732
+ ];
11733
+ var SIGNAL_TIME_COLUMN = {
11734
+ [TABLE_SPAN_EVENTS]: "endedAt",
11735
+ [TABLE_METRIC_EVENTS]: "timestamp",
11736
+ [TABLE_LOG_EVENTS]: "timestamp",
11737
+ [TABLE_SCORE_EVENTS]: "timestamp",
11738
+ [TABLE_FEEDBACK_EVENTS]: "timestamp"
11739
+ };
11740
+ function qualifiedTable(schema, table) {
11741
+ const s = parseSqlIdentifier(schema, "schema name");
11742
+ const t = parseSqlIdentifier(table, "table name");
11743
+ return `"${s}"."${t}"`;
11744
+ }
11745
+ function qualifiedName(schema, name) {
11746
+ const s = parseSqlIdentifier(schema, "schema name");
11747
+ const n = parseSqlIdentifier(name, "object name");
11748
+ return `"${s}"."${n}"`;
11749
+ }
11750
+ function schemaDDL(schema) {
11751
+ const s = parseSqlIdentifier(schema, "schema name");
11752
+ return `CREATE SCHEMA IF NOT EXISTS "${s}"`;
11753
+ }
11754
+ function partitionClause(mode, column) {
11755
+ return mode === "timescale" ? "" : `PARTITION BY RANGE ("${column}")`;
11756
+ }
11757
+ function spanEventsTableDDL(schema, mode) {
11758
+ return `
11759
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_SPAN_EVENTS)} (
11760
+ ${buildColumnDefinitions(SPAN_EVENT_COLUMNS)},
11761
+ PRIMARY KEY ("traceId", "spanId", "endedAt")
11762
+ )
11763
+ ${partitionClause(mode, "endedAt")}
11764
+ `.trim();
11765
+ }
11766
+ function metricEventsTableDDL(schema, mode) {
11767
+ return `
11768
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_METRIC_EVENTS)} (
11769
+ ${buildColumnDefinitions(METRIC_EVENT_COLUMNS)},
11770
+ PRIMARY KEY ("metricId", "timestamp")
11771
+ )
11772
+ ${partitionClause(mode, "timestamp")}
11773
+ `.trim();
11774
+ }
11775
+ function logEventsTableDDL(schema, mode) {
11776
+ return `
11777
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_LOG_EVENTS)} (
11778
+ ${buildColumnDefinitions(LOG_EVENT_COLUMNS)},
11779
+ PRIMARY KEY ("logId", "timestamp")
11780
+ )
11781
+ ${partitionClause(mode, "timestamp")}
11782
+ `.trim();
11783
+ }
11784
+ function scoreEventsTableDDL(schema, mode) {
11785
+ return `
11786
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_SCORE_EVENTS)} (
11787
+ ${buildColumnDefinitions(SCORE_EVENT_COLUMNS)},
11788
+ PRIMARY KEY ("scoreId", "timestamp")
11789
+ )
11790
+ ${partitionClause(mode, "timestamp")}
11791
+ `.trim();
11792
+ }
11793
+ function feedbackEventsTableDDL(schema, mode) {
11794
+ return `
11795
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)} (
11796
+ ${buildColumnDefinitions(FEEDBACK_EVENT_COLUMNS)},
11797
+ PRIMARY KEY ("feedbackId", "timestamp")
11798
+ )
11799
+ ${partitionClause(mode, "timestamp")}
11800
+ `.trim();
11801
+ }
11802
+ function discoveryTableDDL(schema) {
11803
+ return `
11804
+ CREATE TABLE IF NOT EXISTS ${qualifiedTable(schema, TABLE_DISCOVERY)} (
11805
+ "cacheKey" text PRIMARY KEY,
11806
+ "refreshedAt" timestamptz NOT NULL,
11807
+ "values" jsonb NOT NULL DEFAULT '[]'::jsonb
11808
+ )
11809
+ `.trim();
11810
+ }
11811
+ var ROOT_SPAN_WHERE = '"parentSpanId" IS NULL';
11812
+ function tableIndexes() {
11813
+ return [
11814
+ // span_events — full-table indexes used by getTrace / getSpan
11815
+ { name: "mastra_span_events_traceid_idx", table: TABLE_SPAN_EVENTS, columns: '("traceId", "endedAt" DESC)' },
11816
+ {
11817
+ name: "mastra_span_events_parentspan_idx",
11818
+ table: TABLE_SPAN_EVENTS,
11819
+ columns: '("parentSpanId", "endedAt" DESC)'
11820
+ },
11821
+ { name: "mastra_span_events_name_idx", table: TABLE_SPAN_EVENTS, columns: '("name")' },
11822
+ // Used by listBranches page mode (filter by spanType, order by startedAt).
11823
+ { name: "mastra_span_events_spantype_idx", table: TABLE_SPAN_EVENTS, columns: '("spanType", "startedAt" DESC)' },
11824
+ { name: "mastra_span_events_entity_idx", table: TABLE_SPAN_EVENTS, columns: '("entityType", "entityId")' },
11825
+ {
11826
+ name: "mastra_span_events_orgid_userid_idx",
11827
+ table: TABLE_SPAN_EVENTS,
11828
+ columns: '("organizationId", "userId")'
11829
+ },
11830
+ {
11831
+ name: "mastra_span_events_metadatasearch_gin",
11832
+ table: TABLE_SPAN_EVENTS,
11833
+ columns: '("metadataSearch" jsonb_path_ops)',
11834
+ using: "gin"
11835
+ },
11836
+ { name: "mastra_span_events_tags_gin", table: TABLE_SPAN_EVENTS, columns: '("tags")', using: "gin" },
11837
+ // span_events — partial indexes acting as the root-span projection. The
11838
+ // listTraces filter surface (startedAt / spanType / entityType / etc.) is
11839
+ // covered by these; rows where parentSpanId IS NOT NULL are excluded from
11840
+ // the index, so the index is the size of a separate trace_roots table.
11841
+ {
11842
+ name: "mastra_span_events_root_startedat_idx",
11843
+ table: TABLE_SPAN_EVENTS,
11844
+ columns: '("startedAt" DESC)',
11845
+ where: ROOT_SPAN_WHERE
11846
+ },
11847
+ {
11848
+ name: "mastra_span_events_root_endedat_idx",
11849
+ table: TABLE_SPAN_EVENTS,
11850
+ columns: '("endedAt" DESC)',
11851
+ where: ROOT_SPAN_WHERE
11852
+ },
11853
+ {
11854
+ name: "mastra_span_events_root_spantype_idx",
11855
+ table: TABLE_SPAN_EVENTS,
11856
+ columns: '("spanType", "startedAt" DESC)',
11857
+ where: ROOT_SPAN_WHERE
11858
+ },
11859
+ {
11860
+ name: "mastra_span_events_root_entityname_idx",
11861
+ table: TABLE_SPAN_EVENTS,
11862
+ columns: '("entityType", "entityName", "startedAt" DESC)',
11863
+ where: ROOT_SPAN_WHERE
11864
+ },
11865
+ {
11866
+ name: "mastra_span_events_root_traceid_idx",
11867
+ table: TABLE_SPAN_EVENTS,
11868
+ columns: '("traceId")',
11869
+ where: ROOT_SPAN_WHERE
11870
+ },
11871
+ // Delta polling: transaction-safe cursor ordering. Full-table coverage so the same index
11872
+ // serves both listTraces (combined with the `parentSpanId IS NULL`
11873
+ // predicate) and listBranches (combined with `spanType IN (...)`).
11874
+ {
11875
+ name: "mastra_span_events_cursor_idx",
11876
+ table: TABLE_SPAN_EVENTS,
11877
+ columns: '("xactId", "cursorId")'
11878
+ },
11879
+ // metric_events
11880
+ { name: "mastra_metric_events_name_ts_idx", table: TABLE_METRIC_EVENTS, columns: '("name", "timestamp" DESC)' },
11881
+ {
11882
+ name: "mastra_metric_events_entity_idx",
11883
+ table: TABLE_METRIC_EVENTS,
11884
+ columns: '("entityType", "entityId", "timestamp" DESC)'
11885
+ },
11886
+ { name: "mastra_metric_events_traceid_idx", table: TABLE_METRIC_EVENTS, columns: '("traceId")' },
11887
+ { name: "mastra_metric_events_labels_gin", table: TABLE_METRIC_EVENTS, columns: '("labels")', using: "gin" },
11888
+ { name: "mastra_metric_events_tags_gin", table: TABLE_METRIC_EVENTS, columns: '("tags")', using: "gin" },
11889
+ { name: "mastra_metric_events_cursor_idx", table: TABLE_METRIC_EVENTS, columns: '("xactId", "cursorId")' },
11890
+ // log_events
11891
+ { name: "mastra_log_events_ts_idx", table: TABLE_LOG_EVENTS, columns: '("timestamp" DESC)' },
11892
+ { name: "mastra_log_events_level_ts_idx", table: TABLE_LOG_EVENTS, columns: '("level", "timestamp" DESC)' },
11893
+ { name: "mastra_log_events_traceid_idx", table: TABLE_LOG_EVENTS, columns: '("traceId")' },
11894
+ {
11895
+ name: "mastra_log_events_entity_idx",
11896
+ table: TABLE_LOG_EVENTS,
11897
+ columns: '("entityType", "entityId", "timestamp" DESC)'
11898
+ },
11899
+ { name: "mastra_log_events_tags_gin", table: TABLE_LOG_EVENTS, columns: '("tags")', using: "gin" },
11900
+ { name: "mastra_log_events_cursor_idx", table: TABLE_LOG_EVENTS, columns: '("xactId", "cursorId")' },
11901
+ // score_events
11902
+ { name: "mastra_score_events_traceid_idx", table: TABLE_SCORE_EVENTS, columns: '("traceId", "timestamp" DESC)' },
11903
+ { name: "mastra_score_events_scorerid_idx", table: TABLE_SCORE_EVENTS, columns: '("scorerId", "timestamp" DESC)' },
11904
+ {
11905
+ name: "mastra_score_events_entity_idx",
11906
+ table: TABLE_SCORE_EVENTS,
11907
+ columns: '("entityType", "entityId", "timestamp" DESC)'
11908
+ },
11909
+ { name: "mastra_score_events_tags_gin", table: TABLE_SCORE_EVENTS, columns: '("tags")', using: "gin" },
11910
+ { name: "mastra_score_events_cursor_idx", table: TABLE_SCORE_EVENTS, columns: '("xactId", "cursorId")' },
11911
+ // feedback_events
11912
+ {
11913
+ name: "mastra_feedback_events_traceid_idx",
11914
+ table: TABLE_FEEDBACK_EVENTS,
11915
+ columns: '("traceId", "timestamp" DESC)'
11916
+ },
11917
+ {
11918
+ name: "mastra_feedback_events_type_idx",
11919
+ table: TABLE_FEEDBACK_EVENTS,
11920
+ columns: '("feedbackType", "timestamp" DESC)'
11921
+ },
11922
+ {
11923
+ name: "mastra_feedback_events_entity_idx",
11924
+ table: TABLE_FEEDBACK_EVENTS,
11925
+ columns: '("entityType", "entityId", "timestamp" DESC)'
11926
+ },
11927
+ { name: "mastra_feedback_events_tags_gin", table: TABLE_FEEDBACK_EVENTS, columns: '("tags")', using: "gin" },
11928
+ { name: "mastra_feedback_events_cursor_idx", table: TABLE_FEEDBACK_EVENTS, columns: '("xactId", "cursorId")' }
11929
+ ];
11930
+ }
11931
+ function indexDDL(schema, spec) {
11932
+ const idxName = parseSqlIdentifier(spec.name, "index name");
11933
+ const using = spec.using ? `USING ${spec.using}` : "";
11934
+ const where = spec.where ? `WHERE ${spec.where}` : "";
11935
+ return `CREATE INDEX IF NOT EXISTS "${idxName}" ON ${qualifiedTable(schema, spec.table)} ${using} ${spec.columns} ${where}`.replace(
11936
+ /\s+/g,
11937
+ " "
11938
+ );
11939
+ }
11940
+ function allTableDDL(schema, mode) {
11941
+ return [
11942
+ spanEventsTableDDL(schema, mode),
11943
+ metricEventsTableDDL(schema, mode),
11944
+ logEventsTableDDL(schema, mode),
11945
+ scoreEventsTableDDL(schema, mode),
11946
+ feedbackEventsTableDDL(schema, mode),
11947
+ discoveryTableDDL(schema)
11948
+ ];
11949
+ }
11950
+ function allIndexDDL(schema) {
11951
+ return tableIndexes().map((spec) => indexDDL(schema, spec));
11952
+ }
11953
+ var DEFAULT_TTL_SECONDS = 5 * 60;
11954
+ var SIGNAL_TABLES_WITH_CONTEXT = [
11955
+ TABLE_SPAN_EVENTS,
11956
+ TABLE_METRIC_EVENTS,
11957
+ TABLE_LOG_EVENTS,
11958
+ TABLE_SCORE_EVENTS,
11959
+ TABLE_FEEDBACK_EVENTS
11960
+ ];
11961
+ var ENTITY_DISCOVERY_TABLES = [TABLE_SPAN_EVENTS, TABLE_METRIC_EVENTS, TABLE_LOG_EVENTS];
11962
+ var inFlightRefreshes = /* @__PURE__ */ new Map();
11963
+ function startOrJoinRefresh(dedupeKey, cacheKey, refresh, upsert, logger) {
11964
+ const existing = inFlightRefreshes.get(dedupeKey);
11965
+ if (existing) return existing;
11966
+ const promise = (async () => {
11967
+ try {
11968
+ const values = await refresh();
11969
+ await upsert(values);
11970
+ return values;
11971
+ } catch (error) {
11972
+ const message = `[observability/v-next] background refresh failed for discovery cache key "${cacheKey}"`;
11973
+ if (logger) {
11974
+ logger.warn(message, { error });
11975
+ } else {
11976
+ console.warn(message + ":", error);
11467
11977
  }
11468
- ];
11469
- }
11470
- /**
11471
- * Returns all DDL statements for this domain: tables and indexes.
11472
- * Used by exportSchemas to produce a complete, reproducible schema export.
11473
- */
11474
- static getExportDDL(schemaName) {
11475
- const statements = [];
11476
- const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
11477
- const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
11478
- for (const tableName of _PromptBlocksPG.MANAGED_TABLES) {
11479
- statements.push(
11480
- generateTableSQL({
11481
- tableName,
11482
- schema: TABLE_SCHEMAS[tableName],
11483
- schemaName,
11484
- includeAllConstraints: true
11485
- })
11486
- );
11978
+ throw error;
11979
+ } finally {
11980
+ inFlightRefreshes.delete(dedupeKey);
11487
11981
  }
11488
- for (const idx of _PromptBlocksPG.getDefaultIndexDefs(schemaPrefix)) {
11489
- statements.push(generateIndexSQL(idx, schemaName));
11982
+ })();
11983
+ inFlightRefreshes.set(dedupeKey, promise);
11984
+ return promise;
11985
+ }
11986
+ async function readWithRefresh(client, schema, cacheKey, refresh, ttlSeconds, logger) {
11987
+ const table = qualifiedTable(schema, TABLE_DISCOVERY);
11988
+ const row = await client.oneOrNone(
11989
+ `SELECT "values", "refreshedAt" FROM ${table} WHERE "cacheKey" = $1`,
11990
+ [cacheKey]
11991
+ );
11992
+ const refreshedAtMs = row ? new Date(row.refreshedAt).getTime() : 0;
11993
+ const stale = !row || Date.now() - refreshedAtMs > ttlSeconds * 1e3;
11994
+ if (!stale) return row.values;
11995
+ const dedupeKey = `${schema}:${cacheKey}`;
11996
+ const refreshing = startOrJoinRefresh(
11997
+ dedupeKey,
11998
+ cacheKey,
11999
+ refresh,
12000
+ (values) => upsertCache(client, schema, cacheKey, values),
12001
+ logger
12002
+ );
12003
+ if (ttlSeconds <= 0) {
12004
+ try {
12005
+ return await refreshing;
12006
+ } catch {
12007
+ return row?.values ?? [];
11490
12008
  }
11491
- return statements;
11492
- }
11493
- getDefaultIndexDefinitions() {
11494
- const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
11495
- return _PromptBlocksPG.getDefaultIndexDefs(schemaPrefix);
11496
12009
  }
11497
- async createDefaultIndexes() {
11498
- if (this.#skipDefaultIndexes) {
11499
- return;
11500
- }
11501
- for (const indexDef of this.getDefaultIndexDefinitions()) {
11502
- try {
11503
- await this.#db.createIndex(indexDef);
11504
- } catch {
11505
- }
12010
+ if (!row) {
12011
+ try {
12012
+ return await refreshing;
12013
+ } catch {
12014
+ return [];
11506
12015
  }
11507
12016
  }
11508
- async init() {
11509
- await this.#db.createTable({ tableName: TABLE_PROMPT_BLOCKS, schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCKS] });
11510
- await this.#db.createTable({
11511
- tableName: TABLE_PROMPT_BLOCK_VERSIONS,
11512
- schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCK_VERSIONS]
11513
- });
11514
- await this.#db.alterTable({
11515
- tableName: TABLE_PROMPT_BLOCK_VERSIONS,
11516
- schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCK_VERSIONS],
11517
- ifNotExists: ["requestContextSchema"]
11518
- });
11519
- await this.createDefaultIndexes();
11520
- await this.createCustomIndexes();
12017
+ refreshing.catch(() => {
12018
+ });
12019
+ return row.values;
12020
+ }
12021
+ async function upsertCache(client, schema, cacheKey, values) {
12022
+ const table = qualifiedTable(schema, TABLE_DISCOVERY);
12023
+ await client.query(
12024
+ `INSERT INTO ${table} ("cacheKey", "refreshedAt", "values")
12025
+ VALUES ($1, NOW(), $2::jsonb)
12026
+ ON CONFLICT ("cacheKey") DO UPDATE SET
12027
+ "refreshedAt" = EXCLUDED."refreshedAt",
12028
+ "values" = EXCLUDED."values"`,
12029
+ [cacheKey, JSON.stringify(values)]
12030
+ );
12031
+ }
12032
+ async function distinctAcrossTables(client, schema, column, tables, filterSql = "", filterParams = []) {
12033
+ const safeColumn = parseSqlIdentifier(column, "column name");
12034
+ const unions = tables.map(
12035
+ (t) => `SELECT DISTINCT "${safeColumn}" AS v FROM ${qualifiedTable(schema, t)} WHERE "${safeColumn}" IS NOT NULL AND "${safeColumn}" <> '' ${filterSql}`
12036
+ ).join(" UNION ");
12037
+ const rows = await client.manyOrNone(`SELECT v FROM (${unions}) sub ORDER BY v`, filterParams);
12038
+ return rows.map((r) => r.v);
12039
+ }
12040
+ async function getEntityTypes(client, schema, _args, config) {
12041
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12042
+ const values = await readWithRefresh(
12043
+ client,
12044
+ schema,
12045
+ "entity_types",
12046
+ () => distinctAcrossTables(client, schema, "entityType", ENTITY_DISCOVERY_TABLES),
12047
+ ttl,
12048
+ config.logger
12049
+ );
12050
+ return { entityTypes: values };
12051
+ }
12052
+ async function getEntityNames(client, schema, args, config) {
12053
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12054
+ const cacheKey = args.entityType ? `entity_names:${args.entityType}` : "entity_names";
12055
+ const filterSql = args.entityType ? `AND "entityType" = $1` : "";
12056
+ const filterParams = args.entityType ? [args.entityType] : [];
12057
+ const values = await readWithRefresh(
12058
+ client,
12059
+ schema,
12060
+ cacheKey,
12061
+ () => distinctAcrossTables(client, schema, "entityName", ENTITY_DISCOVERY_TABLES, filterSql, filterParams),
12062
+ ttl,
12063
+ config.logger
12064
+ );
12065
+ return { names: values };
12066
+ }
12067
+ async function getServiceNames(client, schema, _args, config) {
12068
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12069
+ const values = await readWithRefresh(
12070
+ client,
12071
+ schema,
12072
+ "service_names",
12073
+ () => distinctAcrossTables(client, schema, "serviceName", SIGNAL_TABLES_WITH_CONTEXT),
12074
+ ttl,
12075
+ config.logger
12076
+ );
12077
+ return { serviceNames: values };
12078
+ }
12079
+ async function getEnvironments(client, schema, _args, config) {
12080
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12081
+ const values = await readWithRefresh(
12082
+ client,
12083
+ schema,
12084
+ "environments",
12085
+ () => distinctAcrossTables(client, schema, "environment", SIGNAL_TABLES_WITH_CONTEXT),
12086
+ ttl,
12087
+ config.logger
12088
+ );
12089
+ return { environments: values };
12090
+ }
12091
+ async function getTags(client, schema, args, config) {
12092
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12093
+ const cacheKey = args.entityType ? `tags:${args.entityType}` : "tags";
12094
+ const refresh = async () => {
12095
+ const filter = args.entityType ? `AND "entityType" = $1` : "";
12096
+ const params = args.entityType ? [args.entityType] : [];
12097
+ const unions = ENTITY_DISCOVERY_TABLES.map(
12098
+ (t) => `SELECT DISTINCT UNNEST("tags") AS v FROM ${qualifiedTable(schema, t)} WHERE array_length("tags", 1) > 0 ${filter}`
12099
+ ).join(" UNION ");
12100
+ const rows = await client.manyOrNone(
12101
+ `SELECT v FROM (${unions}) sub WHERE v IS NOT NULL AND v <> '' ORDER BY v`,
12102
+ params
12103
+ );
12104
+ return rows.map((r) => r.v);
12105
+ };
12106
+ const values = await readWithRefresh(client, schema, cacheKey, refresh, ttl, config.logger);
12107
+ return { tags: values };
12108
+ }
12109
+ async function getMetricNames(client, schema, args, config) {
12110
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12111
+ const values = await readWithRefresh(
12112
+ client,
12113
+ schema,
12114
+ "metric_names",
12115
+ async () => {
12116
+ const rows = await client.manyOrNone(
12117
+ `SELECT DISTINCT "name" AS v FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
12118
+ WHERE "name" IS NOT NULL AND "name" <> '' ORDER BY "name"`
12119
+ );
12120
+ return rows.map((r) => r.v);
12121
+ },
12122
+ ttl,
12123
+ config.logger
12124
+ );
12125
+ let filtered = values;
12126
+ if (args.prefix) filtered = filtered.filter((v) => v.startsWith(args.prefix));
12127
+ if (args.limit) filtered = filtered.slice(0, args.limit);
12128
+ return { names: filtered };
12129
+ }
12130
+ async function getMetricLabelKeys(client, schema, args, config) {
12131
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12132
+ const cacheKey = `metric_label_keys:${args.metricName}`;
12133
+ const values = await readWithRefresh(
12134
+ client,
12135
+ schema,
12136
+ cacheKey,
12137
+ async () => {
12138
+ const rows = await client.manyOrNone(
12139
+ `SELECT DISTINCT k AS v
12140
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}, jsonb_object_keys("labels") k
12141
+ WHERE "name" = $1 ORDER BY k`,
12142
+ [args.metricName]
12143
+ );
12144
+ return rows.map((r) => r.v);
12145
+ },
12146
+ ttl,
12147
+ config.logger
12148
+ );
12149
+ return { keys: values };
12150
+ }
12151
+ async function getMetricLabelValues(client, schema, args, config) {
12152
+ const ttl = config.ttlSeconds ?? DEFAULT_TTL_SECONDS;
12153
+ const cacheKey = `metric_label_values:${args.metricName}:${args.labelKey}`;
12154
+ const values = await readWithRefresh(
12155
+ client,
12156
+ schema,
12157
+ cacheKey,
12158
+ async () => {
12159
+ const rows = await client.manyOrNone(
12160
+ `SELECT DISTINCT "labels" ->> $2 AS v
12161
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
12162
+ WHERE "name" = $1 AND "labels" ? $2
12163
+ ORDER BY v`,
12164
+ [args.metricName, args.labelKey]
12165
+ );
12166
+ return rows.map((r) => r.v).filter((v) => v != null && v !== "");
12167
+ },
12168
+ ttl,
12169
+ config.logger
12170
+ );
12171
+ let filtered = values;
12172
+ if (args.prefix) filtered = filtered.filter((v) => v.startsWith(args.prefix));
12173
+ if (args.limit) filtered = filtered.slice(0, args.limit);
12174
+ return { values: filtered };
12175
+ }
12176
+
12177
+ // src/storage/domains/observability/v-next/filters.ts
12178
+ function newFilterAccumulator(startIndex = 1) {
12179
+ return { conditions: [], params: [], next: startIndex };
12180
+ }
12181
+ function pushEq(acc, column, value, prefix = "") {
12182
+ if (value === void 0) return;
12183
+ acc.conditions.push(`${prefix}"${column}" = $${acc.next++}`);
12184
+ acc.params.push(value);
12185
+ }
12186
+ function pushIn(acc, column, values, prefix = "") {
12187
+ if (!values.length) return;
12188
+ const placeholders = values.map(() => `$${acc.next++}`).join(", ");
12189
+ acc.conditions.push(`${prefix}"${column}" IN (${placeholders})`);
12190
+ acc.params.push(...values);
12191
+ }
12192
+ function applyCommonFilters(acc, filters, options = {}) {
12193
+ if (!filters) return;
12194
+ const tsCol = options.timestampColumn ?? "timestamp";
12195
+ const prefix = options.prefix ?? "";
12196
+ if (filters.timestamp?.start) {
12197
+ const op = filters.timestamp.startExclusive ? ">" : ">=";
12198
+ acc.conditions.push(`${prefix}"${tsCol}" ${op} $${acc.next++}`);
12199
+ acc.params.push(filters.timestamp.start.toISOString());
12200
+ }
12201
+ if (filters.timestamp?.end) {
12202
+ const op = filters.timestamp.endExclusive ? "<" : "<=";
12203
+ acc.conditions.push(`${prefix}"${tsCol}" ${op} $${acc.next++}`);
12204
+ acc.params.push(filters.timestamp.end.toISOString());
12205
+ }
12206
+ pushEq(acc, "traceId", filters.traceId, prefix);
12207
+ pushEq(acc, "spanId", filters.spanId, prefix);
12208
+ pushEq(acc, "entityType", filters.entityType, prefix);
12209
+ pushEq(acc, "entityName", filters.entityName, prefix);
12210
+ pushEq(acc, "entityVersionId", filters.entityVersionId, prefix);
12211
+ pushEq(acc, "parentEntityType", filters.parentEntityType, prefix);
12212
+ pushEq(acc, "parentEntityName", filters.parentEntityName, prefix);
12213
+ pushEq(acc, "parentEntityVersionId", filters.parentEntityVersionId, prefix);
12214
+ pushEq(acc, "rootEntityType", filters.rootEntityType, prefix);
12215
+ pushEq(acc, "rootEntityName", filters.rootEntityName, prefix);
12216
+ pushEq(acc, "rootEntityVersionId", filters.rootEntityVersionId, prefix);
12217
+ pushEq(acc, "userId", filters.userId, prefix);
12218
+ pushEq(acc, "organizationId", filters.organizationId, prefix);
12219
+ pushEq(acc, "resourceId", filters.resourceId, prefix);
12220
+ pushEq(acc, "runId", filters.runId, prefix);
12221
+ pushEq(acc, "sessionId", filters.sessionId, prefix);
12222
+ pushEq(acc, "threadId", filters.threadId, prefix);
12223
+ pushEq(acc, "requestId", filters.requestId, prefix);
12224
+ pushEq(acc, "experimentId", filters.experimentId, prefix);
12225
+ pushEq(acc, "environment", filters.environment, prefix);
12226
+ pushEq(acc, "serviceName", filters.serviceName, prefix);
12227
+ pushEq(acc, "executionSource", filters.executionSource ?? filters.source, prefix);
12228
+ if (filters.tags != null && Array.isArray(filters.tags) && filters.tags.length > 0) {
12229
+ acc.conditions.push(`${prefix}"tags" @> $${acc.next++}::text[]`);
12230
+ acc.params.push(filters.tags);
11521
12231
  }
11522
- async createCustomIndexes() {
11523
- if (!this.#indexes || this.#indexes.length === 0) {
11524
- return;
11525
- }
11526
- for (const indexDef of this.#indexes) {
11527
- try {
11528
- await this.#db.createIndex(indexDef);
11529
- } catch (error) {
11530
- this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
11531
- }
11532
- }
12232
+ }
12233
+ function applySingleOrArrayFilter(acc, column, value, prefix = "") {
12234
+ if (value === void 0) return;
12235
+ if (Array.isArray(value)) {
12236
+ pushIn(acc, column, value, prefix);
12237
+ } else {
12238
+ pushEq(acc, column, value, prefix);
11533
12239
  }
11534
- async dangerouslyClearAll() {
11535
- await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCK_VERSIONS });
11536
- await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCKS });
12240
+ }
12241
+ function whereOrEmpty(acc) {
12242
+ return acc.conditions.length ? `WHERE ${acc.conditions.join(" AND ")}` : "";
12243
+ }
12244
+ var PROMOTED_KEYS = /* @__PURE__ */ new Set([
12245
+ "experimentId",
12246
+ "entityType",
12247
+ "entityId",
12248
+ "entityName",
12249
+ "entityVersionId",
12250
+ "parentEntityVersionId",
12251
+ "rootEntityVersionId",
12252
+ "userId",
12253
+ "organizationId",
12254
+ "resourceId",
12255
+ "runId",
12256
+ "sessionId",
12257
+ "threadId",
12258
+ "requestId",
12259
+ "environment",
12260
+ "executionSource",
12261
+ "serviceName"
12262
+ ]);
12263
+ function nullableString(value) {
12264
+ if (typeof value === "string") return value === "" ? null : value;
12265
+ if (value == null) return null;
12266
+ return String(value);
12267
+ }
12268
+ function nullableEntityType(value) {
12269
+ const normalized = nullableString(value);
12270
+ if (!normalized) return null;
12271
+ return Object.values(EntityType).includes(normalized) ? normalized : null;
12272
+ }
12273
+ function normalizeTags(tags) {
12274
+ if (!Array.isArray(tags)) return [];
12275
+ const seen = /* @__PURE__ */ new Set();
12276
+ const result = [];
12277
+ for (const t of tags) {
12278
+ if (typeof t !== "string") continue;
12279
+ const trimmed = t.trim();
12280
+ if (trimmed === "" || seen.has(trimmed)) continue;
12281
+ seen.add(trimmed);
12282
+ result.push(trimmed);
11537
12283
  }
11538
- // ==========================================================================
11539
- // Prompt Block CRUD Methods
11540
- // ==========================================================================
11541
- async getById(id) {
11542
- try {
11543
- const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
11544
- const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
11545
- if (!result) {
11546
- return null;
11547
- }
11548
- return this.parseBlockRow(result);
11549
- } catch (error) {
11550
- if (error instanceof MastraError) throw error;
11551
- throw new MastraError(
11552
- {
11553
- id: createStorageErrorId("PG", "GET_PROMPT_BLOCK_BY_ID", "FAILED"),
11554
- domain: ErrorDomain.STORAGE,
11555
- category: ErrorCategory.THIRD_PARTY,
11556
- details: { blockId: id }
11557
- },
11558
- error
11559
- );
11560
- }
12284
+ return result;
12285
+ }
12286
+ function normalizeLabels(labels) {
12287
+ if (labels == null || typeof labels !== "object") return {};
12288
+ const result = {};
12289
+ for (const [k, v] of Object.entries(labels)) {
12290
+ if (typeof v !== "string") continue;
12291
+ const trimmedK = k.trim();
12292
+ const trimmedV = v.trim();
12293
+ if (trimmedK === "" || trimmedV === "") continue;
12294
+ result[trimmedK] = trimmedV;
11561
12295
  }
11562
- async create(input) {
11563
- const { promptBlock } = input;
11564
- try {
11565
- const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
11566
- const now = /* @__PURE__ */ new Date();
11567
- const nowIso = now.toISOString();
11568
- await this.#db.client.none(
11569
- `INSERT INTO ${tableName} (
12296
+ return result;
12297
+ }
12298
+ function buildMetadataSearch(metadata) {
12299
+ if (metadata == null || typeof metadata !== "object") return {};
12300
+ const result = {};
12301
+ for (const [k, v] of Object.entries(metadata)) {
12302
+ if (PROMOTED_KEYS.has(k)) continue;
12303
+ if (typeof v !== "string") continue;
12304
+ const trimmed = v.trim();
12305
+ if (trimmed === "") continue;
12306
+ result[k] = trimmed;
12307
+ }
12308
+ return result;
12309
+ }
12310
+ function toDate(value) {
12311
+ if (value instanceof Date) return value;
12312
+ if (value == null || value === "") throw new Error(`Invalid date: ${String(value)}`);
12313
+ const d = new Date(value);
12314
+ if (isNaN(d.getTime())) throw new Error(`Invalid date: ${String(value)}`);
12315
+ return d;
12316
+ }
12317
+ function toDateOrNull(value) {
12318
+ if (value == null || value === "") return null;
12319
+ if (value instanceof Date) return value;
12320
+ const d = new Date(value);
12321
+ if (isNaN(d.getTime())) return null;
12322
+ return d;
12323
+ }
12324
+ function toIsoOrDate(value) {
12325
+ if (value instanceof Date) return value;
12326
+ if (typeof value === "number") return new Date(value);
12327
+ return value;
12328
+ }
12329
+ function jsonField(value) {
12330
+ if (value === void 0) return null;
12331
+ return value;
12332
+ }
12333
+ function parsedJson(value) {
12334
+ if (value == null) return void 0;
12335
+ if (typeof value === "string") {
12336
+ try {
12337
+ return JSON.parse(value);
12338
+ } catch {
12339
+ return void 0;
12340
+ }
12341
+ }
12342
+ return value;
12343
+ }
12344
+ function rowToCommonContext(row) {
12345
+ return {
12346
+ experimentId: nullableString(row.experimentId),
12347
+ entityType: nullableEntityType(row.entityType),
12348
+ entityId: nullableString(row.entityId),
12349
+ entityName: nullableString(row.entityName),
12350
+ entityVersionId: nullableString(row.entityVersionId),
12351
+ parentEntityType: nullableEntityType(row.parentEntityType),
12352
+ parentEntityId: nullableString(row.parentEntityId),
12353
+ parentEntityName: nullableString(row.parentEntityName),
12354
+ parentEntityVersionId: nullableString(row.parentEntityVersionId),
12355
+ rootEntityType: nullableEntityType(row.rootEntityType),
12356
+ rootEntityId: nullableString(row.rootEntityId),
12357
+ rootEntityName: nullableString(row.rootEntityName),
12358
+ rootEntityVersionId: nullableString(row.rootEntityVersionId),
12359
+ userId: nullableString(row.userId),
12360
+ organizationId: nullableString(row.organizationId),
12361
+ resourceId: nullableString(row.resourceId),
12362
+ runId: nullableString(row.runId),
12363
+ sessionId: nullableString(row.sessionId),
12364
+ threadId: nullableString(row.threadId),
12365
+ requestId: nullableString(row.requestId),
12366
+ environment: nullableString(row.environment),
12367
+ executionSource: nullableString(row.executionSource),
12368
+ serviceName: nullableString(row.serviceName)
12369
+ };
12370
+ }
12371
+ function commonContextToRow(record) {
12372
+ return {
12373
+ experimentId: record.experimentId ?? null,
12374
+ entityType: record.entityType ?? null,
12375
+ entityId: record.entityId ?? null,
12376
+ entityName: record.entityName ?? null,
12377
+ entityVersionId: record.entityVersionId ?? null,
12378
+ parentEntityType: record.parentEntityType ?? null,
12379
+ parentEntityId: record.parentEntityId ?? null,
12380
+ parentEntityName: record.parentEntityName ?? null,
12381
+ parentEntityVersionId: record.parentEntityVersionId ?? null,
12382
+ rootEntityType: record.rootEntityType ?? null,
12383
+ rootEntityId: record.rootEntityId ?? null,
12384
+ rootEntityName: record.rootEntityName ?? null,
12385
+ rootEntityVersionId: record.rootEntityVersionId ?? null,
12386
+ userId: record.userId ?? null,
12387
+ organizationId: record.organizationId ?? null,
12388
+ resourceId: record.resourceId ?? null,
12389
+ runId: record.runId ?? null,
12390
+ sessionId: record.sessionId ?? null,
12391
+ threadId: record.threadId ?? null,
12392
+ requestId: record.requestId ?? null,
12393
+ environment: record.environment ?? null,
12394
+ executionSource: record.executionSource ?? record.source ?? null,
12395
+ serviceName: record.serviceName ?? null
12396
+ };
12397
+ }
12398
+ function spanRecordToRow(span) {
12399
+ const endedAt = span.isEvent ? span.startedAt : span.endedAt ?? span.startedAt;
12400
+ const metadata = span.metadata ?? null;
12401
+ return {
12402
+ ...commonContextToRow(span),
12403
+ traceId: span.traceId,
12404
+ spanId: span.spanId,
12405
+ parentSpanId: span.parentSpanId ?? null,
12406
+ name: span.name,
12407
+ spanType: span.spanType,
12408
+ isEvent: Boolean(span.isEvent),
12409
+ startedAt: toIsoOrDate(span.startedAt),
12410
+ endedAt: toIsoOrDate(endedAt),
12411
+ tags: normalizeTags(span.tags),
12412
+ metadataSearch: buildMetadataSearch(metadata),
12413
+ metadataRaw: jsonField(metadata),
12414
+ scope: jsonField(span.scope),
12415
+ attributes: jsonField(span.attributes),
12416
+ links: jsonField(span.links),
12417
+ input: jsonField(span.input),
12418
+ output: jsonField(span.output),
12419
+ error: jsonField(span.error),
12420
+ requestContext: jsonField(span.requestContext)
12421
+ };
12422
+ }
12423
+ function rowToSpanRecord(row) {
12424
+ const startedAt = toDate(row.startedAt);
12425
+ const endedAt = row.isEvent ? startedAt : toDateOrNull(row.endedAt);
12426
+ const error = parsedJson(row.error);
12427
+ const { executionSource, ...ctx } = rowToCommonContext(row);
12428
+ return {
12429
+ ...ctx,
12430
+ source: executionSource,
12431
+ traceId: row.traceId,
12432
+ spanId: row.spanId,
12433
+ parentSpanId: nullableString(row.parentSpanId),
12434
+ name: row.name,
12435
+ spanType: row.spanType,
12436
+ isEvent: Boolean(row.isEvent),
12437
+ startedAt,
12438
+ endedAt,
12439
+ tags: normalizeTags(row.tags),
12440
+ metadata: parsedJson(row.metadataRaw) ?? void 0,
12441
+ scope: parsedJson(row.scope) ?? void 0,
12442
+ attributes: parsedJson(row.attributes) ?? void 0,
12443
+ links: parsedJson(row.links) ?? void 0,
12444
+ input: parsedJson(row.input) ?? void 0,
12445
+ output: parsedJson(row.output) ?? void 0,
12446
+ error: error ?? void 0,
12447
+ requestContext: parsedJson(row.requestContext) ?? void 0,
12448
+ createdAt: startedAt,
12449
+ updatedAt: null
12450
+ };
12451
+ }
12452
+ function rowToLightSpanRecord(row) {
12453
+ const startedAt = toDate(row.startedAt);
12454
+ const endedAt = row.isEvent ? startedAt : toDateOrNull(row.endedAt);
12455
+ return {
12456
+ traceId: row.traceId,
12457
+ spanId: row.spanId,
12458
+ parentSpanId: row.parentSpanId == null || row.parentSpanId === "" ? null : String(row.parentSpanId),
12459
+ name: row.name,
12460
+ spanType: row.spanType,
12461
+ isEvent: Boolean(row.isEvent),
12462
+ startedAt,
12463
+ endedAt,
12464
+ entityType: row.entityType == null || row.entityType === "" ? null : Object.values(EntityType).includes(row.entityType) ? row.entityType : null,
12465
+ entityId: row.entityId == null || row.entityId === "" ? null : String(row.entityId),
12466
+ entityName: row.entityName == null || row.entityName === "" ? null : String(row.entityName),
12467
+ error: parsedJson(row.error) ?? void 0,
12468
+ createdAt: startedAt,
12469
+ updatedAt: null
12470
+ };
12471
+ }
12472
+ function logRecordToRow(log) {
12473
+ return {
12474
+ ...commonContextToRow(log),
12475
+ logId: log.logId,
12476
+ timestamp: toIsoOrDate(log.timestamp),
12477
+ level: log.level,
12478
+ message: log.message,
12479
+ data: jsonField(log.data),
12480
+ traceId: log.traceId ?? null,
12481
+ spanId: log.spanId ?? null,
12482
+ tags: normalizeTags(log.tags),
12483
+ metadata: jsonField(log.metadata),
12484
+ scope: jsonField(log.scope)
12485
+ };
12486
+ }
12487
+ function rowToLogRecord(row) {
12488
+ return {
12489
+ ...rowToCommonContext(row),
12490
+ logId: row.logId,
12491
+ timestamp: toDate(row.timestamp),
12492
+ level: row.level,
12493
+ message: row.message,
12494
+ data: parsedJson(row.data) ?? void 0,
12495
+ traceId: nullableString(row.traceId),
12496
+ spanId: nullableString(row.spanId),
12497
+ tags: normalizeTags(row.tags),
12498
+ metadata: parsedJson(row.metadata) ?? void 0,
12499
+ scope: parsedJson(row.scope) ?? void 0
12500
+ };
12501
+ }
12502
+ function metricRecordToRow(metric) {
12503
+ return {
12504
+ ...commonContextToRow(metric),
12505
+ metricId: metric.metricId,
12506
+ timestamp: toIsoOrDate(metric.timestamp),
12507
+ name: metric.name,
12508
+ value: metric.value,
12509
+ traceId: metric.traceId ?? null,
12510
+ spanId: metric.spanId ?? null,
12511
+ provider: metric.provider ?? null,
12512
+ model: metric.model ?? null,
12513
+ estimatedCost: metric.estimatedCost ?? null,
12514
+ costUnit: metric.costUnit ?? null,
12515
+ tags: normalizeTags(metric.tags),
12516
+ labels: normalizeLabels(metric.labels),
12517
+ costMetadata: jsonField(metric.costMetadata),
12518
+ metadata: jsonField(metric.metadata),
12519
+ scope: jsonField(metric.scope)
12520
+ };
12521
+ }
12522
+ function rowToMetricRecord(row) {
12523
+ return {
12524
+ ...rowToCommonContext(row),
12525
+ metricId: row.metricId,
12526
+ timestamp: toDate(row.timestamp),
12527
+ name: row.name,
12528
+ value: Number(row.value),
12529
+ traceId: nullableString(row.traceId),
12530
+ spanId: nullableString(row.spanId),
12531
+ provider: nullableString(row.provider),
12532
+ model: nullableString(row.model),
12533
+ estimatedCost: row.estimatedCost == null ? void 0 : Number(row.estimatedCost),
12534
+ costUnit: nullableString(row.costUnit),
12535
+ costMetadata: parsedJson(row.costMetadata) ?? void 0,
12536
+ tags: normalizeTags(row.tags),
12537
+ labels: normalizeLabels(row.labels),
12538
+ metadata: parsedJson(row.metadata) ?? void 0,
12539
+ scope: parsedJson(row.scope) ?? void 0
12540
+ };
12541
+ }
12542
+ function scoreRecordToRow(score) {
12543
+ const metadata = score.metadata ?? null;
12544
+ const scoreSource = score.scoreSource ?? score.source ?? null;
12545
+ return {
12546
+ ...commonContextToRow(score),
12547
+ scoreId: score.scoreId,
12548
+ timestamp: toIsoOrDate(score.timestamp),
12549
+ traceId: score.traceId ?? null,
12550
+ spanId: score.spanId ?? null,
12551
+ scoreTraceId: score.scoreTraceId ?? null,
12552
+ scorerId: score.scorerId,
12553
+ scorerVersion: score.scorerVersion ?? null,
12554
+ scoreSource,
12555
+ score: score.score,
12556
+ reason: score.reason ?? null,
12557
+ tags: normalizeTags(score.tags),
12558
+ metadata: jsonField(metadata),
12559
+ scope: jsonField(score.scope)
12560
+ };
12561
+ }
12562
+ function rowToScoreRecord(row) {
12563
+ return {
12564
+ ...rowToCommonContext(row),
12565
+ scoreId: row.scoreId,
12566
+ timestamp: toDate(row.timestamp),
12567
+ // Legacy schema types traceId as required string even though the column is nullable.
12568
+ traceId: nullableString(row.traceId),
12569
+ spanId: nullableString(row.spanId),
12570
+ scoreTraceId: nullableString(row.scoreTraceId),
12571
+ scorerId: row.scorerId,
12572
+ scorerVersion: nullableString(row.scorerVersion),
12573
+ scoreSource: nullableString(row.scoreSource),
12574
+ score: Number(row.score),
12575
+ reason: nullableString(row.reason),
12576
+ tags: normalizeTags(row.tags),
12577
+ metadata: parsedJson(row.metadata) ?? void 0,
12578
+ scope: parsedJson(row.scope) ?? void 0
12579
+ };
12580
+ }
12581
+ function feedbackRecordToRow(feedback) {
12582
+ const metadata = feedback.metadata ?? null;
12583
+ const feedbackSource = feedback.feedbackSource ?? feedback.source ?? "";
12584
+ return {
12585
+ ...commonContextToRow(feedback),
12586
+ feedbackId: feedback.feedbackId,
12587
+ timestamp: toIsoOrDate(feedback.timestamp),
12588
+ traceId: feedback.traceId ?? null,
12589
+ spanId: feedback.spanId ?? null,
12590
+ feedbackUserId: feedback.feedbackUserId ?? null,
12591
+ sourceId: feedback.sourceId ?? null,
12592
+ feedbackSource,
12593
+ feedbackType: feedback.feedbackType,
12594
+ valueString: typeof feedback.value === "string" ? feedback.value : null,
12595
+ valueNumber: typeof feedback.value === "number" ? feedback.value : null,
12596
+ comment: feedback.comment ?? null,
12597
+ tags: normalizeTags(feedback.tags),
12598
+ metadata: jsonField(metadata),
12599
+ scope: jsonField(feedback.scope)
12600
+ };
12601
+ }
12602
+ function rowToFeedbackRecord(row) {
12603
+ const hasNumber = row.valueNumber != null;
12604
+ const feedbackSource = nullableString(row.feedbackSource);
12605
+ return {
12606
+ ...rowToCommonContext(row),
12607
+ feedbackId: row.feedbackId,
12608
+ timestamp: toDate(row.timestamp),
12609
+ // Legacy schema types traceId as required string even though the column is nullable.
12610
+ traceId: nullableString(row.traceId),
12611
+ spanId: nullableString(row.spanId),
12612
+ feedbackUserId: nullableString(row.feedbackUserId),
12613
+ sourceId: nullableString(row.sourceId),
12614
+ feedbackSource,
12615
+ feedbackType: row.feedbackType,
12616
+ value: hasNumber ? Number(row.valueNumber) : nullableString(row.valueString) ?? "",
12617
+ comment: nullableString(row.comment),
12618
+ tags: normalizeTags(row.tags),
12619
+ metadata: parsedJson(row.metadata) ?? void 0,
12620
+ scope: parsedJson(row.scope) ?? void 0
12621
+ };
12622
+ }
12623
+ var OBSERVABILITY_DELTA_POLLING_FEATURE = "observability-delta-polling";
12624
+ function deltaPollingFeatureEnabled() {
12625
+ return coreFeatures.has(OBSERVABILITY_DELTA_POLLING_FEATURE);
12626
+ }
12627
+ function assertDeltaPollingEnabled() {
12628
+ if (deltaPollingFeatureEnabled()) return;
12629
+ throw new MastraError({
12630
+ id: "OBSERVABILITY_DELTA_POLLING_NOT_SUPPORTED",
12631
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
12632
+ category: ErrorCategory.SYSTEM,
12633
+ text: "This storage provider does not support observability delta polling"
12634
+ });
12635
+ }
12636
+ var PG_BIGINT_MAX = 9223372036854775807n;
12637
+ function invalidDeltaCursor() {
12638
+ throw new MastraError({
12639
+ id: "OBSERVABILITY_INVALID_DELTA_CURSOR",
12640
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
12641
+ category: ErrorCategory.USER,
12642
+ text: "Invalid observability delta cursor"
12643
+ });
12644
+ }
12645
+ function validatePgInteger(value) {
12646
+ if (!/^\d+$/.test(value)) {
12647
+ invalidDeltaCursor();
12648
+ }
12649
+ let parsed;
12650
+ try {
12651
+ parsed = BigInt(value);
12652
+ } catch {
12653
+ invalidDeltaCursor();
12654
+ }
12655
+ if (parsed < 0n || parsed > PG_BIGINT_MAX) {
12656
+ invalidDeltaCursor();
12657
+ }
12658
+ return value;
12659
+ }
12660
+ function encodeDeltaCursor(xactId, cursorId = 0) {
12661
+ return `${validatePgInteger(String(xactId ?? 0))}:${validatePgInteger(String(cursorId ?? 0))}`;
12662
+ }
12663
+ function decodeDeltaCursor(cursor) {
12664
+ const parts = cursor.split(":");
12665
+ if (parts.length !== 2) {
12666
+ invalidDeltaCursor();
12667
+ }
12668
+ return {
12669
+ xactId: validatePgInteger(parts[0]),
12670
+ cursorId: validatePgInteger(parts[1])
12671
+ };
12672
+ }
12673
+ async function readSafeXactHorizon(client) {
12674
+ const row = await client.one(`SELECT pg_snapshot_xmin(pg_current_snapshot())::text AS "xactId"`);
12675
+ return validatePgInteger(row.xactId);
12676
+ }
12677
+
12678
+ // src/storage/domains/observability/v-next/listing.ts
12679
+ function responseItems(key, items) {
12680
+ return { [key]: items };
12681
+ }
12682
+ async function readSignalStreamHeadCursor({
12683
+ client,
12684
+ table,
12685
+ filters,
12686
+ applyFilters
12687
+ }) {
12688
+ return encodeDeltaCursor(await readSafeXactHorizon(client), 0);
12689
+ }
12690
+ async function listSignalPage(config) {
12691
+ const {
12692
+ client,
12693
+ table,
12694
+ filters,
12695
+ selectColumns,
12696
+ responseKey,
12697
+ applyFilters,
12698
+ mapRow,
12699
+ page,
12700
+ perPage,
12701
+ orderField,
12702
+ orderDir
12703
+ } = config;
12704
+ const acc = newFilterAccumulator();
12705
+ applyFilters(acc, filters);
12706
+ const whereClause = whereOrEmpty(acc);
12707
+ const countRow = await client.oneOrNone(
12708
+ `SELECT COUNT(*)::text AS count FROM ${table} ${whereClause}`,
12709
+ acc.params
12710
+ );
12711
+ const total = Number(countRow?.count ?? 0);
12712
+ let items = [];
12713
+ if (total > 0) {
12714
+ const safeOrderField = parseSqlIdentifier(orderField, "order field");
12715
+ const rows = await client.manyOrNone(
12716
+ `SELECT ${selectColumns}
12717
+ FROM ${table}
12718
+ ${whereClause}
12719
+ ORDER BY "${safeOrderField}" ${orderDir}, "cursorId" ${orderDir}
12720
+ LIMIT $${acc.next++} OFFSET $${acc.next++}`,
12721
+ [...acc.params, perPage, page * perPage]
12722
+ );
12723
+ items = rows.map(mapRow);
12724
+ }
12725
+ const deltaCursor = config.includeDeltaCursor ? await readSignalStreamHeadCursor({ client, table, filters, applyFilters }) : void 0;
12726
+ return {
12727
+ pagination: { total, page, perPage, hasMore: (page + 1) * perPage < total },
12728
+ ...responseItems(responseKey, items),
12729
+ ...deltaCursor !== void 0 ? { deltaCursor } : {}
12730
+ };
12731
+ }
12732
+ async function listSignalDelta(config) {
12733
+ const { client, table, filters, selectColumns, responseKey, applyFilters, mapRow, after, limit } = config;
12734
+ if (after === void 0) {
12735
+ const deltaCursor2 = await readSignalStreamHeadCursor({ client, table, filters, applyFilters });
12736
+ return { ...responseItems(responseKey, []), delta: { limit, hasMore: false }, deltaCursor: deltaCursor2 };
12737
+ }
12738
+ const afterCursor = decodeDeltaCursor(after);
12739
+ const safeHorizon = await readSafeXactHorizon(client);
12740
+ const acc = newFilterAccumulator();
12741
+ applyFilters(acc, filters);
12742
+ acc.conditions.push(`("xactId", "cursorId") > ($${acc.next++}::xid8, $${acc.next++}::bigint)`);
12743
+ acc.params.push(afterCursor.xactId, afterCursor.cursorId);
12744
+ acc.conditions.push(`"xactId" < $${acc.next++}::xid8`);
12745
+ acc.params.push(safeHorizon);
12746
+ const rows = await client.manyOrNone(
12747
+ `SELECT ${selectColumns}
12748
+ FROM ${table}
12749
+ ${whereOrEmpty(acc)}
12750
+ ORDER BY "xactId" ASC, "cursorId" ASC
12751
+ LIMIT $${acc.next++}`,
12752
+ [...acc.params, limit + 1]
12753
+ );
12754
+ const hasMore = rows.length > limit;
12755
+ const visible = rows.slice(0, limit);
12756
+ const deltaCursor = visible.length > 0 ? encodeDeltaCursor(visible[visible.length - 1].xactId, visible[visible.length - 1].cursorId) : encodeDeltaCursor(safeHorizon, 0);
12757
+ return {
12758
+ ...responseItems(responseKey, visible.map(mapRow)),
12759
+ delta: { limit, hasMore },
12760
+ deltaCursor
12761
+ };
12762
+ }
12763
+ var INTERVAL_SECONDS = {
12764
+ "1m": 60,
12765
+ "5m": 300,
12766
+ "15m": 900,
12767
+ "1h": 3600,
12768
+ "1d": 86400
12769
+ };
12770
+ function bucketSql(column, interval) {
12771
+ const seconds = INTERVAL_SECONDS[interval] ?? 3600;
12772
+ return `to_timestamp(floor(extract(epoch from ${column}) / ${seconds}) * ${seconds})`;
12773
+ }
12774
+ function resolveDistinctColumnSql(distinctColumn) {
12775
+ if (!distinctColumn) {
12776
+ throw new Error(`count_distinct aggregation requires a 'distinctColumn' argument`);
12777
+ }
12778
+ if (!METRIC_DISTINCT_COLUMNS.includes(distinctColumn)) {
12779
+ throw new Error(`Invalid distinctColumn: ${distinctColumn}`);
12780
+ }
12781
+ return `"${parseFieldKey(distinctColumn)}"`;
12782
+ }
12783
+ function metricAggregationSql(agg, measure, timestampColumn = "timestamp", distinctColumn) {
12784
+ if (agg === "count_distinct") {
12785
+ return `COUNT(DISTINCT ${resolveDistinctColumnSql(distinctColumn)})::double precision`;
12786
+ }
12787
+ return aggregationSql(agg, measure, timestampColumn);
12788
+ }
12789
+ function aggregationSql(agg, measure, timestampColumn = "timestamp") {
12790
+ switch (agg) {
12791
+ case "sum":
12792
+ return `SUM(${measure})`;
12793
+ case "avg":
12794
+ return `AVG(${measure})`;
12795
+ case "min":
12796
+ return `MIN(${measure})`;
12797
+ case "max":
12798
+ return `MAX(${measure})`;
12799
+ case "count":
12800
+ return `COUNT(${measure})::double precision`;
12801
+ case "last":
12802
+ return `(array_agg(${measure} ORDER BY "${timestampColumn}" DESC))[1]`;
12803
+ default:
12804
+ return `SUM(${measure})`;
12805
+ }
12806
+ }
12807
+ function resolveGroupBy(acc, groupBy, options) {
12808
+ const labelsColumn = options.labelsColumn ?? null;
12809
+ const excluded = options.excludedColumns ?? /* @__PURE__ */ new Set();
12810
+ return groupBy.map((key, index) => {
12811
+ const alias = `group_by_${index}`;
12812
+ if (options.typedColumns.has(key)) {
12813
+ const parsed = parseFieldKey(key);
12814
+ if (excluded.has(parsed)) {
12815
+ throw new Error(`Invalid groupBy column(s): ${key}`);
12816
+ }
12817
+ return {
12818
+ requestedKey: key,
12819
+ alias,
12820
+ selectSql: `"${parsed}" AS ${alias}`,
12821
+ valueSql: `"${parsed}"`
12822
+ };
12823
+ }
12824
+ if (!labelsColumn) {
12825
+ throw new Error(`Invalid groupBy column(s): ${key}`);
12826
+ }
12827
+ const valueSql = `"${labelsColumn}" ->> $${acc.next++}`;
12828
+ acc.params.push(key);
12829
+ return {
12830
+ requestedKey: key,
12831
+ alias,
12832
+ selectSql: `${valueSql} AS ${alias}`,
12833
+ valueSql
12834
+ };
12835
+ });
12836
+ }
12837
+ function pushLabelExclusions(acc, resolved) {
12838
+ for (const entry of resolved) {
12839
+ if (entry.valueSql.includes("->>")) {
12840
+ acc.conditions.push(`${entry.valueSql} IS NOT NULL`);
12841
+ acc.conditions.push(`${entry.valueSql} <> ''`);
12842
+ }
12843
+ }
12844
+ }
12845
+ function dimensionsFromRow(row, resolved) {
12846
+ const out = {};
12847
+ for (const entry of resolved) {
12848
+ const v = row[entry.alias];
12849
+ out[entry.requestedKey] = v == null || v === "" ? null : String(v);
12850
+ }
12851
+ return out;
12852
+ }
12853
+ function seriesNameFromDimensions(values) {
12854
+ return values.map((v) => v == null || v === "" ? "" : String(v)).join("|");
12855
+ }
12856
+ function shiftRange(range, period) {
12857
+ if (!range.start || !range.end) return null;
12858
+ const start = range.start.getTime();
12859
+ const end = range.end.getTime();
12860
+ const duration = end - start;
12861
+ let offset;
12862
+ switch (period) {
12863
+ case "previous_day":
12864
+ offset = 864e5;
12865
+ break;
12866
+ case "previous_week":
12867
+ offset = 7 * 864e5;
12868
+ break;
12869
+ case "previous_period":
12870
+ default:
12871
+ offset = duration;
12872
+ }
12873
+ return {
12874
+ start: new Date(start - offset),
12875
+ end: new Date(end - offset),
12876
+ startExclusive: range.startExclusive,
12877
+ endExclusive: range.endExclusive
12878
+ };
12879
+ }
12880
+ function changePercent(current, previous) {
12881
+ if (current === null || previous === null || previous === 0) return null;
12882
+ return (current - previous) / Math.abs(previous) * 100;
12883
+ }
12884
+ function bucketDate(value) {
12885
+ return value instanceof Date ? value : new Date(String(value));
12886
+ }
12887
+ function validatePercentiles(percentiles) {
12888
+ if (!percentiles.length) {
12889
+ throw new Error("Percentiles must include at least one value between 0 and 1.");
12890
+ }
12891
+ for (const percentile of percentiles) {
12892
+ if (!Number.isFinite(percentile) || percentile < 0 || percentile > 1) {
12893
+ throw new Error(`Percentile value must be a finite number between 0 and 1, got ${percentile}`);
12894
+ }
12895
+ }
12896
+ }
12897
+ function percentileSelectSql(percentiles, measureSql) {
12898
+ return percentiles.map((percentile, index) => `percentile_cont(${percentile}) WITHIN GROUP (ORDER BY ${measureSql}) AS p${index}`).join(", ");
12899
+ }
12900
+ function percentileSeriesFromRows(rows, percentiles) {
12901
+ return percentiles.map((percentile, index) => ({
12902
+ percentile,
12903
+ points: rows.map((row) => ({
12904
+ timestamp: bucketDate(row.bucket),
12905
+ value: Number(row[`p${index}`] ?? 0)
12906
+ }))
12907
+ }));
12908
+ }
12909
+ function collectSeriesByDimensions(rows, resolved, createEntry, appendRow) {
12910
+ const seriesMap = /* @__PURE__ */ new Map();
12911
+ for (const row of rows) {
12912
+ const dimensionValues = resolved.map((entry2) => row[entry2.alias]);
12913
+ const seriesKey = JSON.stringify(dimensionValues);
12914
+ let entry = seriesMap.get(seriesKey);
12915
+ if (!entry) {
12916
+ entry = createEntry(dimensionValues);
12917
+ seriesMap.set(seriesKey, entry);
12918
+ }
12919
+ appendRow(entry, row, dimensionValues);
12920
+ }
12921
+ return Array.from(seriesMap.values());
12922
+ }
12923
+ var COST_SUMMARY_SELECT = `
12924
+ SUM("estimatedCost") FILTER (WHERE "estimatedCost" IS NOT NULL) AS "agg_estimatedCost",
12925
+ CASE
12926
+ WHEN COUNT(DISTINCT "costUnit") FILTER (WHERE "costUnit" IS NOT NULL) = 1
12927
+ THEN MIN("costUnit") FILTER (WHERE "costUnit" IS NOT NULL)
12928
+ ELSE NULL
12929
+ END AS "agg_costUnit"
12930
+ `;
12931
+ function costSummaryFromRow(row) {
12932
+ return {
12933
+ estimatedCost: row.agg_estimatedCost == null ? null : Number(row.agg_estimatedCost),
12934
+ costUnit: row.agg_costUnit == null || row.agg_costUnit === "" ? null : String(row.agg_costUnit)
12935
+ };
12936
+ }
12937
+ var COMPLEX_GROUP_BY_EXCLUDED = /* @__PURE__ */ new Set([
12938
+ "metadata",
12939
+ "metadataRaw",
12940
+ "metadataSearch",
12941
+ "scope",
12942
+ "attributes",
12943
+ "links",
12944
+ "input",
12945
+ "output",
12946
+ "error",
12947
+ "data",
12948
+ "labels",
12949
+ "costMetadata",
12950
+ "tags",
12951
+ "requestContext"
12952
+ ]);
12953
+ function encodeJsonb(value) {
12954
+ if (value === null || value === void 0) return null;
12955
+ return JSON.stringify(value);
12956
+ }
12957
+ function buildInsert(schema, table, records) {
12958
+ if (records.length === 0) return null;
12959
+ const columns = Object.keys(records[0]).map((c) => parseSqlIdentifier(c, "column name"));
12960
+ const quotedColumns = columns.map((c) => `"${c}"`).join(", ");
12961
+ const values = [];
12962
+ const rowPlaceholders = [];
12963
+ let p = 1;
12964
+ for (const record of records) {
12965
+ const placeholders = columns.map((col) => {
12966
+ const raw = record[col];
12967
+ if (JSONB_COLUMNS.has(col)) {
12968
+ values.push(encodeJsonb(raw));
12969
+ return `$${p++}::jsonb`;
12970
+ }
12971
+ if (TEXT_ARRAY_COLUMNS.has(col)) {
12972
+ values.push(Array.isArray(raw) ? raw : []);
12973
+ return `$${p++}::text[]`;
12974
+ }
12975
+ values.push(raw === void 0 ? null : raw);
12976
+ return `$${p++}`;
12977
+ });
12978
+ rowPlaceholders.push(`(${placeholders.join(", ")})`);
12979
+ }
12980
+ const text = `INSERT INTO ${qualifiedTable(schema, table)} (${quotedColumns})
12981
+ VALUES ${rowPlaceholders.join(", ")}
12982
+ ON CONFLICT DO NOTHING`;
12983
+ return { text, values };
12984
+ }
12985
+ var SPAN_SELECT_COLUMNS = `
12986
+ ${buildSelectColumns(SPAN_EVENT_COLUMNS)}`;
12987
+ var SPAN_LIGHT_SELECT_COLUMNS = `
12988
+ ${buildNamedSelectColumns(SPAN_LIGHT_SELECT_COLUMN_NAMES)}`;
12989
+ var METRIC_SELECT_COLUMNS = `
12990
+ ${buildSelectColumns(METRIC_EVENT_COLUMNS)}`;
12991
+ var LOG_SELECT_COLUMNS = `
12992
+ ${buildSelectColumns(LOG_EVENT_COLUMNS)}`;
12993
+ var SCORE_SELECT_COLUMNS = `
12994
+ ${buildSelectColumns(SCORE_EVENT_COLUMNS)}`;
12995
+ var FEEDBACK_SELECT_COLUMNS = `
12996
+ ${buildSelectColumns(FEEDBACK_EVENT_COLUMNS)}`;
12997
+
12998
+ // src/storage/domains/observability/v-next/feedback.ts
12999
+ function applyFeedbackFilters(acc, filters) {
13000
+ applyCommonFilters(acc, filters);
13001
+ applySingleOrArrayFilter(acc, "feedbackType", filters?.feedbackType);
13002
+ if (filters?.feedbackSource ?? filters?.source) {
13003
+ acc.conditions.push(`"feedbackSource" = $${acc.next++}`);
13004
+ acc.params.push(filters.feedbackSource ?? filters.source);
13005
+ }
13006
+ if (filters?.feedbackUserId) {
13007
+ acc.conditions.push(`"feedbackUserId" = $${acc.next++}`);
13008
+ acc.params.push(filters.feedbackUserId);
13009
+ }
13010
+ }
13011
+ function pushFeedbackIdentity(acc, feedbackType, feedbackSource) {
13012
+ acc.conditions.push(`"feedbackType" = $${acc.next++}`);
13013
+ acc.params.push(feedbackType);
13014
+ if (feedbackSource !== void 0) {
13015
+ acc.conditions.push(`"feedbackSource" = $${acc.next++}`);
13016
+ acc.params.push(feedbackSource);
13017
+ }
13018
+ acc.conditions.push(`"valueNumber" IS NOT NULL`);
13019
+ }
13020
+ async function createFeedback(client, schema, args) {
13021
+ const row = feedbackRecordToRow(args.feedback);
13022
+ const insert = buildInsert(schema, TABLE_FEEDBACK_EVENTS, [row]);
13023
+ if (insert) await client.query(insert.text, insert.values);
13024
+ }
13025
+ async function batchCreateFeedback(client, schema, args) {
13026
+ if (args.feedbacks.length === 0) return;
13027
+ const rows = args.feedbacks.map(feedbackRecordToRow);
13028
+ const insert = buildInsert(schema, TABLE_FEEDBACK_EVENTS, rows);
13029
+ if (insert) await client.query(insert.text, insert.values);
13030
+ }
13031
+ async function listFeedback(client, schema, args) {
13032
+ const { mode, filters, pagination, orderBy, after, limit } = listFeedbackArgsSchema.parse(args);
13033
+ const table = qualifiedTable(schema, TABLE_FEEDBACK_EVENTS);
13034
+ if (mode === "delta") {
13035
+ assertDeltaPollingEnabled();
13036
+ return listFeedbackDelta(client, table, filters, after, limit);
13037
+ }
13038
+ return listFeedbackPage(
13039
+ client,
13040
+ table,
13041
+ filters,
13042
+ pagination.page,
13043
+ pagination.perPage,
13044
+ orderBy.field,
13045
+ orderBy.direction
13046
+ );
13047
+ }
13048
+ async function listFeedbackPage(client, table, filters, page, perPage, orderField, orderDir) {
13049
+ return listSignalPage({
13050
+ client,
13051
+ table,
13052
+ filters,
13053
+ page,
13054
+ perPage,
13055
+ orderField,
13056
+ orderDir,
13057
+ includeDeltaCursor: deltaPollingFeatureEnabled(),
13058
+ selectColumns: FEEDBACK_SELECT_COLUMNS,
13059
+ responseKey: "feedback",
13060
+ applyFilters: applyFeedbackFilters,
13061
+ mapRow: rowToFeedbackRecord
13062
+ });
13063
+ }
13064
+ async function listFeedbackDelta(client, table, filters, after, limit) {
13065
+ return listSignalDelta({
13066
+ client,
13067
+ table,
13068
+ filters,
13069
+ after,
13070
+ limit,
13071
+ selectColumns: FEEDBACK_SELECT_COLUMNS,
13072
+ responseKey: "feedback",
13073
+ applyFilters: applyFeedbackFilters,
13074
+ mapRow: rowToFeedbackRecord
13075
+ });
13076
+ }
13077
+ async function runFeedbackAggregateQuery(client, schema, args, filters) {
13078
+ const acc = newFilterAccumulator();
13079
+ pushFeedbackIdentity(acc, args.feedbackType, args.feedbackSource);
13080
+ applyFeedbackFilters(acc, filters);
13081
+ const sql = `
13082
+ SELECT ${aggregationSql(args.aggregation, '"valueNumber"')} AS "value"
13083
+ FROM ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)}
13084
+ ${whereOrEmpty(acc)}
13085
+ `;
13086
+ const row = await client.oneOrNone(sql, acc.params);
13087
+ return row?.value == null ? null : Number(row.value);
13088
+ }
13089
+ async function getFeedbackAggregate(client, schema, args) {
13090
+ const value = await runFeedbackAggregateQuery(client, schema, args, args.filters);
13091
+ if (args.comparePeriod && args.filters?.timestamp) {
13092
+ const prevRange = shiftRange(args.filters.timestamp, args.comparePeriod);
13093
+ if (prevRange) {
13094
+ const previousValue = await runFeedbackAggregateQuery(client, schema, args, {
13095
+ ...args.filters ?? {},
13096
+ timestamp: prevRange
13097
+ });
13098
+ return {
13099
+ value,
13100
+ previousValue,
13101
+ changePercent: changePercent(value, previousValue)
13102
+ };
13103
+ }
13104
+ }
13105
+ return { value };
13106
+ }
13107
+ async function getFeedbackBreakdown(client, schema, args) {
13108
+ const acc = newFilterAccumulator();
13109
+ const resolved = resolveGroupBy(acc, args.groupBy, {
13110
+ typedColumns: FEEDBACK_TYPED_COLUMNS,
13111
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED
13112
+ });
13113
+ pushFeedbackIdentity(acc, args.feedbackType, args.feedbackSource);
13114
+ applyFeedbackFilters(acc, args.filters);
13115
+ const sql = `
13116
+ SELECT ${resolved.map((e) => e.selectSql).join(", ")},
13117
+ ${aggregationSql(args.aggregation, '"valueNumber"')} AS "value"
13118
+ FROM ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)}
13119
+ ${whereOrEmpty(acc)}
13120
+ GROUP BY ${resolved.map((e) => e.alias).join(", ")}
13121
+ ORDER BY "value" DESC NULLS LAST
13122
+ `;
13123
+ const rows = await client.manyOrNone(sql, acc.params);
13124
+ return {
13125
+ groups: rows.map((row) => ({
13126
+ dimensions: dimensionsFromRow(row, resolved),
13127
+ value: Number(row.value ?? 0)
13128
+ }))
13129
+ };
13130
+ }
13131
+ async function getFeedbackTimeSeries(client, schema, args) {
13132
+ const bucket = bucketSql('"timestamp"', args.interval);
13133
+ if (args.groupBy && args.groupBy.length > 0) {
13134
+ const acc2 = newFilterAccumulator();
13135
+ const resolved = resolveGroupBy(acc2, args.groupBy, {
13136
+ typedColumns: FEEDBACK_TYPED_COLUMNS,
13137
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED
13138
+ });
13139
+ pushFeedbackIdentity(acc2, args.feedbackType, args.feedbackSource);
13140
+ applyFeedbackFilters(acc2, args.filters);
13141
+ const sql2 = `
13142
+ SELECT ${bucket} AS bucket,
13143
+ ${resolved.map((e) => e.selectSql).join(", ")},
13144
+ ${aggregationSql(args.aggregation, '"valueNumber"')} AS "value"
13145
+ FROM ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)}
13146
+ ${whereOrEmpty(acc2)}
13147
+ GROUP BY bucket, ${resolved.map((e) => e.alias).join(", ")}
13148
+ ORDER BY bucket
13149
+ `;
13150
+ const rows2 = await client.manyOrNone(sql2, acc2.params);
13151
+ return {
13152
+ series: collectSeriesByDimensions(
13153
+ rows2,
13154
+ resolved,
13155
+ (dimValues) => ({
13156
+ name: seriesNameFromDimensions(dimValues),
13157
+ points: []
13158
+ }),
13159
+ (entry, row) => {
13160
+ entry.points.push({
13161
+ timestamp: bucketDate(row.bucket),
13162
+ value: Number(row.value ?? 0)
13163
+ });
13164
+ }
13165
+ )
13166
+ };
13167
+ }
13168
+ const acc = newFilterAccumulator();
13169
+ pushFeedbackIdentity(acc, args.feedbackType, args.feedbackSource);
13170
+ applyFeedbackFilters(acc, args.filters);
13171
+ const sql = `
13172
+ SELECT ${bucket} AS bucket,
13173
+ ${aggregationSql(args.aggregation, '"valueNumber"')} AS "value"
13174
+ FROM ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)}
13175
+ ${whereOrEmpty(acc)}
13176
+ GROUP BY bucket
13177
+ ORDER BY bucket
13178
+ `;
13179
+ const rows = await client.manyOrNone(sql, acc.params);
13180
+ const seriesName = args.feedbackSource ? `${args.feedbackType}|${args.feedbackSource}` : args.feedbackType;
13181
+ return {
13182
+ series: [
13183
+ {
13184
+ name: seriesName,
13185
+ points: rows.map((row) => ({
13186
+ timestamp: bucketDate(row.bucket),
13187
+ value: Number(row.value ?? 0)
13188
+ }))
13189
+ }
13190
+ ]
13191
+ };
13192
+ }
13193
+ async function getFeedbackPercentiles(client, schema, args) {
13194
+ validatePercentiles(args.percentiles);
13195
+ const bucket = bucketSql('"timestamp"', args.interval);
13196
+ const acc = newFilterAccumulator();
13197
+ pushFeedbackIdentity(acc, args.feedbackType, args.feedbackSource);
13198
+ applyFeedbackFilters(acc, args.filters);
13199
+ const percentileSelect = percentileSelectSql(args.percentiles, '"valueNumber"');
13200
+ const sql = `
13201
+ SELECT ${bucket} AS bucket, ${percentileSelect}
13202
+ FROM ${qualifiedTable(schema, TABLE_FEEDBACK_EVENTS)}
13203
+ ${whereOrEmpty(acc)}
13204
+ GROUP BY bucket
13205
+ ORDER BY bucket
13206
+ `;
13207
+ const rows = await client.manyOrNone(sql, acc.params);
13208
+ return { series: percentileSeriesFromRows(rows, args.percentiles) };
13209
+ }
13210
+ function applyLogFilters(acc, filters) {
13211
+ applyCommonFilters(acc, filters);
13212
+ applySingleOrArrayFilter(acc, "level", filters?.level);
13213
+ }
13214
+ async function batchCreateLogs(client, schema, args) {
13215
+ if (args.logs.length === 0) return;
13216
+ const rows = args.logs.map(logRecordToRow);
13217
+ const insert = buildInsert(schema, TABLE_LOG_EVENTS, rows);
13218
+ if (insert) await client.query(insert.text, insert.values);
13219
+ }
13220
+ async function listLogs(client, schema, args) {
13221
+ const { mode, filters, pagination, orderBy, after, limit } = listLogsArgsSchema.parse(args);
13222
+ const table = qualifiedTable(schema, TABLE_LOG_EVENTS);
13223
+ if (mode === "delta") {
13224
+ assertDeltaPollingEnabled();
13225
+ return listLogsDelta(client, table, filters, after, limit);
13226
+ }
13227
+ return listLogsPage(client, table, filters, pagination.page, pagination.perPage, orderBy.field, orderBy.direction);
13228
+ }
13229
+ async function listLogsPage(client, table, filters, page, perPage, orderField, orderDir) {
13230
+ return listSignalPage({
13231
+ client,
13232
+ table,
13233
+ filters,
13234
+ page,
13235
+ perPage,
13236
+ orderField,
13237
+ orderDir,
13238
+ includeDeltaCursor: deltaPollingFeatureEnabled(),
13239
+ selectColumns: LOG_SELECT_COLUMNS,
13240
+ responseKey: "logs",
13241
+ applyFilters: applyLogFilters,
13242
+ mapRow: rowToLogRecord
13243
+ });
13244
+ }
13245
+ async function listLogsDelta(client, table, filters, after, limit) {
13246
+ return listSignalDelta({
13247
+ client,
13248
+ table,
13249
+ filters,
13250
+ after,
13251
+ limit,
13252
+ selectColumns: LOG_SELECT_COLUMNS,
13253
+ responseKey: "logs",
13254
+ applyFilters: applyLogFilters,
13255
+ mapRow: rowToLogRecord
13256
+ });
13257
+ }
13258
+ function applyMetricFilters(acc, filters) {
13259
+ applyCommonFilters(acc, filters);
13260
+ applySingleOrArrayFilter(acc, "name", filters?.name);
13261
+ applySingleOrArrayFilter(acc, "provider", filters?.provider);
13262
+ applySingleOrArrayFilter(acc, "model", filters?.model);
13263
+ applySingleOrArrayFilter(acc, "costUnit", filters?.costUnit);
13264
+ if (filters?.labels) {
13265
+ acc.conditions.push(`"labels" @> $${acc.next++}::jsonb`);
13266
+ acc.params.push(JSON.stringify(filters.labels));
13267
+ }
13268
+ }
13269
+ function pushMetricNameFilter(acc, names) {
13270
+ if (!names.length) return;
13271
+ const placeholders = names.map(() => `$${acc.next++}`).join(", ");
13272
+ acc.conditions.push(`"name" IN (${placeholders})`);
13273
+ acc.params.push(...names);
13274
+ }
13275
+ async function batchCreateMetrics(client, schema, args) {
13276
+ if (args.metrics.length === 0) return;
13277
+ const rows = args.metrics.map(metricRecordToRow);
13278
+ const insert = buildInsert(schema, TABLE_METRIC_EVENTS, rows);
13279
+ if (insert) await client.query(insert.text, insert.values);
13280
+ }
13281
+ async function listMetrics(client, schema, args) {
13282
+ const { mode, filters, pagination, orderBy, after, limit } = listMetricsArgsSchema.parse(args);
13283
+ const table = qualifiedTable(schema, TABLE_METRIC_EVENTS);
13284
+ if (mode === "delta") {
13285
+ assertDeltaPollingEnabled();
13286
+ return listMetricsDelta(client, table, filters, after, limit);
13287
+ }
13288
+ return listMetricsPage(client, table, filters, pagination.page, pagination.perPage, orderBy.field, orderBy.direction);
13289
+ }
13290
+ async function listMetricsPage(client, table, filters, page, perPage, orderField, orderDir) {
13291
+ return listSignalPage({
13292
+ client,
13293
+ table,
13294
+ filters,
13295
+ page,
13296
+ perPage,
13297
+ orderField,
13298
+ orderDir,
13299
+ includeDeltaCursor: deltaPollingFeatureEnabled(),
13300
+ selectColumns: METRIC_SELECT_COLUMNS,
13301
+ responseKey: "metrics",
13302
+ applyFilters: applyMetricFilters,
13303
+ mapRow: rowToMetricRecord
13304
+ });
13305
+ }
13306
+ async function listMetricsDelta(client, table, filters, after, limit) {
13307
+ return listSignalDelta({
13308
+ client,
13309
+ table,
13310
+ filters,
13311
+ after,
13312
+ limit,
13313
+ selectColumns: METRIC_SELECT_COLUMNS,
13314
+ responseKey: "metrics",
13315
+ applyFilters: applyMetricFilters,
13316
+ mapRow: rowToMetricRecord
13317
+ });
13318
+ }
13319
+ async function runMetricAggregateQuery(client, schema, filters, names, aggregation, distinctColumn) {
13320
+ const acc = newFilterAccumulator();
13321
+ pushMetricNameFilter(acc, names);
13322
+ applyMetricFilters(acc, filters);
13323
+ const where = whereOrEmpty(acc);
13324
+ const sql = `
13325
+ SELECT ${metricAggregationSql(aggregation, '"value"', "timestamp", distinctColumn)} AS "value",
13326
+ ${COST_SUMMARY_SELECT}
13327
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
13328
+ ${where}
13329
+ `;
13330
+ const row = await client.oneOrNone(sql, acc.params) ?? {};
13331
+ return {
13332
+ value: row.value == null ? null : Number(row.value),
13333
+ cost: costSummaryFromRow(row)
13334
+ };
13335
+ }
13336
+ async function getMetricAggregate(client, schema, args) {
13337
+ const { value, cost } = await runMetricAggregateQuery(
13338
+ client,
13339
+ schema,
13340
+ args.filters,
13341
+ args.name,
13342
+ args.aggregation,
13343
+ args.distinctColumn
13344
+ );
13345
+ if (args.comparePeriod && args.filters?.timestamp) {
13346
+ const prevRange = shiftRange(args.filters.timestamp, args.comparePeriod);
13347
+ if (prevRange) {
13348
+ const prevFilters = { ...args.filters ?? {}, timestamp: prevRange };
13349
+ const prev = await runMetricAggregateQuery(
13350
+ client,
13351
+ schema,
13352
+ prevFilters,
13353
+ args.name,
13354
+ args.aggregation,
13355
+ args.distinctColumn
13356
+ );
13357
+ return {
13358
+ value,
13359
+ estimatedCost: cost.estimatedCost,
13360
+ costUnit: cost.costUnit,
13361
+ previousValue: prev.value,
13362
+ previousEstimatedCost: prev.cost.estimatedCost,
13363
+ changePercent: changePercent(value, prev.value),
13364
+ costChangePercent: changePercent(cost.estimatedCost, prev.cost.estimatedCost)
13365
+ };
13366
+ }
13367
+ }
13368
+ return { value, estimatedCost: cost.estimatedCost, costUnit: cost.costUnit };
13369
+ }
13370
+ async function getMetricBreakdown(client, schema, args) {
13371
+ const acc = newFilterAccumulator();
13372
+ const resolved = resolveGroupBy(acc, args.groupBy, {
13373
+ typedColumns: METRIC_TYPED_COLUMNS,
13374
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED,
13375
+ labelsColumn: "labels"
13376
+ });
13377
+ pushMetricNameFilter(acc, args.name);
13378
+ applyMetricFilters(acc, args.filters);
13379
+ pushLabelExclusions(acc, resolved);
13380
+ const orderDirection = args.orderDirection === "ASC" ? "ASC" : "DESC";
13381
+ const limitClause = args.limit == null ? "" : `LIMIT $${acc.next++}`;
13382
+ if (args.limit != null) acc.params.push(args.limit);
13383
+ const sql = `
13384
+ SELECT ${resolved.map((e) => e.selectSql).join(", ")},
13385
+ ${metricAggregationSql(args.aggregation, '"value"', "timestamp", args.distinctColumn)} AS "value",
13386
+ ${COST_SUMMARY_SELECT}
13387
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
13388
+ ${whereOrEmpty(acc)}
13389
+ GROUP BY ${resolved.map((e) => e.alias).join(", ")}
13390
+ ORDER BY "value" ${orderDirection} NULLS LAST
13391
+ ${limitClause}
13392
+ `;
13393
+ const rows = await client.manyOrNone(sql, acc.params);
13394
+ return {
13395
+ groups: rows.map((row) => {
13396
+ const cs = costSummaryFromRow(row);
13397
+ return {
13398
+ dimensions: dimensionsFromRow(row, resolved),
13399
+ value: Number(row.value ?? 0),
13400
+ estimatedCost: cs.estimatedCost,
13401
+ costUnit: cs.costUnit
13402
+ };
13403
+ })
13404
+ };
13405
+ }
13406
+ async function getMetricTimeSeries(client, schema, args) {
13407
+ const bucket = bucketSql('"timestamp"', args.interval);
13408
+ if (args.groupBy && args.groupBy.length > 0) {
13409
+ const acc2 = newFilterAccumulator();
13410
+ const resolved = resolveGroupBy(acc2, args.groupBy, {
13411
+ typedColumns: METRIC_TYPED_COLUMNS,
13412
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED,
13413
+ labelsColumn: "labels"
13414
+ });
13415
+ pushMetricNameFilter(acc2, args.name);
13416
+ applyMetricFilters(acc2, args.filters);
13417
+ pushLabelExclusions(acc2, resolved);
13418
+ const sql2 = `
13419
+ SELECT ${bucket} AS bucket,
13420
+ ${resolved.map((e) => e.selectSql).join(", ")},
13421
+ ${metricAggregationSql(args.aggregation, '"value"', "timestamp", args.distinctColumn)} AS "value",
13422
+ ${COST_SUMMARY_SELECT}
13423
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
13424
+ ${whereOrEmpty(acc2)}
13425
+ GROUP BY bucket, ${resolved.map((e) => e.alias).join(", ")}
13426
+ ORDER BY bucket
13427
+ `;
13428
+ const rows2 = await client.manyOrNone(sql2, acc2.params);
13429
+ const series = collectSeriesByDimensions(
13430
+ rows2,
13431
+ resolved,
13432
+ (dimValues) => ({
13433
+ name: seriesNameFromDimensions(dimValues),
13434
+ costUnits: /* @__PURE__ */ new Set(),
13435
+ points: []
13436
+ }),
13437
+ (entry, row) => {
13438
+ const cs = costSummaryFromRow(row);
13439
+ if (cs.costUnit) entry.costUnits.add(cs.costUnit);
13440
+ entry.points.push({
13441
+ timestamp: bucketDate(row.bucket),
13442
+ value: Number(row.value ?? 0),
13443
+ estimatedCost: cs.estimatedCost
13444
+ });
13445
+ }
13446
+ ).map((s) => ({
13447
+ name: s.name,
13448
+ costUnit: s.costUnits.size === 1 ? Array.from(s.costUnits)[0] : null,
13449
+ points: s.points
13450
+ }));
13451
+ return { series };
13452
+ }
13453
+ const acc = newFilterAccumulator();
13454
+ pushMetricNameFilter(acc, args.name);
13455
+ applyMetricFilters(acc, args.filters);
13456
+ const sql = `
13457
+ SELECT ${bucket} AS bucket,
13458
+ ${metricAggregationSql(args.aggregation, '"value"', "timestamp", args.distinctColumn)} AS "value",
13459
+ ${COST_SUMMARY_SELECT}
13460
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
13461
+ ${whereOrEmpty(acc)}
13462
+ GROUP BY bucket
13463
+ ORDER BY bucket
13464
+ `;
13465
+ const rows = await client.manyOrNone(sql, acc.params);
13466
+ const overallCostUnits = /* @__PURE__ */ new Set();
13467
+ for (const row of rows) {
13468
+ const cs = costSummaryFromRow(row);
13469
+ if (cs.costUnit) overallCostUnits.add(cs.costUnit);
13470
+ }
13471
+ return {
13472
+ series: [
13473
+ {
13474
+ name: args.name.join("|"),
13475
+ costUnit: overallCostUnits.size === 1 ? Array.from(overallCostUnits)[0] : null,
13476
+ points: rows.map((row) => {
13477
+ const cs = costSummaryFromRow(row);
13478
+ return {
13479
+ timestamp: bucketDate(row.bucket),
13480
+ value: Number(row.value ?? 0),
13481
+ estimatedCost: cs.estimatedCost
13482
+ };
13483
+ })
13484
+ }
13485
+ ]
13486
+ };
13487
+ }
13488
+ async function getMetricPercentiles(client, schema, args) {
13489
+ validatePercentiles(args.percentiles);
13490
+ const bucket = bucketSql('"timestamp"', args.interval);
13491
+ const acc = newFilterAccumulator();
13492
+ pushMetricNameFilter(acc, [args.name]);
13493
+ applyMetricFilters(acc, args.filters);
13494
+ const percentileSelect = percentileSelectSql(args.percentiles, '"value"');
13495
+ const sql = `
13496
+ SELECT ${bucket} AS bucket, ${percentileSelect}
13497
+ FROM ${qualifiedTable(schema, TABLE_METRIC_EVENTS)}
13498
+ ${whereOrEmpty(acc)}
13499
+ GROUP BY bucket
13500
+ ORDER BY bucket
13501
+ `;
13502
+ const rows = await client.manyOrNone(sql, acc.params);
13503
+ return { series: percentileSeriesFromRows(rows, args.percentiles) };
13504
+ }
13505
+
13506
+ // src/storage/domains/observability/v-next/pg-errors.ts
13507
+ function asPgError(error) {
13508
+ return error ?? {};
13509
+ }
13510
+ function isDuplicateRelationError(error) {
13511
+ const { code, constraint, message = "" } = asPgError(error);
13512
+ if (code === "42P07") return true;
13513
+ if (code === "23505" && (constraint === "pg_type_typname_nsp_index" || constraint === "pg_class_relname_nsp_index")) {
13514
+ return true;
13515
+ }
13516
+ return /already exists/i.test(message);
13517
+ }
13518
+ function isDuplicateSchemaError(error) {
13519
+ const { code, constraint, message = "" } = asPgError(error);
13520
+ if (code === "42P06") return true;
13521
+ if (code === "23505" && constraint === "pg_namespace_nspname_index") return true;
13522
+ return /schema .* already exists/i.test(message);
13523
+ }
13524
+
13525
+ // src/storage/domains/observability/v-next/partitioning.ts
13526
+ var DEFAULT_FUTURE_DAYS = 14;
13527
+ async function detectTimescale(client) {
13528
+ const row = await client.oneOrNone(
13529
+ `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'timescaledb') AS "exists"`
13530
+ );
13531
+ return Boolean(row?.exists);
13532
+ }
13533
+ async function detectPartman(client) {
13534
+ const row = await client.oneOrNone(
13535
+ `SELECT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pg_partman') AS "exists"`
13536
+ );
13537
+ return Boolean(row?.exists);
13538
+ }
13539
+ async function getPartmanVersion(client) {
13540
+ const row = await client.oneOrNone(
13541
+ `SELECT extversion FROM pg_extension WHERE extname = 'pg_partman'`
13542
+ );
13543
+ return row?.extversion ?? null;
13544
+ }
13545
+ function getPartmanMajor(version) {
13546
+ if (!version) return null;
13547
+ const match = /^(\d+)/.exec(version);
13548
+ return match ? Number(match[1]) : null;
13549
+ }
13550
+ async function resolveMode(client, options = {}) {
13551
+ if (options.mode && options.mode !== "auto") return options.mode;
13552
+ if (await detectTimescale(client)) return "timescale";
13553
+ if (await detectPartman(client)) return "partman";
13554
+ return "native";
13555
+ }
13556
+ function dayBounds(d) {
13557
+ const year = d.getUTCFullYear();
13558
+ const month = String(d.getUTCMonth() + 1).padStart(2, "0");
13559
+ const day = String(d.getUTCDate()).padStart(2, "0");
13560
+ const start = `${year}-${month}-${day} 00:00:00+00`;
13561
+ const next = new Date(Date.UTC(year, d.getUTCMonth(), d.getUTCDate() + 1));
13562
+ const ny = next.getUTCFullYear();
13563
+ const nm = String(next.getUTCMonth() + 1).padStart(2, "0");
13564
+ const nd = String(next.getUTCDate()).padStart(2, "0");
13565
+ const end = `${ny}-${nm}-${nd} 00:00:00+00`;
13566
+ return { start, end, suffix: `${year}${month}${day}` };
13567
+ }
13568
+ function partitionName(table, suffix) {
13569
+ return `${table}_p${suffix}`;
13570
+ }
13571
+ async function ensureNativePartitions(client, schema, options = {}) {
13572
+ const futureDays = options.futureDays ?? DEFAULT_FUTURE_DAYS;
13573
+ const includeYesterday = options.includeYesterday ?? true;
13574
+ const start = includeYesterday ? -1 : 0;
13575
+ const baseNowMs = Date.now();
13576
+ for (const table of ALL_SIGNAL_TABLES) {
13577
+ for (let i = start; i <= futureDays; i++) {
13578
+ const d = new Date(baseNowMs + i * 864e5);
13579
+ const { start: partStart, end: partEnd, suffix } = dayBounds(d);
13580
+ const childName = partitionName(table, suffix);
13581
+ const child = qualifiedName(schema, childName);
13582
+ const parent = qualifiedTable(schema, table);
13583
+ try {
13584
+ await client.none(`CREATE TABLE IF NOT EXISTS ${child} (LIKE ${parent} INCLUDING ALL)`);
13585
+ } catch (error) {
13586
+ if (!isDuplicateRelationError(error)) throw error;
13587
+ }
13588
+ try {
13589
+ await client.none(
13590
+ `ALTER TABLE ${parent} ATTACH PARTITION ${child}
13591
+ FOR VALUES FROM ('${partStart}') TO ('${partEnd}')`
13592
+ );
13593
+ } catch (error) {
13594
+ if (!isAlreadyAttachedError(error)) throw error;
13595
+ }
13596
+ }
13597
+ }
13598
+ }
13599
+ function isAlreadyAttachedError(error) {
13600
+ const code = error?.code;
13601
+ const message = error?.message ?? "";
13602
+ if (code === "42P17" || code === "42710") {
13603
+ return /is already a partition/i.test(message) || /already a partition/i.test(message);
13604
+ }
13605
+ return /is already a partition/i.test(message);
13606
+ }
13607
+ async function ensureTimescaleHypertables(client, schema) {
13608
+ for (const table of ALL_SIGNAL_TABLES) {
13609
+ const tableExpr = qualifiedTable(schema, table);
13610
+ const timeColumn = SIGNAL_TIME_COLUMN[table].replace(/'/g, "''");
13611
+ await client.none(
13612
+ `SELECT create_hypertable($1::regclass, '${timeColumn}', chunk_time_interval => INTERVAL '1 day', if_not_exists => true)`,
13613
+ [tableExpr]
13614
+ );
13615
+ }
13616
+ }
13617
+ async function ensurePartmanHypertables(client, schema) {
13618
+ const partmanMajor = getPartmanMajor(await getPartmanVersion(client));
13619
+ for (const table of ALL_SIGNAL_TABLES) {
13620
+ const exists = await client.oneOrNone(
13621
+ `SELECT EXISTS (
13622
+ SELECT 1 FROM partman.part_config
13623
+ WHERE parent_table = format('%I.%I', $1::text, $2::text)
13624
+ ) AS "exists"`,
13625
+ [schema, table]
13626
+ );
13627
+ if (exists?.exists) continue;
13628
+ for (let attempt = 0; attempt < 3; attempt++) {
13629
+ try {
13630
+ if (partmanMajor != null && partmanMajor >= 5) {
13631
+ await client.none(
13632
+ `SELECT partman.create_parent(
13633
+ p_parent_table := format('%I.%I', $1::text, $2::text),
13634
+ p_control := $3,
13635
+ p_interval := '1 day',
13636
+ p_type := 'range'
13637
+ )`,
13638
+ [schema, table, SIGNAL_TIME_COLUMN[table]]
13639
+ );
13640
+ } else {
13641
+ await client.none(
13642
+ `SELECT partman.create_parent(
13643
+ p_parent_table := format('%I.%I', $1::text, $2::text),
13644
+ p_control := $3,
13645
+ p_type := 'native',
13646
+ p_interval := '1 day'
13647
+ )`,
13648
+ [schema, table, SIGNAL_TIME_COLUMN[table]]
13649
+ );
13650
+ }
13651
+ break;
13652
+ } catch (error) {
13653
+ const message = error?.message ?? "";
13654
+ const code = error?.code;
13655
+ const isDuplicate = code === "23505" || /already managed by pg_partman/i.test(message) || /relation .* already exists/i.test(message);
13656
+ if (isDuplicate) break;
13657
+ const isDeadlock = /deadlock detected/i.test(message);
13658
+ if (!isDeadlock) throw error;
13659
+ const registered = await client.oneOrNone(
13660
+ `SELECT EXISTS (
13661
+ SELECT 1 FROM partman.part_config
13662
+ WHERE parent_table = format('%I.%I', $1::text, $2::text)
13663
+ ) AS "exists"`,
13664
+ [schema, table]
13665
+ );
13666
+ if (registered?.exists) break;
13667
+ if (attempt === 2) throw error;
13668
+ await new Promise((resolve) => setTimeout(resolve, 25));
13669
+ }
13670
+ }
13671
+ }
13672
+ }
13673
+ async function setupPartitioning(client, schema, options = {}) {
13674
+ const mode = await resolveMode(client, options);
13675
+ switch (mode) {
13676
+ case "timescale":
13677
+ await ensureTimescaleHypertables(client, schema);
13678
+ return "timescale";
13679
+ case "partman":
13680
+ await ensurePartmanHypertables(client, schema);
13681
+ return "partman";
13682
+ case "native":
13683
+ await ensureNativePartitions(client, schema, options);
13684
+ return "native";
13685
+ }
13686
+ }
13687
+ function applyScoreFilters(acc, filters) {
13688
+ applyCommonFilters(acc, filters);
13689
+ applySingleOrArrayFilter(acc, "scorerId", filters?.scorerId);
13690
+ if (filters?.scoreSource ?? filters?.source) {
13691
+ acc.conditions.push(`"scoreSource" = $${acc.next++}`);
13692
+ acc.params.push(filters.scoreSource ?? filters.source);
13693
+ }
13694
+ }
13695
+ function pushScoreIdentity(acc, scorerId, scoreSource) {
13696
+ acc.conditions.push(`"scorerId" = $${acc.next++}`);
13697
+ acc.params.push(scorerId);
13698
+ if (scoreSource !== void 0) {
13699
+ acc.conditions.push(`"scoreSource" = $${acc.next++}`);
13700
+ acc.params.push(scoreSource);
13701
+ }
13702
+ }
13703
+ async function createScore(client, schema, args) {
13704
+ const row = scoreRecordToRow(args.score);
13705
+ const insert = buildInsert(schema, TABLE_SCORE_EVENTS, [row]);
13706
+ if (insert) await client.query(insert.text, insert.values);
13707
+ }
13708
+ async function batchCreateScores(client, schema, args) {
13709
+ if (args.scores.length === 0) return;
13710
+ const rows = args.scores.map(scoreRecordToRow);
13711
+ const insert = buildInsert(schema, TABLE_SCORE_EVENTS, rows);
13712
+ if (insert) await client.query(insert.text, insert.values);
13713
+ }
13714
+ async function listScores(client, schema, args) {
13715
+ const { mode, filters, pagination, orderBy, after, limit } = listScoresArgsSchema.parse(args);
13716
+ const table = qualifiedTable(schema, TABLE_SCORE_EVENTS);
13717
+ if (mode === "delta") {
13718
+ assertDeltaPollingEnabled();
13719
+ return listScoresDelta(client, table, filters, after, limit);
13720
+ }
13721
+ return listScoresPage(client, table, filters, pagination.page, pagination.perPage, orderBy.field, orderBy.direction);
13722
+ }
13723
+ async function getScoreById(client, schema, scoreId) {
13724
+ const row = await client.oneOrNone(
13725
+ `SELECT ${SCORE_SELECT_COLUMNS}
13726
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13727
+ WHERE "scoreId" = $1
13728
+ ORDER BY "timestamp" DESC
13729
+ LIMIT 1`,
13730
+ [scoreId]
13731
+ );
13732
+ return row ? rowToScoreRecord(row) : null;
13733
+ }
13734
+ async function listScoresPage(client, table, filters, page, perPage, orderField, orderDir) {
13735
+ return listSignalPage({
13736
+ client,
13737
+ table,
13738
+ filters,
13739
+ page,
13740
+ perPage,
13741
+ orderField,
13742
+ orderDir,
13743
+ includeDeltaCursor: deltaPollingFeatureEnabled(),
13744
+ selectColumns: SCORE_SELECT_COLUMNS,
13745
+ responseKey: "scores",
13746
+ applyFilters: applyScoreFilters,
13747
+ mapRow: rowToScoreRecord
13748
+ });
13749
+ }
13750
+ async function listScoresDelta(client, table, filters, after, limit) {
13751
+ return listSignalDelta({
13752
+ client,
13753
+ table,
13754
+ filters,
13755
+ after,
13756
+ limit,
13757
+ selectColumns: SCORE_SELECT_COLUMNS,
13758
+ responseKey: "scores",
13759
+ applyFilters: applyScoreFilters,
13760
+ mapRow: rowToScoreRecord
13761
+ });
13762
+ }
13763
+ async function runScoreAggregateQuery(client, schema, args, filters) {
13764
+ const acc = newFilterAccumulator();
13765
+ pushScoreIdentity(acc, args.scorerId, args.scoreSource);
13766
+ applyScoreFilters(acc, filters);
13767
+ const sql = `
13768
+ SELECT ${aggregationSql(args.aggregation, '"score"')} AS "value"
13769
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13770
+ ${whereOrEmpty(acc)}
13771
+ `;
13772
+ const row = await client.oneOrNone(sql, acc.params);
13773
+ return row?.value == null ? null : Number(row.value);
13774
+ }
13775
+ async function getScoreAggregate(client, schema, args) {
13776
+ const value = await runScoreAggregateQuery(client, schema, args, args.filters);
13777
+ if (args.comparePeriod && args.filters?.timestamp) {
13778
+ const prevRange = shiftRange(args.filters.timestamp, args.comparePeriod);
13779
+ if (prevRange) {
13780
+ const previousValue = await runScoreAggregateQuery(client, schema, args, {
13781
+ ...args.filters ?? {},
13782
+ timestamp: prevRange
13783
+ });
13784
+ return {
13785
+ value,
13786
+ previousValue,
13787
+ changePercent: changePercent(value, previousValue)
13788
+ };
13789
+ }
13790
+ }
13791
+ return { value };
13792
+ }
13793
+ async function getScoreBreakdown(client, schema, args) {
13794
+ const acc = newFilterAccumulator();
13795
+ const resolved = resolveGroupBy(acc, args.groupBy, {
13796
+ typedColumns: SCORE_TYPED_COLUMNS,
13797
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED
13798
+ });
13799
+ pushScoreIdentity(acc, args.scorerId, args.scoreSource);
13800
+ applyScoreFilters(acc, args.filters);
13801
+ const sql = `
13802
+ SELECT ${resolved.map((e) => e.selectSql).join(", ")},
13803
+ ${aggregationSql(args.aggregation, '"score"')} AS "value"
13804
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13805
+ ${whereOrEmpty(acc)}
13806
+ GROUP BY ${resolved.map((e) => e.alias).join(", ")}
13807
+ ORDER BY "value" DESC NULLS LAST
13808
+ `;
13809
+ const rows = await client.manyOrNone(sql, acc.params);
13810
+ return {
13811
+ groups: rows.map((row) => ({
13812
+ dimensions: dimensionsFromRow(row, resolved),
13813
+ value: Number(row.value ?? 0)
13814
+ }))
13815
+ };
13816
+ }
13817
+ async function getScoreTimeSeries(client, schema, args) {
13818
+ const bucket = bucketSql('"timestamp"', args.interval);
13819
+ if (args.groupBy && args.groupBy.length > 0) {
13820
+ const acc2 = newFilterAccumulator();
13821
+ const resolved = resolveGroupBy(acc2, args.groupBy, {
13822
+ typedColumns: SCORE_TYPED_COLUMNS,
13823
+ excludedColumns: COMPLEX_GROUP_BY_EXCLUDED
13824
+ });
13825
+ pushScoreIdentity(acc2, args.scorerId, args.scoreSource);
13826
+ applyScoreFilters(acc2, args.filters);
13827
+ const sql2 = `
13828
+ SELECT ${bucket} AS bucket,
13829
+ ${resolved.map((e) => e.selectSql).join(", ")},
13830
+ ${aggregationSql(args.aggregation, '"score"')} AS "value"
13831
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13832
+ ${whereOrEmpty(acc2)}
13833
+ GROUP BY bucket, ${resolved.map((e) => e.alias).join(", ")}
13834
+ ORDER BY bucket
13835
+ `;
13836
+ const rows2 = await client.manyOrNone(sql2, acc2.params);
13837
+ return {
13838
+ series: collectSeriesByDimensions(
13839
+ rows2,
13840
+ resolved,
13841
+ (dimValues) => ({
13842
+ name: seriesNameFromDimensions(dimValues),
13843
+ points: []
13844
+ }),
13845
+ (entry, row) => {
13846
+ entry.points.push({
13847
+ timestamp: bucketDate(row.bucket),
13848
+ value: Number(row.value ?? 0)
13849
+ });
13850
+ }
13851
+ )
13852
+ };
13853
+ }
13854
+ const acc = newFilterAccumulator();
13855
+ pushScoreIdentity(acc, args.scorerId, args.scoreSource);
13856
+ applyScoreFilters(acc, args.filters);
13857
+ const sql = `
13858
+ SELECT ${bucket} AS bucket,
13859
+ ${aggregationSql(args.aggregation, '"score"')} AS "value"
13860
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13861
+ ${whereOrEmpty(acc)}
13862
+ GROUP BY bucket
13863
+ ORDER BY bucket
13864
+ `;
13865
+ const rows = await client.manyOrNone(sql, acc.params);
13866
+ const seriesName = args.scoreSource ? `${args.scorerId}|${args.scoreSource}` : args.scorerId;
13867
+ return {
13868
+ series: [
13869
+ {
13870
+ name: seriesName,
13871
+ points: rows.map((row) => ({
13872
+ timestamp: bucketDate(row.bucket),
13873
+ value: Number(row.value ?? 0)
13874
+ }))
13875
+ }
13876
+ ]
13877
+ };
13878
+ }
13879
+ async function getScorePercentiles(client, schema, args) {
13880
+ validatePercentiles(args.percentiles);
13881
+ const bucket = bucketSql('"timestamp"', args.interval);
13882
+ const acc = newFilterAccumulator();
13883
+ pushScoreIdentity(acc, args.scorerId, args.scoreSource);
13884
+ applyScoreFilters(acc, args.filters);
13885
+ const percentileSelect = percentileSelectSql(args.percentiles, '"score"');
13886
+ const sql = `
13887
+ SELECT ${bucket} AS bucket, ${percentileSelect}
13888
+ FROM ${qualifiedTable(schema, TABLE_SCORE_EVENTS)}
13889
+ ${whereOrEmpty(acc)}
13890
+ GROUP BY bucket
13891
+ ORDER BY bucket
13892
+ `;
13893
+ const rows = await client.manyOrNone(sql, acc.params);
13894
+ return { series: percentileSeriesFromRows(rows, args.percentiles) };
13895
+ }
13896
+ function asIsoTimestamp(value) {
13897
+ return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
13898
+ }
13899
+ async function getRootSpan(client, schema, args) {
13900
+ const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
13901
+ const row = await client.oneOrNone(
13902
+ `SELECT ${SPAN_SELECT_COLUMNS}
13903
+ FROM ${table}
13904
+ WHERE "traceId" = $1 AND "parentSpanId" IS NULL
13905
+ ORDER BY "endedAt" DESC
13906
+ LIMIT 1`,
13907
+ [args.traceId]
13908
+ );
13909
+ if (!row) return null;
13910
+ return { span: rowToSpanRecord(row) };
13911
+ }
13912
+ function buildListTracesFilters(filters, spanTable, nextParamIdx) {
13913
+ const conditions = [`r."parentSpanId" IS NULL`];
13914
+ const params = [];
13915
+ let i = nextParamIdx;
13916
+ if (!filters) {
13917
+ return { conditions, params, nextParamIdx: i };
13918
+ }
13919
+ if (filters.startedAt?.start) {
13920
+ conditions.push(`r."startedAt" ${filters.startedAt.startExclusive ? ">" : ">="} $${i++}`);
13921
+ params.push(asIsoTimestamp(filters.startedAt.start));
13922
+ }
13923
+ if (filters.startedAt?.end) {
13924
+ conditions.push(`r."startedAt" ${filters.startedAt.endExclusive ? "<" : "<="} $${i++}`);
13925
+ params.push(asIsoTimestamp(filters.startedAt.end));
13926
+ }
13927
+ if (filters.endedAt?.start) {
13928
+ conditions.push(`r."endedAt" ${filters.endedAt.startExclusive ? ">" : ">="} $${i++}`);
13929
+ params.push(asIsoTimestamp(filters.endedAt.start));
13930
+ }
13931
+ if (filters.endedAt?.end) {
13932
+ conditions.push(`r."endedAt" ${filters.endedAt.endExclusive ? "<" : "<="} $${i++}`);
13933
+ params.push(asIsoTimestamp(filters.endedAt.end));
13934
+ }
13935
+ if (filters.spanType !== void 0) {
13936
+ conditions.push(`r."spanType" = $${i++}`);
13937
+ params.push(filters.spanType);
13938
+ }
13939
+ if (filters.entityType !== void 0) {
13940
+ conditions.push(`r."entityType" = $${i++}`);
13941
+ params.push(filters.entityType);
13942
+ }
13943
+ if (filters.entityId !== void 0) {
13944
+ conditions.push(`r."entityId" = $${i++}`);
13945
+ params.push(filters.entityId);
13946
+ }
13947
+ if (filters.entityName !== void 0) {
13948
+ conditions.push(`r."entityName" = $${i++}`);
13949
+ params.push(filters.entityName);
13950
+ }
13951
+ if (filters.userId !== void 0) {
13952
+ conditions.push(`r."userId" = $${i++}`);
13953
+ params.push(filters.userId);
13954
+ }
13955
+ if (filters.organizationId !== void 0) {
13956
+ conditions.push(`r."organizationId" = $${i++}`);
13957
+ params.push(filters.organizationId);
13958
+ }
13959
+ if (filters.resourceId !== void 0) {
13960
+ conditions.push(`r."resourceId" = $${i++}`);
13961
+ params.push(filters.resourceId);
13962
+ }
13963
+ if (filters.runId !== void 0) {
13964
+ conditions.push(`r."runId" = $${i++}`);
13965
+ params.push(filters.runId);
13966
+ }
13967
+ if (filters.sessionId !== void 0) {
13968
+ conditions.push(`r."sessionId" = $${i++}`);
13969
+ params.push(filters.sessionId);
13970
+ }
13971
+ if (filters.threadId !== void 0) {
13972
+ conditions.push(`r."threadId" = $${i++}`);
13973
+ params.push(filters.threadId);
13974
+ }
13975
+ if (filters.requestId !== void 0) {
13976
+ conditions.push(`r."requestId" = $${i++}`);
13977
+ params.push(filters.requestId);
13978
+ }
13979
+ if (filters.environment !== void 0) {
13980
+ conditions.push(`r."environment" = $${i++}`);
13981
+ params.push(filters.environment);
13982
+ }
13983
+ if (filters.source !== void 0) {
13984
+ conditions.push(`r."executionSource" = $${i++}`);
13985
+ params.push(filters.source);
13986
+ }
13987
+ if (filters.serviceName !== void 0) {
13988
+ conditions.push(`r."serviceName" = $${i++}`);
13989
+ params.push(filters.serviceName);
13990
+ }
13991
+ if (filters.metadata != null) {
13992
+ conditions.push(`r."metadataSearch" @> $${i++}::jsonb`);
13993
+ params.push(JSON.stringify(filters.metadata));
13994
+ }
13995
+ if (filters.tags != null && filters.tags.length > 0) {
13996
+ conditions.push(`r."tags" @> $${i++}::text[]`);
13997
+ params.push(filters.tags);
13998
+ }
13999
+ if (filters.status !== void 0) {
14000
+ switch (filters.status) {
14001
+ case TraceStatus.ERROR:
14002
+ conditions.push(`r."error" IS NOT NULL`);
14003
+ break;
14004
+ case TraceStatus.RUNNING:
14005
+ conditions.push(`FALSE`);
14006
+ break;
14007
+ case TraceStatus.SUCCESS:
14008
+ conditions.push(`r."error" IS NULL`);
14009
+ break;
14010
+ }
14011
+ }
14012
+ if (filters.hasChildError !== void 0) {
14013
+ const sub = `EXISTS (
14014
+ SELECT 1 FROM ${spanTable} c
14015
+ WHERE c."traceId" = r."traceId" AND c."spanId" <> r."spanId" AND c."error" IS NOT NULL
14016
+ )`;
14017
+ conditions.push(filters.hasChildError ? sub : `NOT ${sub}`);
14018
+ }
14019
+ return { conditions, params, nextParamIdx: i };
14020
+ }
14021
+ var SPAN_SELECT_COLUMNS_ALIASED = SPAN_SELECT_COLUMNS.replace(/\n/g, " ").split(",").map((c) => `r.${c.trim()}`).join(", ");
14022
+ async function listTraces(client, schema, args) {
14023
+ const { mode, filters, pagination, orderBy, after, limit } = listTracesArgsSchema.parse(args);
14024
+ const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14025
+ if (mode === "delta") {
14026
+ assertDeltaPollingEnabled();
14027
+ return listTracesDelta(client, span, filters, after, limit);
14028
+ }
14029
+ return listTracesPage(client, span, filters, pagination.page, pagination.perPage, orderBy.field, orderBy.direction);
14030
+ }
14031
+ async function listTracesPage(client, span, filters, page, perPage, orderField, orderDir) {
14032
+ const { conditions, params, nextParamIdx } = buildListTracesFilters(filters, span, 1);
14033
+ let i = nextParamIdx;
14034
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
14035
+ const orderClause = orderField === "endedAt" ? `ORDER BY r."endedAt" ${orderDir} NULLS ${orderDir === "DESC" ? "FIRST" : "LAST"}, r."cursorId" ${orderDir}` : `ORDER BY r."${orderField}" ${orderDir}, r."cursorId" ${orderDir}`;
14036
+ const countRow = await client.oneOrNone(
14037
+ `SELECT COUNT(*)::text AS count FROM ${span} r ${whereClause}`,
14038
+ params
14039
+ );
14040
+ const count = Number(countRow?.count ?? 0);
14041
+ let spans = [];
14042
+ if (count > 0) {
14043
+ const rows = await client.manyOrNone(
14044
+ `SELECT ${SPAN_SELECT_COLUMNS_ALIASED}
14045
+ FROM ${span} r
14046
+ ${whereClause}
14047
+ ${orderClause}
14048
+ LIMIT $${i++} OFFSET $${i++}`,
14049
+ [...params, perPage, page * perPage]
14050
+ );
14051
+ spans = rows.map(rowToSpanRecord);
14052
+ }
14053
+ const deltaCursor = deltaPollingFeatureEnabled() ? await readTracesStreamHeadCursor(client) : void 0;
14054
+ return {
14055
+ pagination: { total: count, page, perPage, hasMore: (page + 1) * perPage < count },
14056
+ spans: toTraceSpans(spans),
14057
+ ...deltaCursor !== void 0 ? { deltaCursor } : {}
14058
+ };
14059
+ }
14060
+ async function listTracesDelta(client, span, filters, after, limit) {
14061
+ if (after === void 0) {
14062
+ const deltaCursor2 = await readTracesStreamHeadCursor(client);
14063
+ return { spans: [], delta: { limit, hasMore: false }, deltaCursor: deltaCursor2 };
14064
+ }
14065
+ const afterCursor = decodeDeltaCursor(after);
14066
+ const safeHorizon = await readSafeXactHorizon(client);
14067
+ const { conditions, params, nextParamIdx } = buildListTracesFilters(filters, span, 1);
14068
+ let i = nextParamIdx;
14069
+ conditions.push(`(r."xactId", r."cursorId") > ($${i++}::xid8, $${i++}::bigint)`);
14070
+ params.push(afterCursor.xactId, afterCursor.cursorId);
14071
+ conditions.push(`r."xactId" < $${i++}::xid8`);
14072
+ params.push(safeHorizon);
14073
+ const rows = await client.manyOrNone(
14074
+ `SELECT ${SPAN_SELECT_COLUMNS_ALIASED}
14075
+ FROM ${span} r
14076
+ WHERE ${conditions.join(" AND ")}
14077
+ ORDER BY r."xactId" ASC, r."cursorId" ASC
14078
+ LIMIT $${i++}`,
14079
+ [...params, limit + 1]
14080
+ );
14081
+ const hasMore = rows.length > limit;
14082
+ const visible = rows.slice(0, limit);
14083
+ const deltaCursor = visible.length > 0 ? encodeDeltaCursor(visible[visible.length - 1].xactId, visible[visible.length - 1].cursorId) : encodeDeltaCursor(safeHorizon, 0);
14084
+ return {
14085
+ spans: toTraceSpans(visible.map(rowToSpanRecord)),
14086
+ delta: { limit, hasMore },
14087
+ deltaCursor
14088
+ };
14089
+ }
14090
+ async function readTracesStreamHeadCursor(client, span, filters) {
14091
+ return encodeDeltaCursor(await readSafeXactHorizon(client), 0);
14092
+ }
14093
+ var BRANCH_SPAN_TYPE_SET = new Set(BRANCH_SPAN_TYPES);
14094
+ function buildBranchSpanTypeClause(userSpanType, params, startIdx) {
14095
+ if (userSpanType !== void 0) {
14096
+ if (!BRANCH_SPAN_TYPE_SET.has(userSpanType)) {
14097
+ return null;
14098
+ }
14099
+ params.push(userSpanType);
14100
+ return { clause: `r."spanType" = $${startIdx}`, nextIdx: startIdx + 1 };
14101
+ }
14102
+ const placeholders = [];
14103
+ for (const t of BRANCH_SPAN_TYPES) {
14104
+ placeholders.push(`$${startIdx + placeholders.length}`);
14105
+ params.push(t);
14106
+ }
14107
+ return { clause: `r."spanType" IN (${placeholders.join(", ")})`, nextIdx: startIdx + placeholders.length };
14108
+ }
14109
+ function buildListBranchesFilters(filters, spanType, nextParamIdx) {
14110
+ const conditions = [];
14111
+ const params = [];
14112
+ let i = nextParamIdx;
14113
+ const spanTypeClause = buildBranchSpanTypeClause(spanType, params, i);
14114
+ if (!spanTypeClause) return null;
14115
+ conditions.push(spanTypeClause.clause);
14116
+ i = spanTypeClause.nextIdx;
14117
+ if (!filters) return { conditions, params, nextParamIdx: i };
14118
+ if (filters.startedAt?.start) {
14119
+ conditions.push(`r."startedAt" ${filters.startedAt.startExclusive ? ">" : ">="} $${i++}`);
14120
+ params.push(asIsoTimestamp(filters.startedAt.start));
14121
+ }
14122
+ if (filters.startedAt?.end) {
14123
+ conditions.push(`r."startedAt" ${filters.startedAt.endExclusive ? "<" : "<="} $${i++}`);
14124
+ params.push(asIsoTimestamp(filters.startedAt.end));
14125
+ }
14126
+ if (filters.endedAt?.start) {
14127
+ conditions.push(`r."endedAt" ${filters.endedAt.startExclusive ? ">" : ">="} $${i++}`);
14128
+ params.push(asIsoTimestamp(filters.endedAt.start));
14129
+ }
14130
+ if (filters.endedAt?.end) {
14131
+ conditions.push(`r."endedAt" ${filters.endedAt.endExclusive ? "<" : "<="} $${i++}`);
14132
+ params.push(asIsoTimestamp(filters.endedAt.end));
14133
+ }
14134
+ if (filters.traceId !== void 0) {
14135
+ conditions.push(`r."traceId" = $${i++}`);
14136
+ params.push(filters.traceId);
14137
+ }
14138
+ if (filters.entityType !== void 0) {
14139
+ conditions.push(`r."entityType" = $${i++}`);
14140
+ params.push(filters.entityType);
14141
+ }
14142
+ if (filters.entityId !== void 0) {
14143
+ conditions.push(`r."entityId" = $${i++}`);
14144
+ params.push(filters.entityId);
14145
+ }
14146
+ if (filters.entityName !== void 0) {
14147
+ conditions.push(`r."entityName" = $${i++}`);
14148
+ params.push(filters.entityName);
14149
+ }
14150
+ if (filters.entityVersionId !== void 0) {
14151
+ conditions.push(`r."entityVersionId" = $${i++}`);
14152
+ params.push(filters.entityVersionId);
14153
+ }
14154
+ if (filters.parentEntityType !== void 0) {
14155
+ conditions.push(`r."parentEntityType" = $${i++}`);
14156
+ params.push(filters.parentEntityType);
14157
+ }
14158
+ if (filters.parentEntityId !== void 0) {
14159
+ conditions.push(`r."parentEntityId" = $${i++}`);
14160
+ params.push(filters.parentEntityId);
14161
+ }
14162
+ if (filters.parentEntityName !== void 0) {
14163
+ conditions.push(`r."parentEntityName" = $${i++}`);
14164
+ params.push(filters.parentEntityName);
14165
+ }
14166
+ if (filters.parentEntityVersionId !== void 0) {
14167
+ conditions.push(`r."parentEntityVersionId" = $${i++}`);
14168
+ params.push(filters.parentEntityVersionId);
14169
+ }
14170
+ if (filters.rootEntityType !== void 0) {
14171
+ conditions.push(`r."rootEntityType" = $${i++}`);
14172
+ params.push(filters.rootEntityType);
14173
+ }
14174
+ if (filters.rootEntityId !== void 0) {
14175
+ conditions.push(`r."rootEntityId" = $${i++}`);
14176
+ params.push(filters.rootEntityId);
14177
+ }
14178
+ if (filters.rootEntityName !== void 0) {
14179
+ conditions.push(`r."rootEntityName" = $${i++}`);
14180
+ params.push(filters.rootEntityName);
14181
+ }
14182
+ if (filters.rootEntityVersionId !== void 0) {
14183
+ conditions.push(`r."rootEntityVersionId" = $${i++}`);
14184
+ params.push(filters.rootEntityVersionId);
14185
+ }
14186
+ if (filters.userId !== void 0) {
14187
+ conditions.push(`r."userId" = $${i++}`);
14188
+ params.push(filters.userId);
14189
+ }
14190
+ if (filters.organizationId !== void 0) {
14191
+ conditions.push(`r."organizationId" = $${i++}`);
14192
+ params.push(filters.organizationId);
14193
+ }
14194
+ if (filters.resourceId !== void 0) {
14195
+ conditions.push(`r."resourceId" = $${i++}`);
14196
+ params.push(filters.resourceId);
14197
+ }
14198
+ if (filters.runId !== void 0) {
14199
+ conditions.push(`r."runId" = $${i++}`);
14200
+ params.push(filters.runId);
14201
+ }
14202
+ if (filters.sessionId !== void 0) {
14203
+ conditions.push(`r."sessionId" = $${i++}`);
14204
+ params.push(filters.sessionId);
14205
+ }
14206
+ if (filters.threadId !== void 0) {
14207
+ conditions.push(`r."threadId" = $${i++}`);
14208
+ params.push(filters.threadId);
14209
+ }
14210
+ if (filters.requestId !== void 0) {
14211
+ conditions.push(`r."requestId" = $${i++}`);
14212
+ params.push(filters.requestId);
14213
+ }
14214
+ if (filters.experimentId !== void 0) {
14215
+ conditions.push(`r."experimentId" = $${i++}`);
14216
+ params.push(filters.experimentId);
14217
+ }
14218
+ if (filters.environment !== void 0) {
14219
+ conditions.push(`r."environment" = $${i++}`);
14220
+ params.push(filters.environment);
14221
+ }
14222
+ if (filters.serviceName !== void 0) {
14223
+ conditions.push(`r."serviceName" = $${i++}`);
14224
+ params.push(filters.serviceName);
14225
+ }
14226
+ if (filters.source !== void 0) {
14227
+ conditions.push(`r."executionSource" = $${i++}`);
14228
+ params.push(filters.source);
14229
+ }
14230
+ if (filters.metadata != null) {
14231
+ conditions.push(`r."metadataSearch" @> $${i++}::jsonb`);
14232
+ params.push(JSON.stringify(filters.metadata));
14233
+ }
14234
+ if (filters.tags != null && filters.tags.length > 0) {
14235
+ conditions.push(`r."tags" @> $${i++}::text[]`);
14236
+ params.push(filters.tags);
14237
+ }
14238
+ if (filters.status !== void 0) {
14239
+ switch (filters.status) {
14240
+ case TraceStatus.ERROR:
14241
+ conditions.push(`r."error" IS NOT NULL`);
14242
+ break;
14243
+ case TraceStatus.RUNNING:
14244
+ conditions.push(`FALSE`);
14245
+ break;
14246
+ case TraceStatus.SUCCESS:
14247
+ conditions.push(`r."error" IS NULL`);
14248
+ break;
14249
+ }
14250
+ }
14251
+ return { conditions, params, nextParamIdx: i };
14252
+ }
14253
+ async function listBranches(client, schema, args) {
14254
+ const { mode, filters, pagination, orderBy, after, limit } = listBranchesArgsSchema.parse(args);
14255
+ const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14256
+ if (mode === "delta") {
14257
+ assertDeltaPollingEnabled();
14258
+ return listBranchesDelta(client, span, filters, after, limit);
14259
+ }
14260
+ return listBranchesPage(client, span, filters, pagination.page, pagination.perPage, orderBy.field, orderBy.direction);
14261
+ }
14262
+ async function listBranchesPage(client, span, filters, page, perPage, orderField, orderDir) {
14263
+ const built = buildListBranchesFilters(filters, filters?.spanType, 1);
14264
+ if (!built) {
14265
+ const deltaCursor2 = deltaPollingFeatureEnabled() ? await readBranchesStreamHeadCursor(client) : void 0;
14266
+ return {
14267
+ pagination: { total: 0, page, perPage, hasMore: false },
14268
+ branches: [],
14269
+ ...deltaCursor2 !== void 0 ? { deltaCursor: deltaCursor2 } : {}
14270
+ };
14271
+ }
14272
+ const { conditions, params, nextParamIdx } = built;
14273
+ let i = nextParamIdx;
14274
+ const whereClause = `WHERE ${conditions.join(" AND ")}`;
14275
+ const orderClause = orderField === "endedAt" ? `ORDER BY r."endedAt" ${orderDir} NULLS ${orderDir === "DESC" ? "FIRST" : "LAST"}, r."cursorId" ${orderDir}` : `ORDER BY r."${orderField}" ${orderDir}, r."cursorId" ${orderDir}`;
14276
+ const countRow = await client.oneOrNone(
14277
+ `SELECT COUNT(*)::text AS count FROM ${span} r ${whereClause}`,
14278
+ params
14279
+ );
14280
+ const count = Number(countRow?.count ?? 0);
14281
+ let spans = [];
14282
+ if (count > 0) {
14283
+ const rows = await client.manyOrNone(
14284
+ `SELECT ${SPAN_SELECT_COLUMNS_ALIASED}
14285
+ FROM ${span} r
14286
+ ${whereClause}
14287
+ ${orderClause}
14288
+ LIMIT $${i++} OFFSET $${i++}`,
14289
+ [...params, perPage, page * perPage]
14290
+ );
14291
+ spans = rows.map(rowToSpanRecord);
14292
+ }
14293
+ const deltaCursor = deltaPollingFeatureEnabled() ? await readBranchesStreamHeadCursor(client) : void 0;
14294
+ return {
14295
+ pagination: { total: count, page, perPage, hasMore: (page + 1) * perPage < count },
14296
+ branches: toTraceSpans(spans),
14297
+ ...deltaCursor !== void 0 ? { deltaCursor } : {}
14298
+ };
14299
+ }
14300
+ async function listBranchesDelta(client, span, filters, after, limit) {
14301
+ if (after === void 0) {
14302
+ const deltaCursor2 = await readBranchesStreamHeadCursor(client);
14303
+ return { branches: [], delta: { limit, hasMore: false }, deltaCursor: deltaCursor2 };
14304
+ }
14305
+ const built = buildListBranchesFilters(filters, filters?.spanType, 1);
14306
+ if (!built) {
14307
+ return {
14308
+ branches: [],
14309
+ delta: { limit, hasMore: false },
14310
+ deltaCursor: await readBranchesStreamHeadCursor(client)
14311
+ };
14312
+ }
14313
+ const { conditions, params, nextParamIdx } = built;
14314
+ let i = nextParamIdx;
14315
+ const afterCursor = decodeDeltaCursor(after);
14316
+ const safeHorizon = await readSafeXactHorizon(client);
14317
+ conditions.push(`(r."xactId", r."cursorId") > ($${i++}::xid8, $${i++}::bigint)`);
14318
+ params.push(afterCursor.xactId, afterCursor.cursorId);
14319
+ conditions.push(`r."xactId" < $${i++}::xid8`);
14320
+ params.push(safeHorizon);
14321
+ const rows = await client.manyOrNone(
14322
+ `SELECT ${SPAN_SELECT_COLUMNS_ALIASED}
14323
+ FROM ${span} r
14324
+ WHERE ${conditions.join(" AND ")}
14325
+ ORDER BY r."xactId" ASC, r."cursorId" ASC
14326
+ LIMIT $${i++}`,
14327
+ [...params, limit + 1]
14328
+ );
14329
+ const hasMore = rows.length > limit;
14330
+ const visible = rows.slice(0, limit);
14331
+ const deltaCursor = visible.length > 0 ? encodeDeltaCursor(visible[visible.length - 1].xactId, visible[visible.length - 1].cursorId) : encodeDeltaCursor(safeHorizon, 0);
14332
+ return {
14333
+ branches: toTraceSpans(visible.map(rowToSpanRecord)),
14334
+ delta: { limit, hasMore },
14335
+ deltaCursor
14336
+ };
14337
+ }
14338
+ async function readBranchesStreamHeadCursor(client, span, filters) {
14339
+ return encodeDeltaCursor(await readSafeXactHorizon(client), 0);
14340
+ }
14341
+
14342
+ // src/storage/domains/observability/v-next/tracing.ts
14343
+ async function createSpan(client, schema, args) {
14344
+ const row = spanRecordToRow(args.span);
14345
+ const insert = buildInsert(schema, TABLE_SPAN_EVENTS, [row]);
14346
+ if (insert) await client.query(insert.text, insert.values);
14347
+ }
14348
+ async function batchCreateSpans(client, schema, args) {
14349
+ if (args.records.length === 0) return;
14350
+ const rows = args.records.map(spanRecordToRow);
14351
+ const insert = buildInsert(schema, TABLE_SPAN_EVENTS, rows);
14352
+ if (insert) await client.query(insert.text, insert.values);
14353
+ }
14354
+ async function getSpans(client, schema, args) {
14355
+ if (args.spanIds.length === 0) {
14356
+ return { traceId: args.traceId, spans: [] };
14357
+ }
14358
+ const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14359
+ const rows = await client.manyOrNone(
14360
+ `SELECT ${SPAN_SELECT_COLUMNS}
14361
+ FROM ${table}
14362
+ WHERE "traceId" = $1
14363
+ AND "spanId" = ANY($2::text[])
14364
+ ORDER BY "startedAt" ASC`,
14365
+ [args.traceId, args.spanIds]
14366
+ );
14367
+ return { traceId: args.traceId, spans: rows.map(rowToSpanRecord) };
14368
+ }
14369
+ async function getSpan(client, schema, args) {
14370
+ const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14371
+ const row = await client.oneOrNone(
14372
+ `SELECT ${SPAN_SELECT_COLUMNS}
14373
+ FROM ${table}
14374
+ WHERE "traceId" = $1 AND "spanId" = $2
14375
+ ORDER BY "endedAt" DESC
14376
+ LIMIT 1`,
14377
+ [args.traceId, args.spanId]
14378
+ );
14379
+ if (!row) return null;
14380
+ return { span: rowToSpanRecord(row) };
14381
+ }
14382
+ async function getTrace(client, schema, args) {
14383
+ const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14384
+ const rows = await client.manyOrNone(
14385
+ `SELECT ${SPAN_SELECT_COLUMNS}
14386
+ FROM ${table}
14387
+ WHERE "traceId" = $1
14388
+ ORDER BY "startedAt" ASC`,
14389
+ [args.traceId]
14390
+ );
14391
+ if (!rows.length) return null;
14392
+ return { traceId: args.traceId, spans: rows.map(rowToSpanRecord) };
14393
+ }
14394
+ async function getTraceLight(client, schema, args) {
14395
+ const table = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14396
+ const rows = await client.manyOrNone(
14397
+ `SELECT ${SPAN_LIGHT_SELECT_COLUMNS}
14398
+ FROM ${table}
14399
+ WHERE "traceId" = $1
14400
+ ORDER BY "startedAt" ASC`,
14401
+ [args.traceId]
14402
+ );
14403
+ if (!rows.length) return null;
14404
+ return {
14405
+ traceId: args.traceId,
14406
+ spans: rows.map(rowToLightSpanRecord)
14407
+ };
14408
+ }
14409
+ async function batchDeleteTraces(client, schema, args) {
14410
+ if (args.traceIds.length === 0) return;
14411
+ const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14412
+ const placeholders = args.traceIds.map((_, i) => `$${i + 1}`).join(", ");
14413
+ await client.query(`DELETE FROM ${span} WHERE "traceId" IN (${placeholders})`, args.traceIds);
14414
+ }
14415
+ async function dangerouslyClearTracing(client, schema) {
14416
+ const span = qualifiedTable(schema, TABLE_SPAN_EVENTS);
14417
+ await client.none(`TRUNCATE TABLE ${span} RESTART IDENTITY`);
14418
+ }
14419
+
14420
+ // src/storage/domains/observability/v-next/index.ts
14421
+ function wrapError(op, error, details) {
14422
+ if (error instanceof MastraError) throw error;
14423
+ throw new MastraError(
14424
+ {
14425
+ id: createStorageErrorId("PG", op, "FAILED"),
14426
+ domain: ErrorDomain.STORAGE,
14427
+ category: ErrorCategory.THIRD_PARTY,
14428
+ details
14429
+ },
14430
+ error
14431
+ );
14432
+ }
14433
+ var ObservabilityStoragePostgresVNext = class extends ObservabilityStorage {
14434
+ #client;
14435
+ #schema;
14436
+ #partitioning;
14437
+ #discoveryConfig;
14438
+ #partitionMode;
14439
+ constructor(config) {
14440
+ super();
14441
+ const { client, schemaName } = resolvePgConfig(config);
14442
+ this.#client = client;
14443
+ this.#schema = schemaName ?? "public";
14444
+ this.#partitioning = config.partitioning ?? {};
14445
+ this.#discoveryConfig = config.discovery ?? {};
14446
+ }
14447
+ /**
14448
+ * Build the discovery config used at each call site, with the framework
14449
+ * logger injected so background refresh failures land in the same log
14450
+ * stream as the rest of the store. Reads `this.logger` lazily so
14451
+ * `__setLogger()` calls (e.g. when the domain is mounted under a Mastra
14452
+ * instance) propagate without rebuilding the domain.
14453
+ */
14454
+ get #discovery() {
14455
+ return { ...this.#discoveryConfig, logger: this.logger };
14456
+ }
14457
+ // -------------------------------------------------------------------------
14458
+ // Initialization
14459
+ // -------------------------------------------------------------------------
14460
+ /**
14461
+ * Create the signal tables, indexes, and (if Timescale / pg_partman is
14462
+ * present) hypertable / partman registrations.
14463
+ *
14464
+ * Not transactional: each `CREATE TABLE IF NOT EXISTS`, `CREATE INDEX IF
14465
+ * NOT EXISTS`, and `create_hypertable()` / `create_parent()` runs in its
14466
+ * own implicit transaction. Re-running `init()` after a failure is safe
14467
+ * (every statement is idempotent), but a failure partway through against
14468
+ * Timescale can leave some signal tables as hypertables and others as
14469
+ * plain tables. If that happens, fix the underlying error and call
14470
+ * `init()` again — the partially-converted state is recoverable.
14471
+ */
14472
+ async init() {
14473
+ try {
14474
+ const explicit = this.#partitioning.mode;
14475
+ let mode;
14476
+ if (explicit && explicit !== "auto") {
14477
+ mode = explicit;
14478
+ } else if (await detectTimescale(this.#client)) {
14479
+ mode = "timescale";
14480
+ } else if (await detectPartman(this.#client)) {
14481
+ mode = "partman";
14482
+ } else {
14483
+ mode = "native";
14484
+ }
14485
+ const ddlMode = mode === "timescale" ? "timescale" : "partitioned";
14486
+ try {
14487
+ await this.#client.none(schemaDDL(this.#schema));
14488
+ } catch (error) {
14489
+ if (!isDuplicateSchemaError(error)) throw error;
14490
+ }
14491
+ for (const ddl of allTableDDL(this.#schema, ddlMode)) {
14492
+ try {
14493
+ await this.#client.none(ddl);
14494
+ } catch (error) {
14495
+ if (!isDuplicateRelationError(error)) throw error;
14496
+ }
14497
+ }
14498
+ for (const ddl of allIndexDDL(this.#schema)) {
14499
+ try {
14500
+ await this.#client.none(ddl);
14501
+ } catch (error) {
14502
+ if (!isDuplicateRelationError(error)) throw error;
14503
+ }
14504
+ }
14505
+ this.#partitionMode = await setupPartitioning(this.#client, this.#schema, {
14506
+ ...this.#partitioning,
14507
+ mode
14508
+ });
14509
+ } catch (error) {
14510
+ wrapError("VNEXT_INIT", error);
14511
+ }
14512
+ }
14513
+ /** Resolved partition mode after init(). Useful for tests and diagnostics. */
14514
+ get partitionMode() {
14515
+ return this.#partitionMode;
14516
+ }
14517
+ get observabilityStrategy() {
14518
+ return { preferred: "insert-only", supported: ["insert-only"] };
14519
+ }
14520
+ getFeatures() {
14521
+ if (!deltaPollingFeatureEnabled()) return void 0;
14522
+ return ["delta-polling"];
14523
+ }
14524
+ async #run(op, fn, details) {
14525
+ try {
14526
+ return await fn();
14527
+ } catch (error) {
14528
+ wrapError(op, error, details);
14529
+ }
14530
+ }
14531
+ // -------------------------------------------------------------------------
14532
+ // Tracing — writes
14533
+ // -------------------------------------------------------------------------
14534
+ async createSpan(args) {
14535
+ await this.#run("CREATE_SPAN", () => createSpan(this.#client, this.#schema, args), {
14536
+ traceId: args.span.traceId,
14537
+ spanId: args.span.spanId
14538
+ });
14539
+ }
14540
+ async batchCreateSpans(args) {
14541
+ await this.#run("BATCH_CREATE_SPANS", () => batchCreateSpans(this.#client, this.#schema, args), {
14542
+ count: args.records.length
14543
+ });
14544
+ }
14545
+ // -------------------------------------------------------------------------
14546
+ // Tracing — reads
14547
+ // -------------------------------------------------------------------------
14548
+ async getSpan(args) {
14549
+ return this.#run("GET_SPAN", () => getSpan(this.#client, this.#schema, args), {
14550
+ traceId: args.traceId,
14551
+ spanId: args.spanId
14552
+ });
14553
+ }
14554
+ async getSpans(args) {
14555
+ return this.#run("GET_SPANS", () => getSpans(this.#client, this.#schema, args), {
14556
+ traceId: args.traceId,
14557
+ count: args.spanIds.length
14558
+ });
14559
+ }
14560
+ async getRootSpan(args) {
14561
+ return this.#run("GET_ROOT_SPAN", () => getRootSpan(this.#client, this.#schema, args), {
14562
+ traceId: args.traceId
14563
+ });
14564
+ }
14565
+ async getTrace(args) {
14566
+ return this.#run("GET_TRACE", () => getTrace(this.#client, this.#schema, args), {
14567
+ traceId: args.traceId
14568
+ });
14569
+ }
14570
+ async getTraceLight(args) {
14571
+ return this.#run("GET_TRACE_LIGHT", () => getTraceLight(this.#client, this.#schema, args), {
14572
+ traceId: args.traceId
14573
+ });
14574
+ }
14575
+ async listTraces(args) {
14576
+ return this.#run("LIST_TRACES", () => listTraces(this.#client, this.#schema, args));
14577
+ }
14578
+ async listBranches(args) {
14579
+ return this.#run("LIST_BRANCHES", () => listBranches(this.#client, this.#schema, args));
14580
+ }
14581
+ // -------------------------------------------------------------------------
14582
+ // Logs / metrics / scores / feedback — writes
14583
+ // -------------------------------------------------------------------------
14584
+ async batchCreateLogs(args) {
14585
+ await this.#run("BATCH_CREATE_LOGS", () => batchCreateLogs(this.#client, this.#schema, args), {
14586
+ count: args.logs.length
14587
+ });
14588
+ }
14589
+ async batchCreateMetrics(args) {
14590
+ await this.#run("BATCH_CREATE_METRICS", () => batchCreateMetrics(this.#client, this.#schema, args), {
14591
+ count: args.metrics.length
14592
+ });
14593
+ }
14594
+ async createScore(args) {
14595
+ await this.#run("CREATE_SCORE", () => createScore(this.#client, this.#schema, args));
14596
+ }
14597
+ async batchCreateScores(args) {
14598
+ await this.#run("BATCH_CREATE_SCORES", () => batchCreateScores(this.#client, this.#schema, args), {
14599
+ count: args.scores.length
14600
+ });
14601
+ }
14602
+ async createFeedback(args) {
14603
+ await this.#run("CREATE_FEEDBACK", () => createFeedback(this.#client, this.#schema, args));
14604
+ }
14605
+ async batchCreateFeedback(args) {
14606
+ await this.#run("BATCH_CREATE_FEEDBACK", () => batchCreateFeedback(this.#client, this.#schema, args), {
14607
+ count: args.feedbacks.length
14608
+ });
14609
+ }
14610
+ // -------------------------------------------------------------------------
14611
+ // Logs / metrics / scores / feedback — list reads
14612
+ // -------------------------------------------------------------------------
14613
+ async listLogs(args) {
14614
+ return this.#run("LIST_LOGS", () => listLogs(this.#client, this.#schema, args));
14615
+ }
14616
+ async listMetrics(args) {
14617
+ return this.#run("LIST_METRICS", () => listMetrics(this.#client, this.#schema, args));
14618
+ }
14619
+ async listScores(args) {
14620
+ return this.#run("LIST_SCORES", () => listScores(this.#client, this.#schema, args));
14621
+ }
14622
+ async getScoreById(scoreId) {
14623
+ return this.#run("GET_SCORE_BY_ID", () => getScoreById(this.#client, this.#schema, scoreId), {
14624
+ scoreId
14625
+ });
14626
+ }
14627
+ async listFeedback(args) {
14628
+ return this.#run("LIST_FEEDBACK", () => listFeedback(this.#client, this.#schema, args));
14629
+ }
14630
+ // -------------------------------------------------------------------------
14631
+ // OLAP — metrics
14632
+ // -------------------------------------------------------------------------
14633
+ async getMetricAggregate(args) {
14634
+ return this.#run("GET_METRIC_AGGREGATE", () => getMetricAggregate(this.#client, this.#schema, args));
14635
+ }
14636
+ async getMetricBreakdown(args) {
14637
+ return this.#run("GET_METRIC_BREAKDOWN", () => getMetricBreakdown(this.#client, this.#schema, args));
14638
+ }
14639
+ async getMetricTimeSeries(args) {
14640
+ return this.#run("GET_METRIC_TIME_SERIES", () => getMetricTimeSeries(this.#client, this.#schema, args));
14641
+ }
14642
+ async getMetricPercentiles(args) {
14643
+ return this.#run("GET_METRIC_PERCENTILES", () => getMetricPercentiles(this.#client, this.#schema, args));
14644
+ }
14645
+ // -------------------------------------------------------------------------
14646
+ // OLAP — scores
14647
+ // -------------------------------------------------------------------------
14648
+ async getScoreAggregate(args) {
14649
+ return this.#run("GET_SCORE_AGGREGATE", () => getScoreAggregate(this.#client, this.#schema, args));
14650
+ }
14651
+ async getScoreBreakdown(args) {
14652
+ return this.#run("GET_SCORE_BREAKDOWN", () => getScoreBreakdown(this.#client, this.#schema, args));
14653
+ }
14654
+ async getScoreTimeSeries(args) {
14655
+ return this.#run("GET_SCORE_TIME_SERIES", () => getScoreTimeSeries(this.#client, this.#schema, args));
14656
+ }
14657
+ async getScorePercentiles(args) {
14658
+ return this.#run("GET_SCORE_PERCENTILES", () => getScorePercentiles(this.#client, this.#schema, args));
14659
+ }
14660
+ // -------------------------------------------------------------------------
14661
+ // OLAP — feedback
14662
+ // -------------------------------------------------------------------------
14663
+ async getFeedbackAggregate(args) {
14664
+ return this.#run(
14665
+ "GET_FEEDBACK_AGGREGATE",
14666
+ () => getFeedbackAggregate(this.#client, this.#schema, args)
14667
+ );
14668
+ }
14669
+ async getFeedbackBreakdown(args) {
14670
+ return this.#run(
14671
+ "GET_FEEDBACK_BREAKDOWN",
14672
+ () => getFeedbackBreakdown(this.#client, this.#schema, args)
14673
+ );
14674
+ }
14675
+ async getFeedbackTimeSeries(args) {
14676
+ return this.#run(
14677
+ "GET_FEEDBACK_TIME_SERIES",
14678
+ () => getFeedbackTimeSeries(this.#client, this.#schema, args)
14679
+ );
14680
+ }
14681
+ async getFeedbackPercentiles(args) {
14682
+ return this.#run(
14683
+ "GET_FEEDBACK_PERCENTILES",
14684
+ () => getFeedbackPercentiles(this.#client, this.#schema, args)
14685
+ );
14686
+ }
14687
+ // -------------------------------------------------------------------------
14688
+ // Discovery
14689
+ // -------------------------------------------------------------------------
14690
+ async getEntityTypes(args) {
14691
+ return this.#run(
14692
+ "GET_ENTITY_TYPES",
14693
+ () => getEntityTypes(this.#client, this.#schema, args, this.#discovery)
14694
+ );
14695
+ }
14696
+ async getEntityNames(args) {
14697
+ return this.#run(
14698
+ "GET_ENTITY_NAMES",
14699
+ () => getEntityNames(this.#client, this.#schema, args, this.#discovery)
14700
+ );
14701
+ }
14702
+ async getServiceNames(args) {
14703
+ return this.#run(
14704
+ "GET_SERVICE_NAMES",
14705
+ () => getServiceNames(this.#client, this.#schema, args, this.#discovery)
14706
+ );
14707
+ }
14708
+ async getEnvironments(args) {
14709
+ return this.#run(
14710
+ "GET_ENVIRONMENTS",
14711
+ () => getEnvironments(this.#client, this.#schema, args, this.#discovery)
14712
+ );
14713
+ }
14714
+ async getTags(args) {
14715
+ return this.#run("GET_TAGS", () => getTags(this.#client, this.#schema, args, this.#discovery));
14716
+ }
14717
+ async getMetricNames(args) {
14718
+ return this.#run(
14719
+ "GET_METRIC_NAMES",
14720
+ () => getMetricNames(this.#client, this.#schema, args, this.#discovery)
14721
+ );
14722
+ }
14723
+ async getMetricLabelKeys(args) {
14724
+ return this.#run(
14725
+ "GET_METRIC_LABEL_KEYS",
14726
+ () => getMetricLabelKeys(this.#client, this.#schema, args, this.#discovery)
14727
+ );
14728
+ }
14729
+ async getMetricLabelValues(args) {
14730
+ return this.#run(
14731
+ "GET_METRIC_LABEL_VALUES",
14732
+ () => getMetricLabelValues(this.#client, this.#schema, args, this.#discovery)
14733
+ );
14734
+ }
14735
+ // -------------------------------------------------------------------------
14736
+ // Tracing — deletes / clear
14737
+ // -------------------------------------------------------------------------
14738
+ async batchDeleteTraces(args) {
14739
+ await this.#run("BATCH_DELETE_TRACES", () => batchDeleteTraces(this.#client, this.#schema, args), {
14740
+ count: args.traceIds.length
14741
+ });
14742
+ }
14743
+ async dangerouslyClearAll() {
14744
+ try {
14745
+ await dangerouslyClearTracing(this.#client, this.#schema);
14746
+ for (const t of ALL_SIGNAL_TABLES) {
14747
+ if (t === TABLE_SPAN_EVENTS) continue;
14748
+ await this.#client.none(`TRUNCATE TABLE ${qualifiedTable(this.#schema, t)} RESTART IDENTITY`);
14749
+ }
14750
+ await this.#client.none(`TRUNCATE TABLE ${qualifiedTable(this.#schema, TABLE_DISCOVERY)} RESTART IDENTITY`);
14751
+ } catch (error) {
14752
+ wrapError("DANGEROUSLY_CLEAR_ALL", error);
14753
+ }
14754
+ }
14755
+ };
14756
+ var SNAPSHOT_FIELDS3 = ["name", "description", "content", "rules", "requestContextSchema"];
14757
+ var PromptBlocksPG = class _PromptBlocksPG extends PromptBlocksStorage {
14758
+ #db;
14759
+ #schema;
14760
+ #skipDefaultIndexes;
14761
+ #indexes;
14762
+ static MANAGED_TABLES = [TABLE_PROMPT_BLOCKS, TABLE_PROMPT_BLOCK_VERSIONS];
14763
+ constructor(config) {
14764
+ super();
14765
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
14766
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
14767
+ this.#schema = schemaName || "public";
14768
+ this.#skipDefaultIndexes = skipDefaultIndexes;
14769
+ this.#indexes = indexes?.filter((idx) => _PromptBlocksPG.MANAGED_TABLES.includes(idx.table));
14770
+ }
14771
+ /**
14772
+ * Returns default index definitions for the prompt blocks domain tables.
14773
+ * @param schemaPrefix - Prefix for index names (e.g. "my_schema_" or "")
14774
+ */
14775
+ static getDefaultIndexDefs(schemaPrefix) {
14776
+ return [
14777
+ {
14778
+ name: `${schemaPrefix}idx_prompt_block_versions_block_version`,
14779
+ table: TABLE_PROMPT_BLOCK_VERSIONS,
14780
+ columns: ["blockId", "versionNumber"],
14781
+ unique: true
14782
+ }
14783
+ ];
14784
+ }
14785
+ /**
14786
+ * Returns all DDL statements for this domain: tables and indexes.
14787
+ * Used by exportSchemas to produce a complete, reproducible schema export.
14788
+ */
14789
+ static getExportDDL(schemaName) {
14790
+ const statements = [];
14791
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
14792
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
14793
+ for (const tableName of _PromptBlocksPG.MANAGED_TABLES) {
14794
+ statements.push(
14795
+ generateTableSQL({
14796
+ tableName,
14797
+ schema: TABLE_SCHEMAS[tableName],
14798
+ schemaName,
14799
+ includeAllConstraints: true
14800
+ })
14801
+ );
14802
+ }
14803
+ for (const idx of _PromptBlocksPG.getDefaultIndexDefs(schemaPrefix)) {
14804
+ statements.push(generateIndexSQL(idx, schemaName));
14805
+ }
14806
+ return statements;
14807
+ }
14808
+ getDefaultIndexDefinitions() {
14809
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
14810
+ return _PromptBlocksPG.getDefaultIndexDefs(schemaPrefix);
14811
+ }
14812
+ async createDefaultIndexes() {
14813
+ if (this.#skipDefaultIndexes) {
14814
+ return;
14815
+ }
14816
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
14817
+ try {
14818
+ await this.#db.createIndex(indexDef);
14819
+ } catch {
14820
+ }
14821
+ }
14822
+ }
14823
+ async init() {
14824
+ await this.#db.createTable({ tableName: TABLE_PROMPT_BLOCKS, schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCKS] });
14825
+ await this.#db.createTable({
14826
+ tableName: TABLE_PROMPT_BLOCK_VERSIONS,
14827
+ schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCK_VERSIONS]
14828
+ });
14829
+ await this.#db.alterTable({
14830
+ tableName: TABLE_PROMPT_BLOCK_VERSIONS,
14831
+ schema: TABLE_SCHEMAS[TABLE_PROMPT_BLOCK_VERSIONS],
14832
+ ifNotExists: ["requestContextSchema"]
14833
+ });
14834
+ await this.createDefaultIndexes();
14835
+ await this.createCustomIndexes();
14836
+ }
14837
+ async createCustomIndexes() {
14838
+ if (!this.#indexes || this.#indexes.length === 0) {
14839
+ return;
14840
+ }
14841
+ for (const indexDef of this.#indexes) {
14842
+ try {
14843
+ await this.#db.createIndex(indexDef);
14844
+ } catch (error) {
14845
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
14846
+ }
14847
+ }
14848
+ }
14849
+ async dangerouslyClearAll() {
14850
+ await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCK_VERSIONS });
14851
+ await this.#db.clearTable({ tableName: TABLE_PROMPT_BLOCKS });
14852
+ }
14853
+ // ==========================================================================
14854
+ // Prompt Block CRUD Methods
14855
+ // ==========================================================================
14856
+ async getById(id) {
14857
+ try {
14858
+ const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
14859
+ const result = await this.#db.client.oneOrNone(`SELECT * FROM ${tableName} WHERE id = $1`, [id]);
14860
+ if (!result) {
14861
+ return null;
14862
+ }
14863
+ return this.parseBlockRow(result);
14864
+ } catch (error) {
14865
+ if (error instanceof MastraError) throw error;
14866
+ throw new MastraError(
14867
+ {
14868
+ id: createStorageErrorId("PG", "GET_PROMPT_BLOCK_BY_ID", "FAILED"),
14869
+ domain: ErrorDomain.STORAGE,
14870
+ category: ErrorCategory.THIRD_PARTY,
14871
+ details: { blockId: id }
14872
+ },
14873
+ error
14874
+ );
14875
+ }
14876
+ }
14877
+ async create(input) {
14878
+ const { promptBlock } = input;
14879
+ try {
14880
+ const tableName = getTableName2({ indexName: TABLE_PROMPT_BLOCKS, schemaName: getSchemaName2(this.#schema) });
14881
+ const now = /* @__PURE__ */ new Date();
14882
+ const nowIso = now.toISOString();
14883
+ await this.#db.client.none(
14884
+ `INSERT INTO ${tableName} (
11570
14885
  id, status, "activeVersionId", "authorId", metadata,
11571
14886
  "createdAt", "createdAtZ", "updatedAt", "updatedAtZ"
11572
14887
  ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
@@ -13509,16 +16824,39 @@ var SkillsPG = class _SkillsPG extends SkillsStorage {
13509
16824
  this.#skipDefaultIndexes = skipDefaultIndexes;
13510
16825
  this.#indexes = indexes?.filter((idx) => _SkillsPG.MANAGED_TABLES.includes(idx.table));
13511
16826
  }
13512
- getDefaultIndexDefinitions() {
16827
+ static getDefaultIndexDefs(schemaPrefix) {
13513
16828
  return [
13514
16829
  {
13515
- name: "idx_skill_versions_skill_version",
16830
+ name: `${schemaPrefix}idx_skill_versions_skill_version`,
13516
16831
  table: TABLE_SKILL_VERSIONS,
13517
16832
  columns: ["skillId", "versionNumber"],
13518
16833
  unique: true
13519
16834
  }
13520
16835
  ];
13521
16836
  }
16837
+ static getExportDDL(schemaName) {
16838
+ const statements = [];
16839
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
16840
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
16841
+ for (const tableName of _SkillsPG.MANAGED_TABLES) {
16842
+ statements.push(
16843
+ generateTableSQL({
16844
+ tableName,
16845
+ schema: TABLE_SCHEMAS[tableName],
16846
+ schemaName,
16847
+ includeAllConstraints: true
16848
+ })
16849
+ );
16850
+ }
16851
+ for (const idx of _SkillsPG.getDefaultIndexDefs(schemaPrefix)) {
16852
+ statements.push(generateIndexSQL(idx, schemaName));
16853
+ }
16854
+ return statements;
16855
+ }
16856
+ getDefaultIndexDefinitions() {
16857
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
16858
+ return _SkillsPG.getDefaultIndexDefs(schemaPrefix);
16859
+ }
13522
16860
  async createDefaultIndexes() {
13523
16861
  if (this.#skipDefaultIndexes) {
13524
16862
  return;
@@ -14216,6 +17554,254 @@ var SkillsPG = class _SkillsPG extends SkillsStorage {
14216
17554
  };
14217
17555
  }
14218
17556
  };
17557
+ function normaliseScope(raw) {
17558
+ const value = raw == null ? "per-author" : String(raw);
17559
+ if (value === "shared") return "shared";
17560
+ if (value === "caller-supplied") return "caller-supplied";
17561
+ return "per-author";
17562
+ }
17563
+ function rowToToolProviderConnection(row) {
17564
+ return {
17565
+ authorId: String(row.authorId),
17566
+ providerId: String(row.providerId),
17567
+ toolkit: String(row.toolkit),
17568
+ connectionId: String(row.connectionId),
17569
+ label: row.label == null ? null : String(row.label),
17570
+ scope: normaliseScope(row.scope),
17571
+ createdAt: new Date(String(row.createdAtZ ?? row.createdAt)),
17572
+ updatedAt: new Date(String(row.updatedAtZ ?? row.updatedAt))
17573
+ };
17574
+ }
17575
+ var ToolProviderConnectionsPG = class _ToolProviderConnectionsPG extends ToolProviderConnectionsStorage {
17576
+ #db;
17577
+ #schema;
17578
+ #skipDefaultIndexes;
17579
+ #indexes;
17580
+ static MANAGED_TABLES = [TABLE_TOOL_PROVIDER_CONNECTIONS];
17581
+ constructor(config) {
17582
+ super();
17583
+ const { client, schemaName, skipDefaultIndexes, indexes } = resolvePgConfig(config);
17584
+ this.#db = new PgDB({ client, schemaName, skipDefaultIndexes });
17585
+ this.#schema = schemaName || "public";
17586
+ this.#skipDefaultIndexes = skipDefaultIndexes;
17587
+ this.#indexes = indexes?.filter(
17588
+ (idx) => _ToolProviderConnectionsPG.MANAGED_TABLES.includes(idx.table)
17589
+ );
17590
+ }
17591
+ async init() {
17592
+ await this.#db.createTable({
17593
+ tableName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17594
+ schema: TABLE_SCHEMAS[TABLE_TOOL_PROVIDER_CONNECTIONS],
17595
+ compositePrimaryKey: ["authorId", "providerId", "connectionId"]
17596
+ });
17597
+ await this.createDefaultIndexes();
17598
+ await this.createCustomIndexes();
17599
+ }
17600
+ static getDefaultIndexDefs(schemaPrefix) {
17601
+ return [
17602
+ {
17603
+ name: `${schemaPrefix}idx_tool_provider_connections_author`,
17604
+ table: TABLE_TOOL_PROVIDER_CONNECTIONS,
17605
+ columns: ["authorId", "providerId", "toolkit"]
17606
+ }
17607
+ ];
17608
+ }
17609
+ static getExportDDL(schemaName) {
17610
+ const statements = [];
17611
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
17612
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
17613
+ statements.push(
17614
+ generateTableSQL({
17615
+ tableName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17616
+ schema: TABLE_SCHEMAS[TABLE_TOOL_PROVIDER_CONNECTIONS],
17617
+ schemaName,
17618
+ compositePrimaryKey: ["authorId", "providerId", "connectionId"],
17619
+ includeAllConstraints: true
17620
+ })
17621
+ );
17622
+ for (const idx of _ToolProviderConnectionsPG.getDefaultIndexDefs(schemaPrefix)) {
17623
+ statements.push(generateIndexSQL(idx, schemaName));
17624
+ }
17625
+ return statements;
17626
+ }
17627
+ getDefaultIndexDefinitions() {
17628
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
17629
+ return _ToolProviderConnectionsPG.getDefaultIndexDefs(schemaPrefix);
17630
+ }
17631
+ async createDefaultIndexes() {
17632
+ if (this.#skipDefaultIndexes) return;
17633
+ for (const indexDef of this.getDefaultIndexDefinitions()) {
17634
+ try {
17635
+ await this.#db.createIndex(indexDef);
17636
+ } catch (error) {
17637
+ this.logger?.warn?.(`Failed to create index ${indexDef.name}:`, error);
17638
+ }
17639
+ }
17640
+ }
17641
+ async createCustomIndexes() {
17642
+ if (!this.#indexes || this.#indexes.length === 0) return;
17643
+ for (const indexDef of this.#indexes) {
17644
+ try {
17645
+ await this.#db.createIndex(indexDef);
17646
+ } catch (error) {
17647
+ this.logger?.warn?.(`Failed to create custom index ${indexDef.name}:`, error);
17648
+ }
17649
+ }
17650
+ }
17651
+ async dangerouslyClearAll() {
17652
+ await this.#db.clearTable({ tableName: TABLE_TOOL_PROVIDER_CONNECTIONS });
17653
+ }
17654
+ async getConnectionById({
17655
+ authorId,
17656
+ providerId,
17657
+ connectionId
17658
+ }) {
17659
+ const tableName = getTableName2({
17660
+ indexName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17661
+ schemaName: getSchemaName2(this.#schema)
17662
+ });
17663
+ try {
17664
+ const row = await this.#db.client.oneOrNone(
17665
+ `SELECT * FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`,
17666
+ [authorId, providerId, connectionId]
17667
+ );
17668
+ return row ? rowToToolProviderConnection(row) : null;
17669
+ } catch (error) {
17670
+ throw new MastraError(
17671
+ {
17672
+ id: createStorageErrorId("PG", "TOOL_PROVIDER_CONNECTION_GET", "FAILED"),
17673
+ domain: ErrorDomain.STORAGE,
17674
+ category: ErrorCategory.THIRD_PARTY,
17675
+ details: { authorId, providerId, connectionId }
17676
+ },
17677
+ error
17678
+ );
17679
+ }
17680
+ }
17681
+ async upsertConnection(input) {
17682
+ const { authorId, providerId, toolkit, connectionId, label } = input;
17683
+ const tableName = getTableName2({
17684
+ indexName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17685
+ schemaName: getSchemaName2(this.#schema)
17686
+ });
17687
+ const now = /* @__PURE__ */ new Date();
17688
+ const nowIso = now.toISOString();
17689
+ const labelValue = label == null ? null : label;
17690
+ try {
17691
+ return await this.#db.client.tx(async (t) => {
17692
+ const existing = await t.oneOrNone(
17693
+ `SELECT "createdAt", "createdAtZ", scope FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3 LIMIT 1`,
17694
+ [authorId, providerId, connectionId]
17695
+ );
17696
+ const existingCreatedAt = existing ? existing.createdAtZ ?? existing.createdAt : null;
17697
+ const createdAt = existingCreatedAt != null ? new Date(existingCreatedAt).toISOString() : nowIso;
17698
+ const existingScope = existing && existing.scope != null ? normaliseScope(existing.scope) : void 0;
17699
+ const scope = input.scope ?? existingScope ?? "per-author";
17700
+ await t.none(
17701
+ `INSERT INTO ${tableName} ("authorId", "providerId", toolkit, "connectionId", label, scope, "createdAt", "createdAtZ", "updatedAt", "updatedAtZ")
17702
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
17703
+ ON CONFLICT ("authorId", "providerId", "connectionId") DO UPDATE SET
17704
+ toolkit = EXCLUDED.toolkit,
17705
+ label = EXCLUDED.label,
17706
+ scope = EXCLUDED.scope,
17707
+ "updatedAt" = EXCLUDED."updatedAt",
17708
+ "updatedAtZ" = EXCLUDED."updatedAtZ"`,
17709
+ [authorId, providerId, toolkit, connectionId, labelValue, scope, createdAt, createdAt, nowIso, nowIso]
17710
+ );
17711
+ return {
17712
+ authorId,
17713
+ providerId,
17714
+ toolkit,
17715
+ connectionId,
17716
+ label: labelValue,
17717
+ scope,
17718
+ createdAt: new Date(createdAt),
17719
+ updatedAt: now
17720
+ };
17721
+ });
17722
+ } catch (error) {
17723
+ throw new MastraError(
17724
+ {
17725
+ id: createStorageErrorId("PG", "TOOL_PROVIDER_CONNECTION_UPSERT", "FAILED"),
17726
+ domain: ErrorDomain.STORAGE,
17727
+ category: ErrorCategory.THIRD_PARTY,
17728
+ details: { authorId, providerId, connectionId }
17729
+ },
17730
+ error
17731
+ );
17732
+ }
17733
+ }
17734
+ async listConnectionsByAuthor({
17735
+ authorId,
17736
+ providerId,
17737
+ toolkit,
17738
+ scope
17739
+ }) {
17740
+ const tableName = getTableName2({
17741
+ indexName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17742
+ schemaName: getSchemaName2(this.#schema)
17743
+ });
17744
+ try {
17745
+ const clauses = [];
17746
+ const args = [];
17747
+ if (authorId !== void 0) {
17748
+ args.push(authorId);
17749
+ clauses.push(`"authorId" = $${args.length}`);
17750
+ }
17751
+ if (providerId) {
17752
+ args.push(providerId);
17753
+ clauses.push(`"providerId" = $${args.length}`);
17754
+ }
17755
+ if (toolkit) {
17756
+ args.push(toolkit);
17757
+ clauses.push(`toolkit = $${args.length}`);
17758
+ }
17759
+ if (scope) {
17760
+ args.push(scope);
17761
+ clauses.push(`scope = $${args.length}`);
17762
+ }
17763
+ const whereClause = clauses.length > 0 ? ` WHERE ${clauses.join(" AND ")}` : "";
17764
+ const rows = await this.#db.client.manyOrNone(`SELECT * FROM ${tableName}${whereClause}`, args);
17765
+ return rows.map((row) => rowToToolProviderConnection(row));
17766
+ } catch (error) {
17767
+ throw new MastraError(
17768
+ {
17769
+ id: createStorageErrorId("PG", "TOOL_PROVIDER_CONNECTION_LIST", "FAILED"),
17770
+ domain: ErrorDomain.STORAGE,
17771
+ category: ErrorCategory.THIRD_PARTY,
17772
+ details: { authorId: authorId ?? "", providerId: providerId ?? "", toolkit: toolkit ?? "" }
17773
+ },
17774
+ error
17775
+ );
17776
+ }
17777
+ }
17778
+ async deleteConnection({
17779
+ authorId,
17780
+ providerId,
17781
+ connectionId
17782
+ }) {
17783
+ const tableName = getTableName2({
17784
+ indexName: TABLE_TOOL_PROVIDER_CONNECTIONS,
17785
+ schemaName: getSchemaName2(this.#schema)
17786
+ });
17787
+ try {
17788
+ await this.#db.client.none(
17789
+ `DELETE FROM ${tableName} WHERE "authorId" = $1 AND "providerId" = $2 AND "connectionId" = $3`,
17790
+ [authorId, providerId, connectionId]
17791
+ );
17792
+ } catch (error) {
17793
+ throw new MastraError(
17794
+ {
17795
+ id: createStorageErrorId("PG", "TOOL_PROVIDER_CONNECTION_DELETE", "FAILED"),
17796
+ domain: ErrorDomain.STORAGE,
17797
+ category: ErrorCategory.THIRD_PARTY,
17798
+ details: { authorId, providerId, connectionId }
17799
+ },
17800
+ error
17801
+ );
17802
+ }
17803
+ }
17804
+ };
14219
17805
  function getSchemaName7(schema) {
14220
17806
  return schema ? `"${schema}"` : '"public"';
14221
17807
  }
@@ -14549,7 +18135,7 @@ var WorkflowsPG = class _WorkflowsPG extends WorkflowsStorage {
14549
18135
  async listWorkflowRuns({
14550
18136
  workflowName,
14551
18137
  fromDate,
14552
- toDate,
18138
+ toDate: toDate2,
14553
18139
  perPage,
14554
18140
  page,
14555
18141
  resourceId,
@@ -14586,9 +18172,9 @@ var WorkflowsPG = class _WorkflowsPG extends WorkflowsStorage {
14586
18172
  values.push(fromDate);
14587
18173
  paramIndex++;
14588
18174
  }
14589
- if (toDate) {
18175
+ if (toDate2) {
14590
18176
  conditions.push(`"createdAt" <= $${paramIndex}`);
14591
- values.push(toDate);
18177
+ values.push(toDate2);
14592
18178
  paramIndex++;
14593
18179
  }
14594
18180
  const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
@@ -14656,16 +18242,39 @@ var WorkspacesPG = class _WorkspacesPG extends WorkspacesStorage {
14656
18242
  this.#skipDefaultIndexes = skipDefaultIndexes;
14657
18243
  this.#indexes = indexes?.filter((idx) => _WorkspacesPG.MANAGED_TABLES.includes(idx.table));
14658
18244
  }
14659
- getDefaultIndexDefinitions() {
18245
+ static getDefaultIndexDefs(schemaPrefix) {
14660
18246
  return [
14661
18247
  {
14662
- name: "idx_workspace_versions_workspace_version",
18248
+ name: `${schemaPrefix}idx_workspace_versions_workspace_version`,
14663
18249
  table: TABLE_WORKSPACE_VERSIONS,
14664
18250
  columns: ["workspaceId", "versionNumber"],
14665
18251
  unique: true
14666
18252
  }
14667
18253
  ];
14668
18254
  }
18255
+ static getExportDDL(schemaName) {
18256
+ const statements = [];
18257
+ const parsedSchema = schemaName ? parseSqlIdentifier(schemaName, "schema name") : "";
18258
+ const schemaPrefix = parsedSchema && parsedSchema !== "public" ? `${parsedSchema}_` : "";
18259
+ for (const tableName of _WorkspacesPG.MANAGED_TABLES) {
18260
+ statements.push(
18261
+ generateTableSQL({
18262
+ tableName,
18263
+ schema: TABLE_SCHEMAS[tableName],
18264
+ schemaName,
18265
+ includeAllConstraints: true
18266
+ })
18267
+ );
18268
+ }
18269
+ for (const idx of _WorkspacesPG.getDefaultIndexDefs(schemaPrefix)) {
18270
+ statements.push(generateIndexSQL(idx, schemaName));
18271
+ }
18272
+ return statements;
18273
+ }
18274
+ getDefaultIndexDefinitions() {
18275
+ const schemaPrefix = this.#schema !== "public" ? `${this.#schema}_` : "";
18276
+ return _WorkspacesPG.getDefaultIndexDefs(schemaPrefix);
18277
+ }
14669
18278
  async createDefaultIndexes() {
14670
18279
  if (this.#skipDefaultIndexes) {
14671
18280
  return;
@@ -15320,6 +18929,26 @@ function buildConnectionStringPoolConfig(config, defaults) {
15320
18929
  // src/storage/index.ts
15321
18930
  var DEFAULT_MAX_CONNECTIONS = 20;
15322
18931
  var DEFAULT_IDLE_TIMEOUT_MS = 3e4;
18932
+ function createConnectionStringPool(config) {
18933
+ return new Pool(
18934
+ buildConnectionStringPoolConfig(config, {
18935
+ max: DEFAULT_MAX_CONNECTIONS,
18936
+ idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS
18937
+ })
18938
+ );
18939
+ }
18940
+ function createHostPool(config) {
18941
+ return new Pool({
18942
+ host: config.host,
18943
+ port: config.port,
18944
+ database: config.database,
18945
+ user: config.user,
18946
+ password: config.password,
18947
+ ssl: config.ssl,
18948
+ max: config.max ?? DEFAULT_MAX_CONNECTIONS,
18949
+ idleTimeoutMillis: config.idleTimeoutMillis ?? DEFAULT_IDLE_TIMEOUT_MS
18950
+ });
18951
+ }
15323
18952
  var ALL_DOMAINS = [
15324
18953
  MemoryPG,
15325
18954
  NotificationsPG,
@@ -15328,6 +18957,12 @@ var ALL_DOMAINS = [
15328
18957
  ScorerDefinitionsPG,
15329
18958
  PromptBlocksPG,
15330
18959
  AgentsPG,
18960
+ MCPClientsPG,
18961
+ MCPServersPG,
18962
+ WorkspacesPG,
18963
+ SkillsPG,
18964
+ BlobsPG,
18965
+ ToolProviderConnectionsPG,
15331
18966
  WorkflowsPG,
15332
18967
  DatasetsPG,
15333
18968
  ExperimentsPG,
@@ -15352,6 +18987,7 @@ var PostgresStore = class extends MastraCompositeStore {
15352
18987
  #pool;
15353
18988
  #db;
15354
18989
  #ownsPool;
18990
+ #poolClosed = false;
15355
18991
  schema;
15356
18992
  isInitialized = false;
15357
18993
  stores;
@@ -15388,6 +19024,7 @@ var PostgresStore = class extends MastraCompositeStore {
15388
19024
  workspaces: new WorkspacesPG(domainConfig),
15389
19025
  skills: new SkillsPG(domainConfig),
15390
19026
  favorites: new FavoritesPG(domainConfig),
19027
+ toolProviderConnections: new ToolProviderConnectionsPG(domainConfig),
15391
19028
  blobs: new BlobsPG(domainConfig),
15392
19029
  datasets: new DatasetsPG(domainConfig),
15393
19030
  experiments: new ExperimentsPG(domainConfig),
@@ -15408,24 +19045,10 @@ var PostgresStore = class extends MastraCompositeStore {
15408
19045
  }
15409
19046
  createPool(config) {
15410
19047
  if (isConnectionStringConfig(config)) {
15411
- return new Pool(
15412
- buildConnectionStringPoolConfig(config, {
15413
- max: DEFAULT_MAX_CONNECTIONS,
15414
- idleTimeoutMillis: DEFAULT_IDLE_TIMEOUT_MS
15415
- })
15416
- );
19048
+ return createConnectionStringPool(config);
15417
19049
  }
15418
19050
  if (isHostConfig(config)) {
15419
- return new Pool({
15420
- host: config.host,
15421
- port: config.port,
15422
- database: config.database,
15423
- user: config.user,
15424
- password: config.password,
15425
- ssl: config.ssl,
15426
- max: config.max ?? DEFAULT_MAX_CONNECTIONS,
15427
- idleTimeoutMillis: config.idleTimeoutMillis ?? DEFAULT_IDLE_TIMEOUT_MS
15428
- });
19051
+ return createHostPool(config);
15429
19052
  }
15430
19053
  if (isCloudSqlConfig(config)) {
15431
19054
  return new Pool(config);
@@ -15475,13 +19098,81 @@ var PostgresStore = class extends MastraCompositeStore {
15475
19098
  /**
15476
19099
  * Closes the connection pool if it was created by this store.
15477
19100
  * If a pool was passed in via config, it will not be closed.
19101
+ * Safe to call multiple times — subsequent calls are no-ops.
15478
19102
  */
15479
19103
  async close() {
15480
- if (this.#ownsPool) {
19104
+ if (this.#ownsPool && !this.#poolClosed) {
19105
+ this.#poolClosed = true;
15481
19106
  await this.#pool.end();
15482
19107
  }
15483
19108
  }
15484
19109
  };
19110
+ function isSameConnectionTarget(primary, observability) {
19111
+ if ("pool" in primary && "pool" in observability) {
19112
+ return primary.pool === observability.pool;
19113
+ }
19114
+ if ("connectionString" in primary && "connectionString" in observability) {
19115
+ return primary.connectionString === observability.connectionString;
19116
+ }
19117
+ if ("host" in primary && "host" in observability) {
19118
+ return primary.host === observability.host && (primary.port ?? 5432) === (observability.port ?? 5432) && primary.database === observability.database;
19119
+ }
19120
+ return false;
19121
+ }
19122
+ var COLLISION_WARNING = "PostgresStoreVNext: the `observability` connection appears to point at the same Postgres instance as the primary store. For production workloads, point observability at a dedicated Postgres instance to avoid degrading your application database performance.";
19123
+ var PostgresStoreVNext = class extends PostgresStore {
19124
+ #observabilityPool;
19125
+ #ownsObservabilityPool = false;
19126
+ #observabilityPoolClosed = false;
19127
+ constructor(config) {
19128
+ super(config);
19129
+ this.name = "PostgresStoreVNext";
19130
+ const obsConfig = config.observability;
19131
+ if (isSameConnectionTarget(config, obsConfig)) {
19132
+ console.warn(COLLISION_WARNING);
19133
+ }
19134
+ const built = this.#createObservabilityClient(obsConfig);
19135
+ const observabilityClient = built.client;
19136
+ this.#observabilityPool = built.pool;
19137
+ this.#ownsObservabilityPool = built.owned;
19138
+ const observability = new ObservabilityStoragePostgresVNext({
19139
+ client: observabilityClient,
19140
+ schemaName: obsConfig.schemaName ?? config.schemaName,
19141
+ partitioning: obsConfig.partitioning,
19142
+ discovery: obsConfig.discovery
19143
+ });
19144
+ this.stores = {
19145
+ ...this.stores,
19146
+ observability
19147
+ };
19148
+ }
19149
+ #createObservabilityClient(cfg) {
19150
+ if ("pool" in cfg && cfg.pool) {
19151
+ return { client: new PoolAdapter(cfg.pool), pool: cfg.pool, owned: false };
19152
+ }
19153
+ if ("connectionString" in cfg && typeof cfg.connectionString === "string") {
19154
+ const pool2 = createConnectionStringPool(cfg);
19155
+ return { client: new PoolAdapter(pool2), pool: pool2, owned: true };
19156
+ }
19157
+ if ("host" in cfg) {
19158
+ const pool2 = createHostPool(cfg);
19159
+ return { client: new PoolAdapter(pool2), pool: pool2, owned: true };
19160
+ }
19161
+ const pool = new Pool(cfg);
19162
+ return { client: new PoolAdapter(pool), pool, owned: true };
19163
+ }
19164
+ /**
19165
+ * Closes both the primary pool (when owned) and the observability pool
19166
+ * (when this store created it). Safe to call multiple times.
19167
+ */
19168
+ async close() {
19169
+ await super.close();
19170
+ if (this.#ownsObservabilityPool && this.#observabilityPool && !this.#observabilityPoolClosed) {
19171
+ this.#observabilityPoolClosed = true;
19172
+ await this.#observabilityPool.end();
19173
+ }
19174
+ }
19175
+ };
15485
19176
 
15486
19177
  // src/vector/prompt.ts
15487
19178
  var PGVECTOR_PROMPT = `When querying PG Vector, you can ONLY use the operators listed below. Any other operators will be rejected.
@@ -15582,6 +19273,6 @@ Example Complex Query:
15582
19273
  ]
15583
19274
  }`;
15584
19275
 
15585
- export { AgentsPG, BackgroundTasksPG, BlobsPG, ChannelsPG, DatasetsPG, ExperimentsPG, FavoritesPG, MCPClientsPG, MCPServersPG, MemoryPG, NotificationsPG, ObservabilityPG, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PromptBlocksPG, SchedulesPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
19276
+ export { AgentsPG, BackgroundTasksPG, BlobsPG, ChannelsPG, DatasetsPG, ExperimentsPG, FavoritesPG, MCPClientsPG, MCPServersPG, MemoryPG, NotificationsPG, ObservabilityPG, ObservabilityStoragePostgresVNext, PGVECTOR_PROMPT, PgVector, PoolAdapter, PostgresStore, PostgresStoreVNext, PromptBlocksPG, SchedulesPG, ScorerDefinitionsPG, ScoresPG, SkillsPG, ToolProviderConnectionsPG, WorkflowsPG, WorkspacesPG, exportSchemas };
15586
19277
  //# sourceMappingURL=index.js.map
15587
19278
  //# sourceMappingURL=index.js.map