feat(assessment): define corrective and training attempt contracts

This commit is contained in:
TakuyaYagam1 committed 2026-10-07 10:36:16 +03:00
1 parent fade4e76e4
commit 20c03288d6
71 files changed
+14786 -1743

No files matched your search

+60 -1
View File
@@ -133,6 +133,43 @@ def rewrite_schema_references(
name_mapping,
schema_paths,
)
elif key == "discriminator" and isinstance(item, dict):
discriminator: dict[Any, Any] = {}
for discriminator_key, discriminator_value in item.items():
if discriminator_key == "mapping" and isinstance(
discriminator_value, dict
):
mapping: dict[Any, Any] = {}
for tag, reference in discriminator_value.items():
if isinstance(reference, str):
mapping[tag] = rewrite_schema_reference(
reference,
source_path,
contract_root,
merged_path,
name_mapping,
schema_paths,
)
else:
mapping[tag] = rewrite_schema_references(
reference,
source_path,
contract_root,
merged_path,
name_mapping,
schema_paths,
)
discriminator[discriminator_key] = mapping
else:
discriminator[discriminator_key] = rewrite_schema_references(
discriminator_value,
source_path,
contract_root,
merged_path,
name_mapping,
schema_paths,
)
rewritten[key] = discriminator
else:
rewritten[key] = rewrite_schema_references(
item,
@@ -159,13 +196,35 @@ def rewrite_schema_references(
def collect_references(value: Any, location: str = "$") -> list[tuple[str, str]]:
"""Return every nested $ref and its YAML location."""
"""Return nested $ref and discriminator mapping targets with their locations."""
references: list[tuple[str, str]] = []
if isinstance(value, dict):
for key, item in value.items():
child_location = f"{location}.{key}"
if key == "$ref" and isinstance(item, str):
references.append((item, child_location))
elif key == "discriminator" and isinstance(item, dict):
for discriminator_key, discriminator_value in item.items():
if discriminator_key == "mapping" and isinstance(
discriminator_value, dict
):
for tag, target in discriminator_value.items():
target_location = (
f"{child_location}.mapping.{tag}"
)
if isinstance(target, str):
references.append((target, target_location))
else:
references.extend(
collect_references(target, target_location)
)
else:
references.extend(
collect_references(
discriminator_value,
f"{child_location}.{discriminator_key}",
)
)
else:
references.extend(collect_references(item, child_location))
elif isinstance(value, list):
+367
View File
@@ -0,0 +1,367 @@
"""Pin assessment mode, correction-chain, and read-side-effect contracts."""
from __future__ import annotations
import unittest
from pathlib import Path
from typing import Any
import yaml
API_DIR = Path(__file__).resolve().parents[1] / "api"
CORE_BUNDLE = API_DIR / "core" / "openapi.bundle.yml"
def load_bundle() -> dict[str, Any]:
with CORE_BUNDLE.open(encoding="utf-8") as stream:
document = yaml.safe_load(stream)
if not isinstance(document, dict):
raise AssertionError(f"{CORE_BUNDLE} is not an OpenAPI document")
return document
def resolve_schema(schema: dict[str, Any], schemas: dict[str, Any]) -> dict[str, Any]:
current = schema
visited: set[str] = set()
while "$ref" in current:
reference = current["$ref"]
if not reference.startswith("#/components/schemas/"):
raise AssertionError(f"unexpected bundled schema reference: {reference}")
name = reference.rsplit("/", 1)[1]
if name in visited:
raise AssertionError(f"cyclic schema reference: {name}")
visited.add(name)
current = schemas[name]
return current
def referenced_schema_name(schema: dict[str, Any]) -> str:
reference = schema.get("$ref", "")
if not reference.startswith("#/components/schemas/"):
raise AssertionError(f"expected a bundled schema reference, got {reference!r}")
return reference.rsplit("/", 1)[1]
def properties_across_all_of(
schema: dict[str, Any], schemas: dict[str, Any]
) -> dict[str, Any]:
resolved = resolve_schema(schema, schemas)
properties = dict(resolved.get("properties", {}))
for part in resolved.get("allOf", []):
properties.update(properties_across_all_of(part, schemas))
return properties
def union_enum_values(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]:
resolved = resolve_schema(schema, schemas)
values: set[str] = set()
for branch in resolved.get("oneOf", []):
branch_properties = properties_across_all_of(branch, schemas)
format_schema = branch_properties.get("format", {})
values.update(format_schema.get("enum", []))
return values
def required_across_all_of(schema: dict[str, Any], schemas: dict[str, Any]) -> set[str]:
resolved = resolve_schema(schema, schemas)
required = set(resolved.get("required", []))
for part in resolved.get("allOf", []):
required.update(required_across_all_of(part, schemas))
return required
def example_value(example: dict[str, Any], examples: dict[str, Any]) -> dict[str, Any]:
current = example
visited: set[str] = set()
while "$ref" in current:
reference = current["$ref"]
if not reference.startswith("#/components/examples/"):
raise AssertionError(f"unexpected bundled example reference: {reference}")
name = reference.rsplit("/", 1)[1]
if name in visited:
raise AssertionError(f"cyclic example reference: {name}")
visited.add(name)
current = examples[name]
value = current.get("value")
if not isinstance(value, dict):
raise AssertionError("assessment example must contain an object value")
return value
class AssessmentContractTest(unittest.TestCase):
def setUp(self) -> None:
self.document = load_bundle()
self.schemas = self.document["components"]["schemas"]
self.paths = self.document["paths"]
def test_create_has_disjoint_real_corrective_and_express_shapes(self) -> None:
self.assertEqual(
set(self.schemas["AssessmentMode"]["enum"]),
{"demo_basic", "demo_express", "adaptive"},
)
self.assertEqual(
set(self.schemas["AssessmentRealMode"]["enum"]),
{"demo_basic", "adaptive"},
)
create = resolve_schema(self.schemas["AssessmentAttemptCreate"], self.schemas)
self.assertEqual(len(create["oneOf"]), 3)
self.assertEqual(create["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(create["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
variants = {
referenced_schema_name(branch): resolve_schema(branch, self.schemas)
for branch in create["oneOf"]
}
self.assertIn("AssessmentQualifiedAttemptCreate", variants)
self.assertIn("AssessmentCorrectiveAttemptCreate", variants)
self.assertIn("AssessmentExpressAttemptCreate", variants)
real = variants["AssessmentQualifiedAttemptCreate"]
corrective = variants["AssessmentCorrectiveAttemptCreate"]
express = variants["AssessmentExpressAttemptCreate"]
self.assertFalse(real.get("additionalProperties", True))
self.assertNotIn("root_attempt_id", real.get("properties", {}))
self.assertEqual(real["properties"]["kind"]["enum"], ["root"])
self.assertFalse(corrective.get("additionalProperties", True))
self.assertIn("root_attempt_id", corrective["required"])
self.assertNotIn("chain_deadline", corrective.get("properties", {}))
self.assertEqual(corrective["properties"]["kind"]["enum"], ["corrective"])
self.assertEqual(express["required"], ["kind"])
self.assertEqual(express["properties"]["kind"]["enum"], ["demo_express"])
self.assertEqual(set(express["properties"]), {"kind"})
availability = resolve_schema(
self.schemas["AssessmentGradeAvailability"], self.schemas
)
mode = availability["properties"]["mode"]["oneOf"][0]
self.assertEqual(referenced_schema_name(mode), "AssessmentRealMode")
def test_attempt_and_result_one_of_keep_express_out_of_qualification(self) -> None:
attempt = resolve_schema(self.schemas["AssessmentAttempt"], self.schemas)
self.assertEqual(attempt["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(attempt["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
attempt_variants = {
referenced_schema_name(branch): branch for branch in attempt["oneOf"]
}
self.assertEqual(
set(attempt_variants),
{
"AssessmentQualifiedAttempt",
"AssessmentCorrectiveAttempt",
"AssessmentExpressAttempt",
},
)
corrective_properties = properties_across_all_of(
attempt_variants["AssessmentCorrectiveAttempt"], self.schemas
)
corrective_required = required_across_all_of(
attempt_variants["AssessmentCorrectiveAttempt"], self.schemas
)
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_properties))
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(corrective_required))
self.assertEqual(corrective_properties["chain_deadline"]["$ref"], "#/components/schemas/Timestamp")
qualified_attempt = resolve_schema(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
qualified_attempt_properties = properties_across_all_of(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
self.assertEqual(
set(qualified_attempt_properties["mode"]["enum"]),
{"demo_basic", "adaptive"},
)
self.assertEqual(qualified_attempt_properties["root_attempt_id"]["type"], "null")
self.assertEqual(qualified_attempt_properties["chain_deadline"]["type"], "null")
self.assertTrue(
{"root_attempt_id", "chain_deadline"}.issubset(
required_across_all_of(
attempt_variants["AssessmentQualifiedAttempt"], self.schemas
)
)
)
self.assertNotIn("not", qualified_attempt["allOf"][1])
express_attempt = properties_across_all_of(
attempt_variants["AssessmentExpressAttempt"], self.schemas
)
self.assertEqual(express_attempt["mode"]["enum"], ["demo_express"])
for name in ("specialization", "target_grade", "task_language", "root_attempt_id", "chain_deadline"):
self.assertEqual(express_attempt[name]["type"], "null", name)
result = resolve_schema(self.schemas["AssessmentResult"], self.schemas)
self.assertEqual(result["discriminator"]["propertyName"], "kind")
self.assertEqual(
set(result["discriminator"]["mapping"]),
{"root", "corrective", "demo_express"},
)
result_variants = {referenced_schema_name(branch): branch for branch in result["oneOf"]}
self.assertEqual(
set(result_variants),
{"AssessmentQualifiedResult", "AssessmentCorrectiveResult", "AssessmentExpressResult"},
)
qualified_properties = properties_across_all_of(
result_variants["AssessmentQualifiedResult"], self.schemas
)
self.assertEqual(
set(qualified_properties["mode"]["enum"]),
{"demo_basic", "adaptive"},
)
corrective_properties = properties_across_all_of(
result_variants["AssessmentCorrectiveResult"], self.schemas
)
for variant_name, variant, properties, expected_type in (
(
"qualified",
result_variants["AssessmentQualifiedResult"],
qualified_properties,
"null",
),
(
"corrective",
result_variants["AssessmentCorrectiveResult"],
corrective_properties,
"string",
),
):
required = required_across_all_of(variant, self.schemas)
self.assertTrue({"root_attempt_id", "chain_deadline"}.issubset(required), variant_name)
self.assertEqual(properties["root_attempt_id"]["type"], expected_type, variant_name)
if expected_type == "null":
self.assertEqual(properties["chain_deadline"]["type"], "null", variant_name)
else:
self.assertEqual(
properties["chain_deadline"]["$ref"],
"#/components/schemas/Timestamp",
variant_name,
)
express = resolve_schema(result_variants["AssessmentExpressResult"], self.schemas)
express_properties = express["properties"]
self.assertEqual(express_properties["mode"]["enum"], ["demo_express"])
for name in ("specialization", "target_grade", "confirmed_grade", "strength", "uncertainty", "basic_score"):
self.assertEqual(express_properties[name]["type"], "null", name)
self.assertEqual(express_properties["outcome"]["enum"], ["demonstration"])
self.assertEqual(express_properties["limitations"]["items"]["enum"], ["demonstration_only"])
self.assertIn("$ref", express_properties["practices"]["items"])
self.assertIn("$ref", express_properties["gaps"]["items"])
self.assertIn("$ref", express_properties["next_steps"]["items"])
self.assertFalse(express.get("additionalProperties", True))
self.assertNotIn("percentile", express_properties)
self.assertNotIn("score", express_properties)
self.assertIn("summary", express_properties)
def test_assessment_examples_match_discriminators_and_chain_pairs(self) -> None:
examples = self.document["components"]["examples"]
def operation_examples(path: str, method: str, location: tuple[str, ...]) -> list[dict[str, Any]]:
value: Any = self.paths[path][method]
for key in location:
value = value[key]
return [example_value(item, examples) for item in value.values()]
create_requests = operation_examples(
"/api/v1/me/assessment-attempts",
"post",
("requestBody", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in create_requests}, {"root", "corrective", "demo_express"})
requests_by_kind = {value["kind"]: value for value in create_requests}
self.assertNotIn("root_attempt_id", requests_by_kind["root"])
self.assertIn("root_attempt_id", requests_by_kind["corrective"])
self.assertNotIn("chain_deadline", requests_by_kind["corrective"])
self.assertEqual(set(requests_by_kind["demo_express"]), {"kind"})
created_attempts = operation_examples(
"/api/v1/me/assessment-attempts",
"post",
("responses", "201", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in created_attempts}, {"root", "corrective", "demo_express"})
for value in created_attempts:
if value["kind"] == "corrective":
self.assertIsNotNone(value["root_attempt_id"])
self.assertIsNotNone(value["chain_deadline"])
else:
self.assertIsNone(value["root_attempt_id"])
self.assertIsNone(value["chain_deadline"])
results = operation_examples(
"/api/v1/me/assessment-attempts/{attempt_id}/result",
"get",
("responses", "200", "content", "application/json", "examples"),
)
self.assertEqual({value["kind"] for value in results}, {"root", "corrective", "demo_express"})
for value in results:
if value["kind"] == "corrective":
self.assertIsNotNone(value["root_attempt_id"])
self.assertIsNotNone(value["chain_deadline"])
elif value["kind"] == "root":
self.assertIsNone(value["root_attempt_id"])
self.assertIsNone(value["chain_deadline"])
else:
self.assertNotIn("root_attempt_id", value)
self.assertNotIn("chain_deadline", value)
def test_session_start_is_explicit_versioned_and_idempotent(self) -> None:
operation = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/sessions"
]["post"]
body = operation["requestBody"]["content"]["application/json"]["schema"]
session_start = resolve_schema(body, self.schemas)
self.assertEqual(session_start["required"], ["expected_version"])
self.assertIn(
"#/components/parameters/IdempotencyKey",
[parameter.get("$ref") for parameter in operation["parameters"]],
)
self.assertIn("412", operation["responses"])
self.assertIn("sessionCsrf", operation["security"][0])
def test_get_attempt_and_result_are_read_only_projections(self) -> None:
attempt = self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]
result = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/result"
]["get"]
for operation in (attempt, result):
self.assertNotIn("requestBody", operation)
self.assertIn("read-only", operation["description"].lower())
self.assertNotIn("sessionCsrf", operation["security"][0])
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"])
self.assertNotIn("post", self.paths["/api/v1/me/assessment-attempts/{attempt_id}/result"])
def test_attempt_items_and_answers_keep_the_seven_public_formats(self) -> None:
expected = {
"choice",
"number",
"string",
"order",
"find_error",
"configuration",
"practice",
}
self.assertEqual(union_enum_values(self.schemas["ItemContent"], self.schemas), expected)
self.assertEqual(union_enum_values(self.schemas["AssessmentAnswer"], self.schemas), expected)
def test_candidate_schemas_do_not_name_secrets_or_employer_access(self) -> None:
forbidden = {"answer_key", "answer_keys", "seed", "hidden_seed", "hidden_checks"}
for name in ("AssessmentAttemptCommon", "AssessmentRealResultCommon", "AssessmentExpressResult"):
schema = self.schemas[name]
self.assertFalse(forbidden.intersection(schema.get("properties", {})), name)
attempt_description = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}"
]["get"]["description"].lower()
result_description = self.paths[
"/api/v1/me/assessment-attempts/{attempt_id}/result"
]["get"]["description"].lower()
self.assertIn("employer", attempt_description)
self.assertIn("employer", result_description)
self.assertIn("404", self.paths["/api/v1/me/assessment-attempts/{attempt_id}"]["get"]["responses"])
if __name__ == "__main__":
unittest.main()
+95
View File
@@ -118,6 +118,101 @@ class MergeSchemasTest(unittest.TestCase):
"#/Contact/properties/email",
)
def test_rewrites_only_schema_targets_in_discriminator_mappings(self) -> None:
self.write_yaml(
"components/schemas/common_schemas.yml",
{
"schemas": {
"entity.Contact": {"type": "object"},
"entity.Status": {"type": "string"},
}
},
)
profile_path = self.write_yaml(
"components/schemas/profile_schemas.yml",
{
"schemas": {
"response.Profile": {
"type": "object",
"discriminator": {
"propertyName": "kind",
"mapping": {
"profile": "#/schemas/response.Profile",
"status": "#/schemas/entity.Status",
"contact": "./common_schemas.yml#/schemas/entity.Contact",
"external": "https://schemas.example.test/external.yml#/schemas/External",
},
},
"mapping": {"example": "#/schemas/entity.Status"},
"example": {"mapping": {"example": "#/schemas/entity.Status"}},
}
}
},
)
source_schema = MERGE.load_yaml(profile_path)["schemas"]["response.Profile"]
references = MERGE.collect_references(source_schema)
self.assertIn(("#/schemas/response.Profile", "$.discriminator.mapping.profile"), references)
self.assertIn(
(
"./common_schemas.yml#/schemas/entity.Contact",
"$.discriminator.mapping.contact",
),
references,
)
self.assertNotIn(("#/schemas/entity.Status", "$.mapping.example"), references)
MERGE.merge_contract(self.contract_root)
profile = self.read_yaml("components/schemas.yml")["Profile"]
mapping = profile["discriminator"]["mapping"]
self.assertEqual(mapping["profile"], "#/Profile")
self.assertEqual(mapping["status"], "#/Status")
self.assertEqual(mapping["contact"], "#/Contact")
self.assertEqual(
mapping["external"],
"https://schemas.example.test/external.yml#/schemas/External",
)
self.assertEqual(profile["mapping"]["example"], "#/schemas/entity.Status")
self.assertEqual(
profile["example"]["mapping"]["example"], "#/schemas/entity.Status"
)
def test_stale_discriminator_mapping_route_refs_are_rejected(self) -> None:
self.write_yaml(
"components/schemas/health_schemas.yml",
{"schemas": {"response.Health": {"type": "object"}}},
)
self.write_yaml(
"routes/health.yml",
{
"get": {
"responses": {
"200": {
"content": {
"application/json": {
"schema": {
"oneOf": [],
"discriminator": {
"propertyName": "kind",
"mapping": {
"health": "../components/schemas.yml#/schemas/response.Health"
},
},
}
}
}
}
}
}
},
)
with self.assertRaisesRegex(MERGE.MergeError, "stale schema references") as error:
MERGE.merge_contract(self.contract_root)
self.assertIn("discriminator.mapping.health", str(error.exception))
self.assertFalse((self.contract_root / "components" / "schemas.yml").exists())
def test_duplicate_normalized_names_fail_without_overwriting_output(self) -> None:
self.write_yaml(
"components/schemas/auth_schemas.yml",