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
96 changes: 90 additions & 6 deletions src/lib/evaluation/scorers/rule/formatScorer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 };
}
}

/**
Expand Down
155 changes: 155 additions & 0 deletions test/continuous-test-suite-bugfixes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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<Uint8Array> {
Expand Down
Loading