"""Fail-closed experiment validation with deterministic checks first.""" from __future__ import annotations import json import logging from copy import deepcopy from typing import Any from .client import cache_extra_body, get_client, model_name from .models import ExperimentRequest, ExperimentValidation, ValidationCheck LOGGER = logging.getLogger(__name__) MAX_VALIDATION_ATTEMPTS = 3 SYSTEM_PROMPT = """You are an independent experiment feasibility reviewer. You receive one structured hypothetical experiment and must decide whether it could realistically generate the requested measurements. You do not know what datasets are available and must not infer availability. Dataset availability is checked only after your review by a separate hidden matcher. Never require an accession, checksum, repository, bundled file, or proof that a named input is present, and never reject or request revision because availability is unknown. For archival or computational experiments, review whether the specified extraction and measurement would be reproducible if matching records exist. Return feasible when the design is sufficiently reproducible, internally consistent, measurable, controlled/replicated for its stated purpose, physically and scientifically plausible, and compatible with the stated resources, duration, safety, and ethics. Judge the requested measurements and stated purpose, not optional improvements to an ideal study. Do not require extra timepoints, covariates, normalization, controls, spare capacity, or broader replication unless their absence prevents the requested measurements from being generated or interpreted at all. Severity and status must agree. Use error only for an issue that blocks execution. Use warning for a real limitation that does not block execution, and info for observations. If every check is info or warning, return feasible. Return needs_revision only with at least one error for a missing, ambiguous, or repairable blocking detail. Return unrealistic when the proposed mechanism, method, timing, scale, precision, or resources cannot realistically produce the requested output. Return restricted for unsafe, unethical, or disallowed work. Report at most three blocking errors, ordered by importance. Give concise field-path checks. Do not rewrite the protocol and do not claim the experiment was performed.""" def _check( category: str, path: str, message: str, severity: str = "error", ) -> ValidationCheck: return ValidationCheck( category=category, severity=severity, path=path, message=message ) def deterministic_validation(request: ExperimentRequest) -> ExperimentValidation | None: """Return a revision result for semantic omissions not expressible in JSON Schema.""" checks: list[ValidationCheck] = [] entity_ids = {entity.id for entity in request.entities} measurement_ids = [measurement.id for measurement in request.measurements] if len(measurement_ids) != len(set(measurement_ids)): checks.append( _check("consistency", "measurements", "Measurement IDs must be unique.") ) for index, entity in enumerate(request.entities): if entity.kind != "other" and not entity.identifiers: checks.append( _check( "completeness", f"entities[{index}].identifiers", "Provide a stable taxonomy, strain, cell-line, CAS, grade, or model identifier.", ) ) for prop_index, prop in enumerate(entity.properties): if isinstance(prop.value, (int, float)) and not prop.unit: checks.append( _check( "completeness", f"entities[{index}].properties[{prop_index}].unit", "Numeric properties require an explicit unit or 'dimensionless'.", ) ) if request.design.design_type in {"controlled", "factorial", "dose_response"}: if not request.interventions: checks.append( _check( "completeness", "interventions", "This design type requires at least one explicit intervention.", ) ) control_ids = { group.id for group in request.design.groups if group.role == "control" } if not control_ids: checks.append( _check( "controls", "design.groups", "This design type requires a group with role 'control'.", ) ) for index, intervention in enumerate(request.interventions): if intervention.agent_entity_id and intervention.agent_entity_id not in entity_ids: checks.append( _check( "consistency", f"interventions[{index}].agent_entity_id", "The intervention agent must reference a declared entity.", ) ) for param_index, param in enumerate(intervention.parameters): if isinstance(param.value, (int, float)) and not param.unit: checks.append( _check( "completeness", f"interventions[{index}].parameters[{param_index}].unit", "Numeric intervention parameters require an explicit unit.", ) ) declared_fields = {field.name.lower() for field in request.data_product.fields} for index, measurement in enumerate(request.measurements): if measurement.property.lower() not in declared_fields and not any( measurement.property.lower() in field.description.lower() for field in request.data_product.fields ): checks.append( _check( "consistency", f"measurements[{index}].property", "The measured property must map to a declared data-product field.", ) ) if checks: return ExperimentValidation( status="needs_revision", summary="The experiment specification has repairable omissions or inconsistencies.", checks=checks, ) return None def _strict_schema(schema: dict[str, Any]) -> dict[str, Any]: result = deepcopy(schema) def visit(node: Any) -> None: if isinstance(node, dict): properties = node.get("properties") if isinstance(properties, dict): node["additionalProperties"] = False node["required"] = list(properties) for value in node.values(): visit(value) elif isinstance(node, list): for value in node: visit(value) visit(result) return result def _extract_json(text: str) -> dict[str, Any] | None: text = (text or "").strip() try: value = json.loads(text) except json.JSONDecodeError: start, end = text.find("{"), text.rfind("}") if start < 0 or end <= start: return None try: value = json.loads(text[start : end + 1]) except json.JSONDecodeError: return None return value if isinstance(value, dict) else None def normalize_validation(validation: ExperimentValidation) -> ExperimentValidation: """Keep review status consistent with the severities returned by the reviewer.""" if validation.status == "needs_revision" and not any( check.severity == "error" for check in validation.checks ): return validation.model_copy( update={ "status": "feasible", "summary": ( "The experiment is feasible. The reviewer noted non-blocking " "limitations to consider during interpretation." ), } ) if validation.status == "feasible" and any( check.severity == "error" for check in validation.checks ): return validation.model_copy(update={"status": "needs_revision"}) return validation def validate_experiment(request: ExperimentRequest) -> ExperimentValidation: deterministic = deterministic_validation(request) if deterministic is not None: return deterministic request_json = request.model_dump_json(exclude={"problem_id"}) for attempt in range(1, MAX_VALIDATION_ATTEMPTS + 1): try: response = get_client().chat.completions.create( model=model_name(), temperature=0, messages=[ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": request_json}, ], extra_body=cache_extra_body("feasibility", request_json), response_format={ "type": "json_schema", "json_schema": { "name": "experiment_validation", "strict": True, "schema": _strict_schema( ExperimentValidation.model_json_schema() ), }, }, ) content = response.choices[0].message.content or "" obj = _extract_json(content) if obj is not None: return normalize_validation(ExperimentValidation.model_validate(obj)) LOGGER.warning( "Independent feasibility validation returned invalid JSON " "(attempt %d/%d)", attempt, MAX_VALIDATION_ATTEMPTS, ) except Exception: # validation is an authorization boundary LOGGER.exception( "Independent feasibility validation failed (attempt %d/%d)", attempt, MAX_VALIDATION_ATTEMPTS, ) return ExperimentValidation( status="temporarily_unavailable", summary="Independent feasibility validation is temporarily unavailable.", checks=[ _check( "plausibility", "$", "Retry the same experiment later; the design was not rejected.", severity="warning", ) ], )