Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion packages/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@
"devDependencies": {
"@opentelemetry/sdk-trace-base": "^2.8.0",
"@stoplight/spectral-cli": "^6.15.0",
"@total-typescript/shoehorn": "^0.1.2",
"@types/compression": "^1.7.3",
"@types/cors": "^2.8.14",
"@types/express": "^4.17.13",
Expand Down Expand Up @@ -106,7 +107,7 @@
"dev-task": "DOTENV_CONFIG_PATH=.env.development nodemon --exec 'ts-node' --transpile-only -r tsconfig-paths/register -r dotenv-expand/config -r ./src/telemetry.ts ./src/tasks/index.ts",
"build": "rimraf ./build && tsc -p tsconfig.build.json && tsc-alias -p tsconfig.build.json && cp -r ./src/opamp/proto ./build/opamp/",
"build:vercel": "rimraf ./build && tsc -p tsconfig.vercel.json && tsc-alias -p tsconfig.vercel.json && cp -r ./src/opamp/proto ./build/opamp/",
"lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 302 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'",
"lint": "node ../../scripts/ci/oxlint-warnings.mjs --max-warnings 173 && yarn run -T oxfmt --check 'src/**/*.ts' 'scripts/**/*.ts'",
"lint:fix": "yarn run -T oxlint --fix && yarn run -T oxfmt 'src/**/*.ts' 'scripts/**/*.ts'",
"ci:lint": "yarn lint && yarn tsc --noEmit && yarn lint:openapi",
"ci:unit": "jest --ci --coverage",
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/controllers/__tests__/ai.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { fromPartial } from '@total-typescript/shoehorn';
import type { LanguageModel } from 'ai';

const mockAnthropicModel = {
const mockAnthropicModel: LanguageModel = fromPartial({
modelId: 'claude-sonnet-4-5-20250929',
} as unknown as LanguageModel;
});

const mockOpenAIModel = {
const mockOpenAIModel: LanguageModel = fromPartial({
modelId: 'gpt-4o',
} as unknown as LanguageModel;
});

const mockAnthropicFactory = jest.fn((_model?: string) => mockAnthropicModel);
const mockCreateAnthropic = jest.fn(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { ClickHouseError } from '@clickhouse/client-common';
import { ClickHouseQueryError } from '@hyperdx/common-utils/dist/clickhouse';
import { fromAny } from '@total-typescript/shoehorn';

import {
formatMatrixResponse,
Expand Down Expand Up @@ -50,7 +51,7 @@ describe('formatMatrixResponse', () => {
] as [string | number, number][],
},
];
expect(formatMatrixResponse(rows as any)).toEqual([
expect(formatMatrixResponse(fromAny(rows))).toEqual([
{
metric: { __name__: 'http_requests_total', method: 'GET' },
values: [
Expand All @@ -72,7 +73,7 @@ describe('formatVectorResponse', () => {
{ tags: [['service', 'api']], timestamp: 1700000000, value: 42 },
{ tags: [], timestamp: '2023-11-14T22:13:20.000Z', value: 3 },
];
expect(formatVectorResponse(rows as any)).toEqual([
expect(formatVectorResponse(fromAny(rows))).toEqual([
{ metric: { service: 'api' }, value: [1700000000, '42'] },
{ metric: {}, value: [1700000000, '3'] },
]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => {

// Snapshot the raw tiles from the DB before patching
const beforePatch = await Dashboard.findById(dashboardId).lean();
const tilesBeforePatch = (beforePatch as any).tiles;
const tilesBeforePatch = beforePatch!.tiles;
const tileBBefore = tilesBeforePatch[1];
const tileCBefore = tilesBeforePatch[2];

Expand All @@ -470,7 +470,7 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => {

// Read raw DB tiles again; tiles B and C should be byte-identical
const afterPatch = await Dashboard.findById(dashboardId).lean();
const tilesAfterPatch = (afterPatch as any).tiles;
const tilesAfterPatch = afterPatch!.tiles;

expect(tilesAfterPatch).toHaveLength(3);
// Tile B (index 1) and Tile C (index 2) should be untouched
Expand Down Expand Up @@ -943,10 +943,10 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => {
const output = JSON.parse(getFirstText(patchResult));
expect(output.patchedTile.name).toBe('Static SQL');
const dashboard = await Dashboard.findById(created.id);
const persistedConfig = dashboard?.tiles?.[0]?.config as {
sqlTemplate?: string;
};
expect(persistedConfig?.sqlTemplate).toBe('SELECT 1 AS value LIMIT 1');
expect(dashboard?.tiles?.[0]?.config).toHaveProperty(
'sqlTemplate',
'SELECT 1 AS value LIMIT 1',
);

expect(Array.isArray(output.warnings)).toBe(true);
expect(output.warnings).toHaveLength(1);
Expand Down
13 changes: 7 additions & 6 deletions packages/api/src/mcp/__tests__/dashboards/validation.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { DASHBOARD_VARIABLE_NAME_MAX_LENGTH } from '@hyperdx/common-utils/dist/types';
import { fromAny } from '@total-typescript/shoehorn';
import mongoose from 'mongoose';

import {
Expand Down Expand Up @@ -64,7 +65,7 @@ function makeSqlTile(overrides: {
sourceId?: string;
displayType?: string;
}): ExternalDashboardTileWithId {
return {
return fromAny({
id: 'sql-tile',
x: 0,
y: 0,
Expand All @@ -78,7 +79,7 @@ function makeSqlTile(overrides: {
sqlTemplate: overrides.sqlTemplate,
...(overrides.sourceId ? { sourceId: overrides.sourceId } : {}),
},
} as ExternalDashboardTileWithId;
});
}

describe('tile-level where rejection (builder tiles)', () => {
Expand Down Expand Up @@ -251,7 +252,7 @@ describe('getRawSqlTilesMissingRequiredSource', () => {
});

it('ignores builder (non-SQL) tiles entirely', () => {
const builderTile = {
const builderTile: ExternalDashboardTileWithId = fromAny({
id: 'builder',
x: 0,
y: 0,
Expand All @@ -263,7 +264,7 @@ describe('getRawSqlTilesMissingRequiredSource', () => {
sourceId,
select: [{ aggFn: 'count', valueExpression: '', where: '' }],
},
} as unknown as ExternalDashboardTileWithId;
});
expect(getRawSqlTilesMissingRequiredSource([builderTile])).toEqual([]);
});

Expand Down Expand Up @@ -433,7 +434,7 @@ describe('getRawSqlTileMacroHints', () => {
});

it('ignores builder (non-SQL) tiles entirely', () => {
const builderTile = {
const builderTile: ExternalDashboardTileWithId = fromAny({
id: 'builder',
x: 0,
y: 0,
Expand All @@ -445,7 +446,7 @@ describe('getRawSqlTileMacroHints', () => {
sourceId,
select: [{ aggFn: 'count', valueExpression: '', where: '' }],
},
} as unknown as ExternalDashboardTileWithId;
});
expect(getRawSqlTileMacroWarnings([builderTile])).toEqual([]);
});

Expand Down
5 changes: 3 additions & 2 deletions packages/api/src/mcp/__tests__/dashboards/variables.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { SourceKind } from '@hyperdx/common-utils/dist/types';
import { fromAny } from '@total-typescript/shoehorn';
import mongoose from 'mongoose';

import {
Expand All @@ -17,15 +18,15 @@ const sourceId = new mongoose.Types.ObjectId().toString();
function filter(
overrides: Partial<ExternalDashboardFilterWithId> = {},
): ExternalDashboardFilterWithId {
return {
return fromAny({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 P2 — fromAny replaces a checked single as T cast, so fixture typos no longer fail to compile

The old {...} as ExternalDashboardFilterWithId still made TypeScript check that the object overlaps the type: a misspelled type: 'QUERY_EXPRES' or a wrong whereLanguage literal would not compile. fromAny accepts any shape at all. The same file's staticFilter already shows a fix that needs no cast: type overrides as Partial<Extract<ExternalDashboardFilterWithId, { type: 'QUERY_EXPRESSION' }>> and return the literal directly. The same downgrade from as T to fromAny happens in makeSqlTile (validation.test.ts:68) and makeRule (ColorRulesEditor.test.tsx:12), where the comment explaining why the cast was safe was also deleted.

Advisory. Fix if it is a small defect in code this PR changes; otherwise reply in the thread. Do not widen the PR or touch files it did not already change. How to respond

id: new mongoose.Types.ObjectId().toString(),
type: 'QUERY_EXPRESSION',
name: 'Service',
expression: 'ServiceName',
sourceId,
whereLanguage: 'sql',
...overrides,
} as ExternalDashboardFilterWithId;
});
}

const variableFilter = filter({
Expand Down
21 changes: 7 additions & 14 deletions packages/api/src/mcp/__tests__/deltasTool.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,23 +186,16 @@ describe('MCP Event Deltas Tool', () => {
expect(severity.baseline).toBeUndefined();
expect(severity.targetCount).toBeGreaterThan(0);
expect(severity.baselineCount).toBeGreaterThan(0);
const errorDelta = (
severity.topDeltas as Array<{
value: string;
targetPct: number;
baselinePct: number;
}>
).find(v => v.value === 'ERROR');
const topDeltas: Array<{
value: string;
targetPct: number;
baselinePct: number;
}> = severity.topDeltas;
const errorDelta = topDeltas.find(v => v.value === 'ERROR');
expect(errorDelta).toBeDefined();
// Target window planted ERROR, baseline window planted INFO.
expect(errorDelta!.targetPct).toBeGreaterThan(errorDelta!.baselinePct);
const infoDelta = (
severity.topDeltas as Array<{
value: string;
targetPct: number;
baselinePct: number;
}>
).find(v => v.value === 'INFO');
const infoDelta = topDeltas.find(v => v.value === 'INFO');
expect(infoDelta).toBeDefined();
expect(infoDelta!.baselinePct).toBeGreaterThan(infoDelta!.targetPct);
});
Expand Down
43 changes: 20 additions & 23 deletions packages/api/src/mcp/__tests__/describeSourceTimeout.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ jest.mock('@/utils/trimToolResponse', () => ({
}));

import { SourceKind } from '@hyperdx/common-utils/dist/types';
import { fromAny, fromPartial } from '@total-typescript/shoehorn';

import { getConnectionById } from '@/controllers/connection';
import { getPromqlLabelCatalog } from '@/controllers/promql';
Expand All @@ -36,7 +37,7 @@ import {
registerDescribeSource,
} from '@/mcp/tools/sources/describeSource';
import { sampleMetricNamesWithLookback } from '@/mcp/tools/sources/metricNames';
import type { ToolRegistrar, ToolResult } from '@/mcp/tools/types';
import type { ToolResult } from '@/mcp/tools/types';

const COLUMNS = [
{ name: 'Timestamp', type: 'DateTime64(9)' },
Expand Down Expand Up @@ -81,13 +82,15 @@ const rejectOnAbort = (signal: AbortSignal) =>
function getHandler() {
let handler: ((args: { sourceId: string }) => Promise<ToolResult>) | null =
null;
registerDescribeSource({
server: {},
context: { teamId: 'team-1', userId: 'user-1', promqlEnabled: true },
registerTool: (_name: string, _config: unknown, h: typeof handler) => {
handler = h;
},
} as unknown as ToolRegistrar);
registerDescribeSource(
fromAny({
server: {},
context: { teamId: 'team-1', userId: 'user-1', promqlEnabled: true },
registerTool: (_name: string, _config: unknown, h: typeof handler) => {
handler = h;
},
}),
);
return handler!;
}

Expand All @@ -102,16 +105,14 @@ const parse = (result: ToolResult) => JSON.parse(result.content[0].text);
describe('clickstack_describe_source deadline', () => {
beforeEach(() => {
jest.useFakeTimers();
jest
.mocked(getSource)
.mockResolvedValue(
traceSource as unknown as Awaited<ReturnType<typeof getSource>>,
);
jest.mocked(getConnectionById).mockResolvedValue({
host: 'http://localhost:8123',
username: 'default',
password: '',
} as unknown as Awaited<ReturnType<typeof getConnectionById>>);
jest.mocked(getSource).mockResolvedValue(fromAny(traceSource));
jest.mocked(getConnectionById).mockResolvedValue(
fromPartial({
host: 'http://localhost:8123',
username: 'default',
password: '',
}),
);
mockMetadata.getColumns.mockResolvedValue(COLUMNS);
mockMetadata.getMapKeys.mockResolvedValue(['http.method']);
mockMetadata.getAllKeyValues.mockResolvedValue([
Expand Down Expand Up @@ -297,11 +298,7 @@ describe('clickstack_describe_source deadline', () => {

describe('metric sources', () => {
beforeEach(() => {
jest
.mocked(getSource)
.mockResolvedValue(
metricSource as unknown as Awaited<ReturnType<typeof getSource>>,
);
jest.mocked(getSource).mockResolvedValue(fromAny(metricSource));
mockMetadata.getColumns.mockResolvedValue([
{ name: 'TimeUnix', type: 'DateTime64(9)' },
{ name: 'MetricName', type: 'LowCardinality(String)' },
Expand Down
2 changes: 1 addition & 1 deletion packages/api/src/mcp/__tests__/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -688,7 +688,7 @@ describe('isServerError', () => {
const a = new Error('a');
const b = new Error('b', { cause: a });
// Create circular reference: a.cause -> b -> a -> ...
(a as any).cause = b;
a.cause = b;
// Should terminate and return false (no server error codes)
expect(isServerError(a)).toBe(false);
});
Expand Down
8 changes: 4 additions & 4 deletions packages/api/src/mcp/__tests__/sources.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -962,10 +962,10 @@ describe('MCP Source Tools', () => {
expect(second.isError).toBeFalsy();
const secondOutput = JSON.parse(getFirstText(second));
// The second page must not repeat the first page's last name.
const firstNames = new Set(
(firstOutput.metrics as { name: string }[]).map(m => m.name),
);
for (const entry of secondOutput.metrics as { name: string }[]) {
const firstMetrics: { name: string }[] = firstOutput.metrics;
const secondMetrics: { name: string }[] = secondOutput.metrics;
const firstNames = new Set(firstMetrics.map(m => m.name));
for (const entry of secondMetrics) {
expect(firstNames.has(entry.name)).toBe(false);
}
});
Expand Down
9 changes: 5 additions & 4 deletions packages/api/src/middleware/__tests__/error.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { Request, Response } from 'express';
import { fromAny, fromPartial } from '@total-typescript/shoehorn';
import type { Response } from 'express';

// --- mocks (hoisted; names must be prefixed with `mock`) ---
const mockCounterAdd = jest.fn();
Expand Down Expand Up @@ -27,12 +28,12 @@ import { appErrorHandler } from '@/middleware/error';
import { Api404Error } from '@/utils/errors';

const invoke = (err: unknown): Response => {
const res = {
const res: Response = fromPartial({
headersSent: false,
status: jest.fn().mockReturnThis(),
json: jest.fn(),
} as unknown as Response;
appErrorHandler(err as any, {} as Request, res, jest.fn());
});
appErrorHandler(fromAny(err), fromPartial({}), res, jest.fn());
return res;
};

Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/routers/api/__tests__/alerts.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1411,7 +1411,7 @@ describe('alerts router', () => {
});

describe('GET /alerts/:id/history', () => {
const createTileAlert = async () => {
const createTileAlert = async (): Promise<string> => {
const dashboard = await agent
.post('/dashboards')
.send(MOCK_DASHBOARD)
Expand All @@ -1426,7 +1426,7 @@ describe('alerts router', () => {
}),
)
.expect(200);
return alert.body.data._id as string;
return alert.body.data._id;
};

it('returns firing and recovery transitions within the range', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
SourceKind,
TSource,
} from '@hyperdx/common-utils/dist/types';
import { fromAny } from '@total-typescript/shoehorn';
import { omit } from 'lodash';
import mongoose, { Types } from 'mongoose';

Expand Down Expand Up @@ -100,7 +101,7 @@ describe('dashboard router', () => {
const tileWithLegacyColor = makeTile();
tileWithLegacyColor.config = {
...tileWithLegacyColor.config,
color: 'chart-1' as any,
color: fromAny('chart-1'),
};

const created = await agent
Expand Down Expand Up @@ -151,7 +152,10 @@ describe('dashboard router', () => {
// PATCH, so a follow-up no-op PATCH would surface a regression.
it('returns hue-named tokens on GET (list) for a Mongo-seeded legacy chart-N tile', async () => {
const tileWithLegacy = makeTile();
(tileWithLegacy.config as any).color = 'chart-1';
tileWithLegacy.config = {
...tileWithLegacy.config,
color: fromAny('chart-1'),
};
const seeded = await Dashboard.create({
name: 'Pre-rename Dashboard',
team: team._id,
Expand Down
Loading
Loading