Skip to content

armgit / laya

Public Imported from GitHub
0

Non-autoregressive System 1 decision engine. Typed choice, score and yes/no decisions over any text in a single forward pass, in 100+ languages, with a router that picks the right checkpoint per request.

fix(ts): type min_confidence maps with the bucket keys the runtime can produce

Bruce-Yii0529394717c7
diff --git a/laya-ts/package.json b/laya-ts/package.json
index b58537b6..c5e081ff 100644
--- a/laya-ts/package.json
+++ b/laya-ts/package.json
@@ -10,7 +10,8 @@
"scripts": {
"clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
"build": "npm run clean && tsc -p tsconfig.json && node -e \"require('node:fs').copyFileSync('../LICENSE', 'LICENSE')\"",
- "test": "vitest",
+ "test": "npm run test:types && vitest",
+ "test:types": "tsc --noEmit -p tests/tsconfig.types.json",
"test:package": "node --test tests/package-e2e.mjs",
"prepack": "npm run build"
},
diff --git a/laya-ts/src/common.ts b/laya-ts/src/common.ts
index 38f170ed..0bd44472 100644
--- a/laya-ts/src/common.ts
+++ b/laya-ts/src/common.ts
@@ -238,10 +238,28 @@ function pyRepr(v: unknown): string {
return String(v);
}
-export type MinConfidenceMap = Record<string, number>;
+/** The option types and option-count sizes `optionBucket`/`tempBucket` can produce. The bucket
+ * type and the runtime `BUCKET_KEY` check below are both derived from these, so what the type
+ * accepts cannot drift from the keys the runtime produces. */
+const BUCKET_TYPES = ["choice", "score", "noul"] as const;
+const BUCKET_SIZES = ["2", "3-5", "6-10", "11+"] as const;
+
+/** The option-count bucket for a question with `k` options. */
+function optionCountBucketSize(k: number): (typeof BUCKET_SIZES)[number] {
+ return k <= 2 ? BUCKET_SIZES[0] : k <= 5 ? BUCKET_SIZES[1] : k <= 10 ? BUCKET_SIZES[2] : BUCKET_SIZES[3];
+}
+
+/** One bucket key the runtime can produce, e.g. "choice:2" or "score:11+". */
+export type MinConfidenceBucket = `${(typeof BUCKET_TYPES)[number]}:${(typeof BUCKET_SIZES)[number]}`;
+/** A `MinConfidenceMap` key: a bucket the runtime can produce, or "default" for the rest. */
+export type MinConfidenceKey = MinConfidenceBucket | "default";
+
+export type MinConfidenceMap = { [K in MinConfidenceKey]?: number };
export type MinConfidence = number | MinConfidenceMap;
-const BUCKET_KEY = /^(choice|score|noul):(2|3-5|6-10|11\+)$/;
+const BUCKET_KEY = new RegExp(
+ `^(${BUCKET_TYPES.join("|")}):(${BUCKET_SIZES.map((size) => size.replace("+", "\\+")).join("|")})$`,
+);
/**
* Validate a per-bucket abstention-threshold map (#394).
@@ -253,7 +271,7 @@ export function checkMinConfidenceMap(m: unknown): MinConfidenceMap {
if (!m || typeof m !== "object" || Array.isArray(m) || Object.keys(m).length === 0) {
throw new Error(`a min_confidence map must be a non-empty dict of bucket -> float, got ${pyRepr(m)}`);
}
- const out: MinConfidenceMap = {};
+ const out: Record<string, number> = {};
for (const [key, val] of Object.entries(m as Record<string, unknown>)) {
if (key !== "default" && !BUCKET_KEY.test(key)) {
throw new Error(`min_confidence map keys must be strings like 'choice:3-5', got ${pyRepr(key)}`);
@@ -293,7 +311,7 @@ export function optionBucket(answer: Record<string, unknown>): string | null {
} else {
return null;
}
- const size = k <= 2 ? "2" : k <= 5 ? "3-5" : k <= 10 ? "6-10" : "11+";
+ const size = optionCountBucketSize(k);
return `${qt}:${size}`;
}
@@ -303,8 +321,9 @@ export function resolveMinConfidence(
defaultVal: number = 0.0,
): number {
const key = optionBucket(answer);
- if (key !== null && key in thresholds) {
- return thresholds[key];
+ if (key !== null) {
+ const threshold = (thresholds as Record<string, number | undefined>)[key];
+ if (threshold !== undefined) return threshold;
}
return thresholds.default ?? defaultVal;
}
@@ -352,8 +371,7 @@ export function clampTemperature(t: unknown): number {
return Math.min(TEMP_MAX, Math.max(TEMP_MIN, f));
}
export function tempBucket(qtype: number, k: number): string {
- const size = k <= 2 ? "2" : k <= 5 ? "3-5" : k <= 10 ? "6-10" : "11+";
- return `${["choice", "score", "noul"][qtype]}:${size}`;
+ return `${BUCKET_TYPES[qtype]}:${optionCountBucketSize(k)}`;
}
export interface BinningEntry {
diff --git a/laya-ts/src/index.ts b/laya-ts/src/index.ts
index 1f62f73b..a9dd789d 100644
--- a/laya-ts/src/index.ts
+++ b/laya-ts/src/index.ts
@@ -82,6 +82,8 @@ export type {
OptionStats,
MinConfidence,
MinConfidenceMap,
+ MinConfidenceBucket,
+ MinConfidenceKey,
BinningEntry,
BinningMap,
} from "./common.js";
diff --git a/laya-ts/tests/confidence-gating.test.ts b/laya-ts/tests/confidence-gating.test.ts
index 846f8d30..5f29e7e2 100644
--- a/laya-ts/tests/confidence-gating.test.ts
+++ b/laya-ts/tests/confidence-gating.test.ts
@@ -85,7 +85,7 @@ describe("checkMinConfidenceMap", () => {
});
it("rejects unknown bucket keys and typos", () => {
- for (const typo of ["choice:3_5", "Choice:2", "invalid", "score:1", "foo:2", "choice:12"]) {
+ for (const typo of ["choice:3_5", "choice:2-5", "Choice:2", "invalid", "score:1", "foo:2", "choice:12"]) {
expect(() => checkMinConfidenceMap({ [typo]: 0.5 })).toThrowError(
/min_confidence map keys must be strings like 'choice:3-5'/,
);
diff --git a/laya-ts/tests/tsconfig.types.json b/laya-ts/tests/tsconfig.types.json
new file mode 100644
index 00000000..274cf7ad
--- /dev/null
+++ b/laya-ts/tests/tsconfig.types.json
@@ -0,0 +1,8 @@
+{
+ "extends": "../tsconfig.json",
+ "compilerOptions": {
+ "noEmit": true,
+ "rootDir": ".."
+ },
+ "include": ["types/**/*.ts"]
+}
diff --git a/laya-ts/tests/types/min-confidence-bucket-key.types.ts b/laya-ts/tests/types/min-confidence-bucket-key.types.ts
new file mode 100644
index 00000000..2a2f8f2b
--- /dev/null
+++ b/laya-ts/tests/types/min-confidence-bucket-key.types.ts
@@ -0,0 +1,30 @@
+/**
+ * Compile-time regression guard for the `min_confidence` bucket-key vocabulary (#1002 TypeScript
+ * parity). `tsc -p tests/types/tsconfig.json` type-checks this file: a key the runtime cannot
+ * produce has to be rejected by the type, not only by `checkMinConfidenceMap` at run time.
+ */
+import type { MinConfidenceMap } from "../../src/common.js";
+
+// Every bucket `optionBucket` can produce, plus `default`, keeps type-checking.
+export const valid: MinConfidenceMap = {
+ "choice:2": 0.9,
+ "choice:3-5": 0.8,
+ "choice:6-10": 0.7,
+ "choice:11+": 0.6,
+ "score:3-5": 0.5,
+ "noul:2": 0.4,
+ default: 0.3,
+};
+
+// A map assembled at run time is still accepted: `Record<string, number>` stays assignable.
+export const dynamic: MinConfidenceMap = Object.fromEntries([["choice:2", 0.4]]);
+
+// An impossible size reads as a bucket but cannot be produced, so it is a type error.
+// @ts-expect-error "choice:2-5" is not a bucket the runtime can produce
+export const impossibleSize: MinConfidenceMap = { "choice:2-5": 0.9 };
+// @ts-expect-error "foo" is not an option type
+export const unknownType: MinConfidenceMap = { "foo:2": 0.9 };
+// @ts-expect-error "score:1" is not a bucket the runtime can produce
+export const impossibleScoreSize: MinConfidenceMap = { "score:1": 0.9 };
+// @ts-expect-error values are thresholds, not strings
+export const badValue: MinConfidenceMap = { "choice:2": "0.9" };