From 236d7679e436dfc6519cdbc933cf91d09b7dc237 Mon Sep 17 00:00:00 2001 From: reginaldalfret Date: Mon, 19 Oct 2026 19:08:25 +0530 Subject: [PATCH] fix(evaluation): validate JSON response against JSON Schema in FormatScorer FormatScorer._validateJsonSchema previously only checked if text parsed as JSON, scoring any valid JSON as 1.0 (passed) regardless of whether it conformed to the schema. Use @cfworker/json-schema Validator to validate the parsed JSON against the provided schema and return pass/fail accordingly. Resolves the schema draft version from the schema's $schema declaration (supporting drafts 4, 7, 2019-09, 2020-12 and enforcing $ref sibling constraints), rejecting unsupported drafts explicitly. Closes #1955 Signed-off-by: reginaldalfret --- .../evaluation/scorers/rule/formatScorer.ts | 96 ++++++++++- test/continuous-test-suite-bugfixes.ts | 155 ++++++++++++++++++ 2 files changed, 245 insertions(+), 6 deletions(-) diff --git a/src/lib/evaluation/scorers/rule/formatScorer.ts b/src/lib/evaluation/scorers/rule/formatScorer.ts index 91e7855067..6cb6d844d4 100644 --- a/src/lib/evaluation/scorers/rule/formatScorer.ts +++ b/src/lib/evaluation/scorers/rule/formatScorer.ts @@ -12,6 +12,7 @@ import type { ScorerMetadata, ScorerRule, } from "../../../types/index.js"; +import { Validator, type SchemaDraft } from "@cfworker/json-schema"; import { logger } from "../../../utils/logger.js"; import { BaseRuleScorer, @@ -498,22 +499,105 @@ export class FormatScorer extends BaseRuleScorer { return { passed: score >= 0.8, score }; } + /** + * Resolves the JSON Schema draft version from the schema's `$schema` declaration, + * or defaults to draft '2019-09' when omitted. + * + * @param schema - The JSON Schema object to inspect + * @returns The resolved SchemaDraft or an error message if unsupported + */ + private _resolveSchemaDraft(schema: object): { + draft?: SchemaDraft; + error?: string; + } { + if (!("$schema" in schema)) { + // Documented library default is 2019-09 when $schema is omitted + return { draft: "2019-09" }; + } + + const declared = (schema as { $schema?: unknown }).$schema; + // A present-but-non-string $schema (7, null, ...) is malformed, not absent. + if (typeof declared !== "string") { + return { + error: `Unsupported or invalid JSON Schema draft: ${JSON.stringify(declared)}`, + }; + } + + const raw = declared.trim().toLowerCase(); + + // The unversioned meta-schema URL names no draft; use the default. + if (/^https?:\/\/json-schema\.org\/schema#?$/.test(raw)) { + return { draft: "2019-09" }; + } + // The library has no draft-06; draft-07 is a near-superset, so validate + // draft-06 schemas as draft-07 rather than rejecting them. + if (/(?:^|\/|#)draft-0?6(?:[/#]|$)/.test(raw) || raw === "6") { + return { draft: "7" }; + } + // Match draft-04 / 4 + if (/(?:^|\/|#)draft-0?4(?:[/#]|$)/.test(raw) || raw === "4") { + return { draft: "4" }; + } + // Match draft-07 / 7 + if (/(?:^|\/|#)draft-0?7(?:[/#]|$)/.test(raw) || raw === "7") { + return { draft: "7" }; + } + // Match draft-2019-09 / 2019-09 + if ( + /(?:^|\/|#)(?:draft[/-])?2019-09(?:[/#]|$)/.test(raw) || + raw === "2019-09" + ) { + return { draft: "2019-09" }; + } + // Match draft-2020-12 / 2020-12 + if ( + /(?:^|\/|#)(?:draft[/-])?2020-12(?:[/#]|$)/.test(raw) || + raw === "2020-12" + ) { + return { draft: "2020-12" }; + } + + // Fail closed: a genuinely unknown draft (e.g. draft-03) cannot be + // validated faithfully, and passing it unchecked would reintroduce the + // "any parseable JSON passes" bug this scorer exists to prevent. + return { + error: `Unsupported or invalid JSON Schema draft: "${declared}"`, + }; + } + /** * Validate JSON against schema (basic validation) */ private _validateJsonSchema( text: string, - _schema: object, + schema: object, ): { passed: boolean; score: number } { - // First check if it's valid JSON + let parsed: unknown; try { - JSON.parse(text); - // TODO(#1955): Implement full JSON Schema validation - // For now, just check it's valid JSON - return { passed: true, score: 1.0 }; + parsed = JSON.parse(text); } catch { return { passed: false, score: 0.0 }; } + + const { draft, error: draftError } = this._resolveSchemaDraft(schema); + if (draftError || !draft) { + logger.warn( + `[FormatScorer] ${draftError ?? "Unsupported JSON Schema draft"}`, + ); + return { passed: false, score: 0.0 }; + } + + try { + const validator = new Validator(schema as never, draft, false); + const result = validator.validate(parsed); + return { + passed: result.valid, + score: result.valid ? 1.0 : 0.0, + }; + } catch (err) { + logger.warn("[FormatScorer] JSON Schema validation error:", err); + return { passed: false, score: 0.0 }; + } } /** diff --git a/test/continuous-test-suite-bugfixes.ts b/test/continuous-test-suite-bugfixes.ts index 15616c1c44..0bc064df10 100644 --- a/test/continuous-test-suite-bugfixes.ts +++ b/test/continuous-test-suite-bugfixes.ts @@ -61,6 +61,7 @@ import { buildMultimodalMessagesArray, mergeMediaFileAliases, } from "../src/lib/utils/messageBuilder.js"; +import { createFormatScorer } from "../src/lib/evaluation/scorers/rule/formatScorer.js"; import { buildMultimodalOptions } from "../src/lib/utils/multimodalOptionsBuilder.js"; import { CSVProcessor, @@ -12468,6 +12469,160 @@ exit 127 ); }, }, + { + name: "formatScorer: validates JSON against schema rather than accepting any valid JSON (#1955)", + category: "evaluation", + fn: async () => { + const schema = { + type: "object", + required: ["name", "age"], + properties: { + name: { type: "string" }, + age: { type: "number" }, + }, + }; + const scorer = await createFormatScorer({ + allowedFormats: ["json"], + jsonSchema: schema, + }); + + const validResult = await scorer.score({ + query: "test", + response: JSON.stringify({ name: "Alice", age: 30 }), + }); + const nonConformingResult = await scorer.score({ + query: "test", + response: JSON.stringify({ name: "Alice" }), + }); + const malformedJsonResult = await scorer.score({ + query: "test", + response: "not json at all", + }); + + return ( + validResult.passed === true && + validResult.score === 10 && + nonConformingResult.passed === false && + nonConformingResult.score < 10 && + malformedJsonResult.passed === false && + malformedJsonResult.score === 0 + ); + }, + }, + { + name: "formatScorer: enforces $ref sibling constraints under draft 2020-12 and rejects unsupported drafts (#1955)", + category: "evaluation", + fn: async () => { + // Draft 2020-12 schema with $ref and sibling 'required' constraint + const schema2020 = { + $schema: "https://json-schema.org/draft/2020-12/schema", + $defs: { + person: { + type: "object", + properties: { + name: { type: "string" }, + }, + }, + }, + $ref: "#/$defs/person", + required: ["age"], + properties: { + age: { type: "number" }, + }, + }; + + const scorer2020 = await createFormatScorer({ + allowedFormats: ["json"], + jsonSchema: schema2020, + }); + + // Satisfies $ref but missing sibling required field 'age' -> MUST fail + const missingSiblingResult = await scorer2020.score({ + query: "test", + response: JSON.stringify({ name: "Alice" }), + }); + + // Satisfies both $ref and sibling required field 'age' -> MUST pass + const validSiblingResult = await scorer2020.score({ + query: "test", + response: JSON.stringify({ name: "Alice", age: 30 }), + }); + + // Unsupported schema draft (draft-03) -> MUST be explicitly rejected + const unsupportedDraftSchema = { + $schema: "http://json-schema.org/draft-03/schema#", + type: "object", + properties: { + name: { type: "string" }, + }, + }; + + const unsupportedScorer = await createFormatScorer({ + allowedFormats: ["json"], + jsonSchema: unsupportedDraftSchema, + }); + + const unsupportedResult = await unsupportedScorer.score({ + query: "test", + response: JSON.stringify({ name: "Alice" }), + }); + + return ( + missingSiblingResult.passed === false && + missingSiblingResult.score < 10 && + validSiblingResult.passed === true && + validSiblingResult.score === 10 && + unsupportedResult.passed === false && + unsupportedResult.score < 10 + ); + }, + }, + { + name: "formatScorer: maps draft-06 and unversioned $schema, rejects non-string $schema (#1955)", + category: "evaluation", + fn: async () => { + const body = { + type: "object", + required: ["name"], + properties: { name: { type: "string" } }, + }; + const run = async ( + schemaDecl: unknown, + response: unknown, + ): Promise<{ passed: boolean; score: number }> => { + const scorer = await createFormatScorer({ + allowedFormats: ["json"], + jsonSchema: { $schema: schemaDecl, ...body }, + }); + return scorer.score({ + query: "test", + response: JSON.stringify(response), + }); + }; + const good = { name: "Alice" }; + const bad = { age: 1 }; + const draft06 = "http://json-schema.org/draft-06/schema#"; + const generic = "http://json-schema.org/schema#"; + + const d6Ok = await run(draft06, good); + const d6Bad = await run(draft06, bad); + const gOk = await run(generic, good); + const gBad = await run(generic, bad); + const numDecl = await run(7, good); + const nullDecl = await run(null, good); + + return ( + d6Ok.passed === true && + d6Ok.score === 10 && + d6Bad.passed === false && + gOk.passed === true && + gOk.score === 10 && + gBad.passed === false && + numDecl.passed === false && + nullDecl.passed === false + ); + }, + }, ]; function sseBody(events: unknown[]): ReadableStream {