@mastra/mssql 1.0.0-beta.12 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -0
- package/dist/docs/README.md +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/SOURCE_MAP.json +1 -1
- package/dist/index.cjs +207 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +208 -7
- package/dist/index.js.map +1 -1
- package/dist/storage/db/index.d.ts +45 -0
- package/dist/storage/db/index.d.ts.map +1 -1
- package/dist/storage/domains/observability/index.d.ts +23 -0
- package/dist/storage/domains/observability/index.d.ts.map +1 -1
- package/dist/storage/index.d.ts +2 -2
- package/dist/storage/index.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
|
|
2
|
-
import { MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, ObservabilityStorage, TABLE_SPANS, SPAN_SCHEMA, listTracesArgsSchema, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT,
|
|
2
|
+
import { MemoryStorage, TABLE_THREADS, TABLE_MESSAGES, TABLE_RESOURCES, TABLE_SCHEMAS, createStorageErrorId, normalizePerPage, calculatePagination, ObservabilityStorage, TABLE_SPANS, SPAN_SCHEMA, listTracesArgsSchema, ScoresStorage, TABLE_SCORERS, WorkflowsStorage, TABLE_WORKFLOW_SNAPSHOT, MastraCompositeStore, TraceStatus, getDefaultValue, transformScoreRow as transformScoreRow$1 } from '@mastra/core/storage';
|
|
3
3
|
import sql from 'mssql';
|
|
4
4
|
import { MessageList } from '@mastra/core/agent';
|
|
5
5
|
import { MastraBase } from '@mastra/core/base';
|
|
@@ -334,15 +334,49 @@ ${columns}
|
|
|
334
334
|
);
|
|
335
335
|
const pkExists = Array.isArray(pkResult.recordset) && pkResult.recordset.length > 0;
|
|
336
336
|
if (!pkExists) {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
337
|
+
const duplicateInfo = await this.checkForDuplicateSpans();
|
|
338
|
+
if (duplicateInfo.hasDuplicates) {
|
|
339
|
+
const errorMessage = `
|
|
340
|
+
===========================================================================
|
|
341
|
+
MIGRATION REQUIRED: Duplicate spans detected in ${duplicateInfo.tableName}
|
|
342
|
+
===========================================================================
|
|
343
|
+
|
|
344
|
+
Found ${duplicateInfo.duplicateCount} duplicate (traceId, spanId) combinations.
|
|
345
|
+
|
|
346
|
+
The spans table requires a unique constraint on (traceId, spanId), but your
|
|
347
|
+
database contains duplicate entries that must be resolved first.
|
|
348
|
+
|
|
349
|
+
To fix this, run the manual migration command:
|
|
350
|
+
|
|
351
|
+
npx mastra migrate
|
|
352
|
+
|
|
353
|
+
This command will:
|
|
354
|
+
1. Remove duplicate spans (keeping the most complete/recent version)
|
|
355
|
+
2. Add the required unique constraint
|
|
356
|
+
|
|
357
|
+
Note: This migration may take some time for large tables.
|
|
358
|
+
===========================================================================
|
|
359
|
+
`;
|
|
360
|
+
throw new MastraError({
|
|
361
|
+
id: createStorageErrorId("MSSQL", "MIGRATION_REQUIRED", "DUPLICATE_SPANS"),
|
|
362
|
+
domain: ErrorDomain.STORAGE,
|
|
363
|
+
category: ErrorCategory.USER,
|
|
364
|
+
text: errorMessage
|
|
365
|
+
});
|
|
366
|
+
} else {
|
|
367
|
+
try {
|
|
368
|
+
const addPkSql = `ALTER TABLE ${getTableName({ indexName: tableName, schemaName: getSchemaName(this.schemaName) })} ADD CONSTRAINT [${pkConstraintName}] PRIMARY KEY ([traceId], [spanId])`;
|
|
369
|
+
await this.pool.request().query(addPkSql);
|
|
370
|
+
} catch (pkError) {
|
|
371
|
+
this.logger?.warn?.(`Failed to add composite primary key to spans table:`, pkError);
|
|
372
|
+
}
|
|
342
373
|
}
|
|
343
374
|
}
|
|
344
375
|
}
|
|
345
376
|
} catch (error) {
|
|
377
|
+
if (error instanceof MastraError) {
|
|
378
|
+
throw error;
|
|
379
|
+
}
|
|
346
380
|
throw new MastraError(
|
|
347
381
|
{
|
|
348
382
|
id: createStorageErrorId("MSSQL", "CREATE_TABLE", "FAILED"),
|
|
@@ -384,6 +418,154 @@ ${columns}
|
|
|
384
418
|
this.logger?.warn?.(`Failed to migrate spans table ${fullTableName}:`, error);
|
|
385
419
|
}
|
|
386
420
|
}
|
|
421
|
+
/**
|
|
422
|
+
* Deduplicates spans with the same (traceId, spanId) combination.
|
|
423
|
+
* This is needed for databases that existed before the unique constraint was added.
|
|
424
|
+
*
|
|
425
|
+
* Priority for keeping spans:
|
|
426
|
+
* 1. Completed spans (endedAt IS NOT NULL) over incomplete spans
|
|
427
|
+
* 2. Most recent updatedAt
|
|
428
|
+
* 3. Most recent createdAt (as tiebreaker)
|
|
429
|
+
*
|
|
430
|
+
* Note: This prioritizes migration completion over perfect data preservation.
|
|
431
|
+
* Old trace data may be lost, which is acceptable for this use case.
|
|
432
|
+
*/
|
|
433
|
+
async deduplicateSpans() {
|
|
434
|
+
const fullTableName = getTableName({ indexName: TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
|
|
435
|
+
try {
|
|
436
|
+
const duplicateCheck = await this.pool.request().query(`
|
|
437
|
+
SELECT TOP 1 1 as has_duplicates
|
|
438
|
+
FROM ${fullTableName}
|
|
439
|
+
GROUP BY [traceId], [spanId]
|
|
440
|
+
HAVING COUNT(*) > 1
|
|
441
|
+
`);
|
|
442
|
+
if (!duplicateCheck.recordset || duplicateCheck.recordset.length === 0) {
|
|
443
|
+
this.logger?.debug?.(`No duplicate spans found in ${fullTableName}`);
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
this.logger?.info?.(`Duplicate spans detected in ${fullTableName}, starting deduplication...`);
|
|
447
|
+
const result = await this.pool.request().query(`
|
|
448
|
+
WITH RankedSpans AS (
|
|
449
|
+
SELECT *, ROW_NUMBER() OVER (
|
|
450
|
+
PARTITION BY [traceId], [spanId]
|
|
451
|
+
ORDER BY
|
|
452
|
+
CASE WHEN [endedAt] IS NOT NULL THEN 0 ELSE 1 END,
|
|
453
|
+
[updatedAt] DESC,
|
|
454
|
+
[createdAt] DESC
|
|
455
|
+
) as rn
|
|
456
|
+
FROM ${fullTableName}
|
|
457
|
+
)
|
|
458
|
+
DELETE FROM RankedSpans WHERE rn > 1
|
|
459
|
+
`);
|
|
460
|
+
this.logger?.info?.(
|
|
461
|
+
`Deduplication complete: removed ${result.rowsAffected?.[0] ?? 0} duplicate spans from ${fullTableName}`
|
|
462
|
+
);
|
|
463
|
+
} catch (error) {
|
|
464
|
+
this.logger?.warn?.("Failed to deduplicate spans:", error);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Checks for duplicate (traceId, spanId) combinations in the spans table.
|
|
469
|
+
* Returns information about duplicates for logging/CLI purposes.
|
|
470
|
+
*/
|
|
471
|
+
async checkForDuplicateSpans() {
|
|
472
|
+
const fullTableName = getTableName({ indexName: TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
|
|
473
|
+
try {
|
|
474
|
+
const result = await this.pool.request().query(`
|
|
475
|
+
SELECT COUNT(*) as duplicate_count
|
|
476
|
+
FROM (
|
|
477
|
+
SELECT [traceId], [spanId]
|
|
478
|
+
FROM ${fullTableName}
|
|
479
|
+
GROUP BY [traceId], [spanId]
|
|
480
|
+
HAVING COUNT(*) > 1
|
|
481
|
+
) duplicates
|
|
482
|
+
`);
|
|
483
|
+
const duplicateCount = result.recordset?.[0]?.duplicate_count ?? 0;
|
|
484
|
+
return {
|
|
485
|
+
hasDuplicates: duplicateCount > 0,
|
|
486
|
+
duplicateCount,
|
|
487
|
+
tableName: fullTableName
|
|
488
|
+
};
|
|
489
|
+
} catch (error) {
|
|
490
|
+
this.logger?.debug?.(`Could not check for duplicates: ${error}`);
|
|
491
|
+
return { hasDuplicates: false, duplicateCount: 0, tableName: fullTableName };
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
/**
|
|
495
|
+
* Checks if the PRIMARY KEY constraint on (traceId, spanId) already exists on the spans table.
|
|
496
|
+
*/
|
|
497
|
+
async spansPrimaryKeyExists() {
|
|
498
|
+
const schemaPrefix = this.schemaName ? `${parseSqlIdentifier(this.schemaName, "schema name")}_` : "";
|
|
499
|
+
const pkConstraintName = `${schemaPrefix}mastra_ai_spans_traceid_spanid_pk`;
|
|
500
|
+
const checkPkRequest = this.pool.request();
|
|
501
|
+
checkPkRequest.input("constraintName", pkConstraintName);
|
|
502
|
+
const pkResult = await checkPkRequest.query(
|
|
503
|
+
`SELECT 1 AS found FROM sys.key_constraints WHERE name = @constraintName`
|
|
504
|
+
);
|
|
505
|
+
return Array.isArray(pkResult.recordset) && pkResult.recordset.length > 0;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Manually run the spans migration to deduplicate and add the unique constraint.
|
|
509
|
+
* This is intended to be called from the CLI when duplicates are detected.
|
|
510
|
+
*
|
|
511
|
+
* @returns Migration result with status and details
|
|
512
|
+
*/
|
|
513
|
+
async migrateSpans() {
|
|
514
|
+
const fullTableName = getTableName({ indexName: TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
|
|
515
|
+
const pkExists = await this.spansPrimaryKeyExists();
|
|
516
|
+
if (pkExists) {
|
|
517
|
+
return {
|
|
518
|
+
success: true,
|
|
519
|
+
alreadyMigrated: true,
|
|
520
|
+
duplicatesRemoved: 0,
|
|
521
|
+
message: `Migration already complete. PRIMARY KEY constraint exists on ${fullTableName}.`
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
const duplicateInfo = await this.checkForDuplicateSpans();
|
|
525
|
+
if (duplicateInfo.hasDuplicates) {
|
|
526
|
+
this.logger?.info?.(
|
|
527
|
+
`Found ${duplicateInfo.duplicateCount} duplicate (traceId, spanId) combinations. Starting deduplication...`
|
|
528
|
+
);
|
|
529
|
+
await this.deduplicateSpans();
|
|
530
|
+
} else {
|
|
531
|
+
this.logger?.info?.(`No duplicate spans found.`);
|
|
532
|
+
}
|
|
533
|
+
const schemaPrefix = this.schemaName ? `${parseSqlIdentifier(this.schemaName, "schema name")}_` : "";
|
|
534
|
+
const pkConstraintName = `${schemaPrefix}mastra_ai_spans_traceid_spanid_pk`;
|
|
535
|
+
const addPkSql = `ALTER TABLE ${fullTableName} ADD CONSTRAINT [${pkConstraintName}] PRIMARY KEY ([traceId], [spanId])`;
|
|
536
|
+
await this.pool.request().query(addPkSql);
|
|
537
|
+
return {
|
|
538
|
+
success: true,
|
|
539
|
+
alreadyMigrated: false,
|
|
540
|
+
duplicatesRemoved: duplicateInfo.duplicateCount,
|
|
541
|
+
message: duplicateInfo.hasDuplicates ? `Migration complete. Removed duplicates and added PRIMARY KEY constraint to ${fullTableName}.` : `Migration complete. Added PRIMARY KEY constraint to ${fullTableName}.`
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Check migration status for the spans table.
|
|
546
|
+
* Returns information about whether migration is needed.
|
|
547
|
+
*/
|
|
548
|
+
async checkSpansMigrationStatus() {
|
|
549
|
+
const fullTableName = getTableName({ indexName: TABLE_SPANS, schemaName: getSchemaName(this.schemaName) });
|
|
550
|
+
const pkExists = await this.spansPrimaryKeyExists();
|
|
551
|
+
if (pkExists) {
|
|
552
|
+
return {
|
|
553
|
+
needsMigration: false,
|
|
554
|
+
hasDuplicates: false,
|
|
555
|
+
duplicateCount: 0,
|
|
556
|
+
constraintExists: true,
|
|
557
|
+
tableName: fullTableName
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
const duplicateInfo = await this.checkForDuplicateSpans();
|
|
561
|
+
return {
|
|
562
|
+
needsMigration: true,
|
|
563
|
+
hasDuplicates: duplicateInfo.hasDuplicates,
|
|
564
|
+
duplicateCount: duplicateInfo.duplicateCount,
|
|
565
|
+
constraintExists: false,
|
|
566
|
+
tableName: fullTableName
|
|
567
|
+
};
|
|
568
|
+
}
|
|
387
569
|
/**
|
|
388
570
|
* Alters table schema to add columns if they don't exist
|
|
389
571
|
* @param tableName Name of the table
|
|
@@ -2262,6 +2444,22 @@ var ObservabilityMSSQL = class _ObservabilityMSSQL extends ObservabilityStorage
|
|
|
2262
2444
|
async dangerouslyClearAll() {
|
|
2263
2445
|
await this.db.clearTable({ tableName: TABLE_SPANS });
|
|
2264
2446
|
}
|
|
2447
|
+
/**
|
|
2448
|
+
* Manually run the spans migration to deduplicate and add the unique constraint.
|
|
2449
|
+
* This is intended to be called from the CLI when duplicates are detected.
|
|
2450
|
+
*
|
|
2451
|
+
* @returns Migration result with status and details
|
|
2452
|
+
*/
|
|
2453
|
+
async migrateSpans() {
|
|
2454
|
+
return this.db.migrateSpans();
|
|
2455
|
+
}
|
|
2456
|
+
/**
|
|
2457
|
+
* Check migration status for the spans table.
|
|
2458
|
+
* Returns information about whether migration is needed.
|
|
2459
|
+
*/
|
|
2460
|
+
async checkSpansMigrationStatus() {
|
|
2461
|
+
return this.db.checkSpansMigrationStatus();
|
|
2462
|
+
}
|
|
2265
2463
|
get tracingStrategy() {
|
|
2266
2464
|
return {
|
|
2267
2465
|
preferred: "batch-with-updates",
|
|
@@ -3661,7 +3859,7 @@ var WorkflowsMSSQL = class _WorkflowsMSSQL extends WorkflowsStorage {
|
|
|
3661
3859
|
var isPoolConfig = (config) => {
|
|
3662
3860
|
return "pool" in config;
|
|
3663
3861
|
};
|
|
3664
|
-
var MSSQLStore = class extends
|
|
3862
|
+
var MSSQLStore = class extends MastraCompositeStore {
|
|
3665
3863
|
pool;
|
|
3666
3864
|
schema;
|
|
3667
3865
|
isConnected = null;
|
|
@@ -3732,6 +3930,9 @@ var MSSQLStore = class extends MastraStorage {
|
|
|
3732
3930
|
await super.init();
|
|
3733
3931
|
} catch (error) {
|
|
3734
3932
|
this.isConnected = null;
|
|
3933
|
+
if (error instanceof MastraError) {
|
|
3934
|
+
throw error;
|
|
3935
|
+
}
|
|
3735
3936
|
throw new MastraError(
|
|
3736
3937
|
{
|
|
3737
3938
|
id: createStorageErrorId("MSSQL", "INIT", "FAILED"),
|