From 5b51548d402d316164161a17deb06b2b7858cdab Mon Sep 17 00:00:00 2001 From: Osamaali313 Date: Wed, 8 Jul 2026 00:29:05 +0300 Subject: [PATCH] fix(internals): compare both matrices' column counts in cosineSimilarityMatrix The column-count guard compared `matrixA[0]` to itself, so it could never fire and matrices with differing column counts bypassed validation (mismatched input returned `[[]]` instead of raising). Compare `matrixB[0]` as the error message ("Matrices must have the same number of columns.") intends. Signed-off-by: Osamaali313 --- typescript/src/internals/helpers/math.test.ts | 24 +++++++++++++++++++ typescript/src/internals/helpers/math.ts | 2 +- 2 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 typescript/src/internals/helpers/math.test.ts diff --git a/typescript/src/internals/helpers/math.test.ts b/typescript/src/internals/helpers/math.test.ts new file mode 100644 index 000000000..20d546ed0 --- /dev/null +++ b/typescript/src/internals/helpers/math.test.ts @@ -0,0 +1,24 @@ +/** + * Copyright 2025 © BeeAI a Series of LF Projects, LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import { describe, expect, it } from "vitest"; + +import { cosineSimilarityMatrix } from "@/internals/helpers/math.js"; + +describe("cosineSimilarityMatrix", () => { + it("rejects matrices with differing column counts", () => { + expect(() => cosineSimilarityMatrix([[1, 2]], [[1, 2, 3]])).toThrowError( + "Matrices must have the same number of columns.", + ); + expect(() => cosineSimilarityMatrix([[1, 2]], [])).toThrowError( + "Matrices must have the same number of columns.", + ); + }); + + it("computes similarity for matching column counts", () => { + const result = cosineSimilarityMatrix([[1, 0]], [[1, 0]]); + expect(result[0][0]).toBeCloseTo(1); + }); +}); diff --git a/typescript/src/internals/helpers/math.ts b/typescript/src/internals/helpers/math.ts index 3c54ba5bf..936d979d9 100644 --- a/typescript/src/internals/helpers/math.ts +++ b/typescript/src/internals/helpers/math.ts @@ -21,7 +21,7 @@ export function cosineSimilarity(vecA: number[], vecB: number[]): number { } export function cosineSimilarityMatrix(matrixA: number[][], matrixB: number[][]): number[][] { - if ((matrixA[0]?.length ?? 0) !== (matrixA[0]?.length ?? 0)) { + if ((matrixA[0]?.length ?? 0) !== (matrixB[0]?.length ?? 0)) { throw new ValueError("Matrices must have the same number of columns."); }