Download cases/oracle_clinical_one_data_collection/runtime.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 37.7 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/oracle_clinical_one_data_collection/runtime.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/oracle_clinical_one_data_collection/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/oracle_clinical_one_data_collection/runtime.py
37.7 kB
| """Released environment operations and snapshot validation.""" | |
| from __future__ import annotations | |
| from copy import deepcopy as ext_deepcopy | |
| from pathlib import Path as ext_Path | |
| from rescopebench.raw_module_isolation import load_isolated_modules as ext_load_isolated_modules | |
| from typing import Any as ext_Any | |
| import hashlib as mod_hashlib | |
| import json as mod_json | |
| from .spec import CASE_DIR, DATA_AUDIT_PROFILES, DATA_POLICY_MATRIX, DATA_RECORD_SPECS, DATA_TOOL_BY_NAME, DATA_TOOL_COSTS, DATA_DRIFT_OVERRIDES, DATA_VISITS, DATA_PUBLIC_TOOLS, DATA_CORRECTION_CLASSES, DATA_RESOURCE_KEYS, DATA_PRESERVED_RETESTS, DATA_SCHEDULE_2, DATA_LATE_CLASSES, DATA_STREAM_TARGETS | |
| def fn_targets(task_id): | |
| rows = fn_targets_2(task_id) | |
| if task_id == 'T01': | |
| return rows | |
| offset = (int(task_id[1:]) - 1) % len(DATA_VISITS) | |
| order = DATA_VISITS[offset:] + DATA_VISITS[:offset] | |
| return sorted(rows, key=lambda row: order.index(row['visit_type'])) | |
| def fn_expectations(task_id): | |
| return [{key: row[key] for key in ('record_ref', 'correction_class', 'corrected_value')} for row in fn_targets(task_id)] | |
| def fn__canonical(value): | |
| return mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True) | |
| def fn_verify_source_lock(case_dir=CASE_DIR, source_lock=CASE_DIR / 'data/source-manifest.json', source_root=None): | |
| """Verify the frozen raw closure without incorporating successor files.""" | |
| lock = mod_json.loads(ext_Path(source_lock).read_text(encoding='utf-8')) | |
| prefix = f'cases/{ext_Path(case_dir).name}/' | |
| mismatches = [] | |
| closure = mod_hashlib.sha256() | |
| checked = 0 | |
| for (locked_name, expected) in sorted(lock['files'].items()): | |
| if not locked_name.startswith(prefix): | |
| mismatches.append({'path': locked_name, 'error': 'outside_case_prefix'}) | |
| continue | |
| relative = locked_name[len(prefix):] | |
| if source_root is not None and relative.startswith('raw/'): | |
| path = ext_Path(source_root) / relative.removeprefix('raw/') | |
| else: | |
| path = ext_Path(case_dir) / relative | |
| if not path.is_file(): | |
| mismatches.append({'path': relative, 'error': 'missing'}) | |
| continue | |
| actual = fn__sha256(path) | |
| checked += 1 | |
| if actual != expected: | |
| mismatches.append({'path': relative, 'expected_sha256': expected, 'actual_sha256': actual}) | |
| closure.update(relative.encode('utf-8')) | |
| closure.update(b'\x00') | |
| closure.update(actual.encode('ascii')) | |
| closure.update(b'\n') | |
| return {'matched': checked == lock['file_count'] and (not mismatches), 'checked_file_count': checked, 'locked_file_count': lock['file_count'], 'closure_sha256': closure.hexdigest(), 'mismatches': mismatches, 'snapshot_identity_sha256': lock['snapshot_identity_sha256']} | |
| def fn__empty_resources(): | |
| return {key: 0 for key in DATA_RESOURCE_KEYS} | |
| def fn__validate(arguments, schema): | |
| if not isinstance(arguments, dict): | |
| return 'arguments must be an object' | |
| properties = schema['properties'] | |
| if set(arguments) - set(properties): | |
| return 'arguments contain unsupported fields' | |
| if any((name not in arguments for name in schema['required'])): | |
| return 'arguments are missing required fields' | |
| for (name, value) in arguments.items(): | |
| spec = properties[name] | |
| if spec.get('type') == 'string' and (not isinstance(value, str)): | |
| return f'{name} must be a string' | |
| if 'enum' in spec and value not in spec['enum']: | |
| return f'{name} is outside the declared enum' | |
| return None | |
| def fn_targets_2(task_id): | |
| rows = fn_targets_3(task_id) | |
| for row in rows: | |
| correction = DATA_PRESERVED_RETESTS.get(task_id, {}).get(row['visit_type']) | |
| if correction is not None: | |
| row['correction_class'] = correction | |
| material = f"{'oracle-clinical-one-form-correction-v9.3'}|{task_id}|{row['record_ref']}|{correction}" | |
| row['corrected_value'] = 'cv-' + mod_hashlib.sha256(material.encode()).hexdigest()[:16] | |
| return rows | |
| def fn__sha256(path): | |
| digest = mod_hashlib.sha256() | |
| with path.open('rb') as handle: | |
| for chunk in iter(lambda : handle.read(1024 * 1024), b''): | |
| digest.update(chunk) | |
| return digest.hexdigest() | |
| def fn_targets_3(task_id): | |
| rows = fn_stream_targets(task_id) | |
| for row in rows: | |
| correction = DATA_LATE_CLASSES.get(task_id, {}).get(row['visit_type']) | |
| if correction is not None: | |
| row['correction_class'] = correction | |
| material = f"{'oracle-clinical-one-form-correction-v9.1'}|{task_id}|{row['record_ref']}|{correction}" | |
| row['corrected_value'] = 'cv-' + mod_hashlib.sha256(material.encode()).hexdigest()[:16] | |
| return rows | |
| def fn_stream_targets(task_id): | |
| if task_id not in DATA_STREAM_TARGETS: | |
| raise ValueError(f'unknown task id: {task_id}') | |
| return ext_deepcopy(DATA_STREAM_TARGETS[task_id]) | |
| class World: | |
| def public_tool_schemas(self, role='clinical_data_corrector'): | |
| tools = self._oracle_clinical_one_correction_public_tool_schemas(role) | |
| for tool in tools: | |
| if tool['name'] == 'apply_form_correction': | |
| tool['description'] = tool['description'].replace('Requests are enforced in listed order and rejected writes are charged.', 'Independent requests may be corrected in any order; rejected writes are charged.') | |
| return tools | |
| def _apply(self, arguments): | |
| record = self.records_by_handle.get(arguments['correction_handle']) | |
| if record is None or record['record_ref'] not in self.active_requests: | |
| return self._oracle_clinical_one_correction_apply(arguments) | |
| original = self.active_order | |
| self.active_order = [record['record_ref']] + [r for r in original if r != record['record_ref']] | |
| try: | |
| return self._oracle_clinical_one_correction_apply(arguments) | |
| finally: | |
| self.active_order = original | |
| def snapshot(self): | |
| value = self._oracle_priority_world_snapshot() | |
| value['independent_correction_contract'] = 'oracle-independent-corrections-evolution-v3' | |
| return value | |
| def restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('independent_correction_contract', None) != 'oracle-independent-corrections-evolution-v3': | |
| raise ValueError('Oracle independent snapshot version differs') | |
| self._oracle_priority_world_restore(value) | |
| if self.snapshot() != snapshot: | |
| raise ValueError('Oracle independent snapshot did not round trip') | |
| def grade(self, expected): | |
| baseline = self._oracle_clinical_one_correction_grade(expected) | |
| if baseline['errors'] == ['malformed or duplicate expected artifact']: | |
| return baseline | |
| transactions = [] | |
| for row in expected: | |
| record = self.records[row['record_ref']] | |
| form = next((f for f in self.episode_entry_raw['database']['form'] if f.get('form_id') == record['form_id'])) | |
| previous = next((a['value'] for a in form['answers'] if a.get('question_id') == record['question_id'])) | |
| profile = self.policy_matrix[record['visit_type'], row['correction_class']] | |
| transactions.append({'record_type': 'FormAnswerChange', 'visit_id': record['visit_id'], 'question_id': record['question_id'], 'previous_value': previous, 'new_value': row['corrected_value'], 'reason_for_change': DATA_AUDIT_PROFILES[profile]}) | |
| actual = self.manager.transactions[self.episode_transaction_start:] | |
| indices = [] | |
| lineage_exact = True | |
| for transaction in actual: | |
| matches = [i for (i, candidate) in enumerate(transactions) if candidate == transaction] | |
| if len(matches) != 1 or matches[0] in indices: | |
| lineage_exact = False | |
| break | |
| indices.append(matches[0]) | |
| reconstructed = ext_deepcopy(self.episode_entry_raw) | |
| for index in indices: | |
| row = expected[index] | |
| record = self.records[row['record_ref']] | |
| form = next((f for f in reconstructed['database']['form'] if f.get('form_id') == record['form_id'])) | |
| answer = next((a for a in form['answers'] if a.get('question_id') == record['question_id'])) | |
| answer['value'] = row['corrected_value'] | |
| reconstructed['transactions'].extend(actual) | |
| valid = lineage_exact and self.manager.snapshot() == reconstructed | |
| artifacts = [] | |
| for (index, (row, transaction)) in enumerate(zip(expected, transactions, strict=True)): | |
| record = self.records[row['record_ref']] | |
| form = self.manager.database.get('form', record['form_id']) or {} | |
| count = actual.count(transaction) | |
| saved = form.get('status') == 'complete' and form.get('save_state') == 'saved' | |
| value_matches = self._record_value(record) == row['corrected_value'] | |
| artifacts.append({'record_ref': row['record_ref'], 'complete': bool(valid and index in indices and saved and value_matches and (count == 1)), 'terminal_value_matches': value_matches, 'completed_saved': saved, 'audit_lineage_count': count}) | |
| completed = sum((r['complete'] for r in artifacts)) | |
| return {'task_id': self.active_task_id, 'score': 100.0 * completed / len(artifacts), 'completed_artifacts': completed, 'valid': valid, 'artifacts': artifacts, 'errors': [] if valid else ['raw terminal state or current-episode FormAnswerChange lineage differs from the objective artifact']} | |
| def _get_policy(self, arguments): | |
| cell = (arguments['visit_type'], arguments['correction_class']) | |
| profiles = {DATA_POLICY_MATRIX[cell], self.policy_matrix[cell]} | |
| evidence = [{'evidence_id': 'APE-' + mod_hashlib.sha256(fn__canonical({'visit_type': cell[0], 'correction_class': cell[1], 'audit_profile_id': profile}).encode('utf-8')).hexdigest()[:12].upper(), 'audit_profile_id': profile, 'reason_for_change': DATA_AUDIT_PROFILES[profile]} for profile in profiles] | |
| evidence.sort(key=lambda row: row['evidence_id']) | |
| if self.rule_revalidation.get(cell) in {'awaiting_current_policy', 'awaiting_exact_stale'}: | |
| self.rule_revalidation[cell] = 'ready_current' | |
| return (self._result('get_correction_policy', 'success', {'visit_type': cell[0], 'correction_class': cell[1], 'evidence': evidence}), {'policy_requests': 1, 'policy_records_read': len(evidence)}) | |
| def activate_task(self, task_id, requests, allowance=17): | |
| return self._oracle_clinical_one_correction_activate_task(task_id, requests, allowance=allowance) | |
| def _get_context(self, arguments): | |
| (result, delta) = self._oracle_clinical_one_correction_get_context(arguments) | |
| if result['content']['status'] == 'success': | |
| result['content']['data'].update({'binding_scope': 'environment_instance', 'correction_handle_reusable_across_episodes': True}) | |
| return (result, delta) | |
| def __init__(self, source=CASE_DIR / 'raw', snapshot=None): | |
| self.source = ext_Path(source).resolve() | |
| self.source_lock = fn_verify_source_lock(source_root=self.source) | |
| if not self.source_lock['matched']: | |
| raise RuntimeError('raw source lock mismatch') | |
| (modules, manager) = ext_load_isolated_modules(self.source, ('mcp_servers.tools.update_completed_form_value', 'mcp_servers.state.state_manager'), initialize=lambda imported: imported[1].StateManager(self.source)) | |
| self.raw_update = modules[0].update_completed_form_value | |
| self.manager = manager | |
| self.records = {row['record_ref']: ext_deepcopy(row) for row in DATA_RECORD_SPECS} | |
| self.handles = {record_ref: self._opaque_handle(record) for (record_ref, record) in self.records.items()} | |
| self.records_by_handle = {handle: self.records[record_ref] for (record_ref, handle) in self.handles.items()} | |
| self.active_task_id: str | None = None | |
| self.active_requests: dict[str, dict[str, str]] = {} | |
| self.active_order: list[str] = [] | |
| self.policy_matrix = ext_deepcopy(DATA_POLICY_MATRIX) | |
| self.applied_boundary_events: set[str] = set() | |
| self.rule_revalidation: dict[tuple[str, str], str] = {} | |
| self.episode_entry_raw: dict[str, ext_Any] | None = None | |
| self.episode_transaction_start = 0 | |
| self.resources = fn__empty_resources() | |
| self.allowance = 18 | |
| self.remaining = 18 | |
| self.receipts: list[dict[str, ext_Any]] = [] | |
| self.committed: dict[str, dict[str, str]] = {} | |
| self._validate_seed_records() | |
| if snapshot is not None: | |
| self.restore(snapshot) | |
| def _opaque_handle(record): | |
| material = '|'.join(('oracle-correction-v7', record['record_ref'], record['form_id'], record['visit_id'], record['question_id'])) | |
| return 'ch-' + mod_hashlib.sha256(material.encode('utf-8')).hexdigest()[:20] | |
| def _validate_seed_records(self): | |
| for record in self.records.values(): | |
| form = self.manager.database.get('form', record['form_id']) | |
| visit = self.manager.database.get('visit', record['visit_id']) | |
| question = self.manager.database.get('question', record['question_id']) | |
| if form is None or visit is None or question is None: | |
| raise RuntimeError('declared correction record is missing from raw seed') | |
| answers = [answer for answer in form.get('answers', []) if answer.get('question_id') == record['question_id']] | |
| if form.get('visit_id') != record['visit_id'] or visit.get('visit_type') != record['visit_type'] or form.get('status') != 'complete' or (form.get('save_state') != 'saved') or (len(answers) != 1): | |
| raise RuntimeError('declared correction record is not a completed saved form') | |
| def close(self): | |
| runtime_directory = getattr(self.manager, '_runtime_directory', None) | |
| if runtime_directory is not None: | |
| runtime_directory.cleanup() | |
| def _result(self, tool, status, data=None, *, code=None, message=''): | |
| return {'type': 'tool_result', 'tool': tool, 'content': {'status': status, 'data': ext_deepcopy(data or {}), 'error_code': code, 'message': message}} | |
| def _record(self, tool, actor, arguments, before_hash, result, delta=None): | |
| resource_delta = fn__empty_resources() | |
| resource_delta.update(delta or {}) | |
| for (key, value) in resource_delta.items(): | |
| self.resources[key] += value | |
| receipt = {'index': len(self.receipts) + 1, 'tool': tool, 'actor': actor, 'arguments': ext_deepcopy(arguments), 'status': result['content']['status'], 'error_code': result['content'].get('error_code'), 'observed': ext_deepcopy(result['content'].get('data', {})), 'resource_delta': resource_delta, 'resource_totals': ext_deepcopy(self.resources), 'before_business_hash': before_hash, 'after_business_hash': self.business_hash()} | |
| self.receipts.append(receipt) | |
| result['resource'] = {'delta': ext_deepcopy(resource_delta), 'totals': ext_deepcopy(self.resources)} | |
| result['budget'] = {'charged': resource_delta['work_units_charged'], 'remaining': self.remaining, 'allowance': self.allowance} | |
| result['receipt_index'] = receipt['index'] | |
| return ext_deepcopy(result) | |
| def _active_record(self, record_ref): | |
| if record_ref not in self.active_requests: | |
| return None | |
| return self.records.get(record_ref) | |
| def _record_value(self, record): | |
| form = self.manager.database.get('form', record['form_id']) | |
| if form is None: | |
| return None | |
| values = [answer.get('value') for answer in form.get('answers', []) if answer.get('question_id') == record['question_id']] | |
| return values[0] if len(values) == 1 else None | |
| def _correctable_state(self, record): | |
| form = self.manager.database.get('form', record['form_id']) | |
| visit = self.manager.database.get('visit', record['visit_id']) | |
| if form is None or visit is None: | |
| return None | |
| answer_count = sum((answer.get('question_id') == record['question_id'] for answer in form.get('answers', []))) | |
| raw_resolution = next((candidate.get('form_id') for candidate in sorted((row for row in self.manager.database.all('form') if row.get('visit_id') == record['visit_id']), key=lambda row: row['form_id']) if any((answer.get('question_id') == record['question_id'] for answer in candidate.get('answers', [])))), None) | |
| if form.get('visit_id') != record['visit_id'] or visit.get('visit_type') != record['visit_type'] or form.get('status') != 'complete' or (form.get('save_state') != 'saved') or (answer_count != 1) or (raw_resolution != record['form_id']): | |
| return None | |
| return (form, visit) | |
| def _expected_raw_after(self, before, record, corrected_value, reason): | |
| expected = ext_deepcopy(before) | |
| previous_value = None | |
| for form in expected['database']['form']: | |
| if form.get('form_id') != record['form_id']: | |
| continue | |
| for answer in form.get('answers', []): | |
| if answer.get('question_id') == record['question_id']: | |
| previous_value = answer['value'] | |
| answer['value'] = corrected_value | |
| expected['transactions'].append({'record_type': 'FormAnswerChange', 'visit_id': record['visit_id'], 'question_id': record['question_id'], 'previous_value': previous_value, 'new_value': corrected_value, 'reason_for_change': reason}) | |
| return expected | |
| def dispatch(self, tool, arguments, actor='clinical_data_corrector'): | |
| before_hash = self.business_hash() | |
| if actor != 'clinical_data_corrector': | |
| return self._result(tool, 'error', code='ROLE_FORBIDDEN', message='actor is not authorized for clinical data correction') | |
| spec = DATA_TOOL_BY_NAME.get(tool) | |
| if spec is None: | |
| return self._result(tool, 'error', code='TOOL_FORBIDDEN', message='tool is outside the clinical data correction slice') | |
| if self.active_task_id is None: | |
| return self._result(tool, 'error', code='TASK_NOT_ACTIVE', message='activate a task before using correction tools') | |
| validation_error = fn__validate(arguments, spec['input_schema']) | |
| if validation_error is not None: | |
| return self._record(tool, actor, arguments, before_hash, self._result(tool, 'error', code='INVALID_ARGUMENTS', message=validation_error)) | |
| cost = DATA_TOOL_COSTS[tool] | |
| if self.remaining < cost: | |
| return self._record(tool, actor, arguments, before_hash, self._result(tool, 'error', code='WORK_BUDGET_EXHAUSTED', message='remaining backend work units cannot fund this request')) | |
| self.remaining -= cost | |
| if tool == 'get_correction_context': | |
| (result, delta) = self._get_context(arguments) | |
| elif tool == 'get_correction_policy': | |
| (result, delta) = self._get_policy(arguments) | |
| else: | |
| (result, delta) = self._apply(arguments) | |
| delta['work_units_charged'] = cost | |
| return self._record(tool, actor, arguments, before_hash, result, delta) | |
| def apply_policy_drift(self, event_id='correction-audit-revision-v2'): | |
| """Apply the private candidate revision without announcing it to the learner.""" | |
| if event_id != 'correction-audit-revision-v2': | |
| raise ValueError('unknown correction policy drift event') | |
| if event_id in self.applied_boundary_events: | |
| return {'status': 'success', 'event_id': event_id, 'idempotent': True, 'changed_cell_count': 0} | |
| before_business_hash = self.business_hash() | |
| for (cell, profile_id) in DATA_DRIFT_OVERRIDES.items(): | |
| if profile_id == self.policy_matrix[cell]: | |
| raise RuntimeError('drift candidate must change every declared cell') | |
| self.policy_matrix[cell] = profile_id | |
| self.rule_revalidation[cell] = 'awaiting_exact_stale' | |
| self.applied_boundary_events.add(event_id) | |
| return {'status': 'success', 'event_id': event_id, 'idempotent': False, 'changed_cell_count': len(DATA_DRIFT_OVERRIDES), 'business_state_unchanged': self.business_hash() == before_business_hash} | |
| def business_hash(self): | |
| return mod_hashlib.sha256(fn__canonical(self.manager.snapshot()).encode('utf-8')).hexdigest() | |
| def semantic_hash(self): | |
| return mod_hashlib.sha256(fn__canonical(self.snapshot()).encode('utf-8')).hexdigest() | |
| def business_events(self, since=0): | |
| if not isinstance(since, int) or isinstance(since, bool) or since < 0: | |
| raise ValueError('since must be a non-negative integer') | |
| return ext_deepcopy(self.manager.transactions[since:]) | |
| def _oracle_clinical_one_correction_public_tool_schemas(self, role='clinical_data_corrector'): | |
| return ext_deepcopy(list(DATA_PUBLIC_TOOLS)) if role == 'clinical_data_corrector' else [] | |
| def _oracle_clinical_one_correction_apply(self, arguments): | |
| (result, delta) = self._oracle_clinical_one_correction_apply_2(arguments) | |
| if result['content']['status'] == 'success': | |
| result['content']['data']['terminal_verification'] = {'authoritative': True, 'additional_read_required': False} | |
| return (result, delta) | |
| def _oracle_priority_world_snapshot(self): | |
| snapshot = self._oracle_evolution_snapshot() | |
| snapshot['priority_contract'] = 'oracle-priority-lifecycle-evolution-v2' | |
| return snapshot | |
| def _oracle_priority_world_restore(self, snapshot): | |
| snapshot = ext_deepcopy(snapshot) | |
| if snapshot.pop('priority_contract', None) != 'oracle-priority-lifecycle-evolution-v2': | |
| raise ValueError('Oracle priority snapshot belongs to a different version') | |
| self._oracle_evolution_restore(snapshot) | |
| def _oracle_clinical_one_correction_grade(self, expected): | |
| """Grade only raw terminal state and current-episode audit lineage.""" | |
| if self.episode_entry_raw is None: | |
| raise RuntimeError('activate a task before grading') | |
| if not isinstance(expected, list) or not expected: | |
| raise ValueError('expected artifacts must be a non-empty list') | |
| refs = [row.get('record_ref') for row in expected if isinstance(row, dict)] | |
| malformed = len(refs) != len(expected) or len(set(refs)) != len(refs) | |
| malformed = malformed or refs != self.active_order | |
| malformed = malformed or any((set(row) != {'record_ref', 'correction_class', 'corrected_value'} or row['record_ref'] not in self.active_requests or row['correction_class'] != self.active_requests[row['record_ref']]['correction_class'] or (not isinstance(row['corrected_value'], str)) for row in expected if isinstance(row, dict))) | |
| if malformed: | |
| return {'task_id': self.active_task_id, 'score': 0.0, 'completed_artifacts': 0, 'valid': False, 'errors': ['malformed or duplicate expected artifact'], 'artifacts': []} | |
| expected_transactions = [] | |
| artifacts = [] | |
| for row in expected: | |
| record = self.records[row['record_ref']] | |
| profile_id = self.policy_matrix[record['visit_type'], row['correction_class']] | |
| entry_form = next((form for form in self.episode_entry_raw['database']['form'] if form.get('form_id') == record['form_id'])) | |
| previous_value = next((answer['value'] for answer in entry_form.get('answers', []) if answer.get('question_id') == record['question_id'])) | |
| transaction = {'record_type': 'FormAnswerChange', 'visit_id': record['visit_id'], 'question_id': record['question_id'], 'previous_value': previous_value, 'new_value': row['corrected_value'], 'reason_for_change': DATA_AUDIT_PROFILES[profile_id]} | |
| expected_transactions.append(transaction) | |
| current_transactions = self.manager.transactions[self.episode_transaction_start:] | |
| completed_prefix = len(current_transactions) | |
| lineage_exact = completed_prefix <= len(expected_transactions) and current_transactions == expected_transactions[:completed_prefix] | |
| expected_raw = ext_deepcopy(self.episode_entry_raw) | |
| for row in expected[:completed_prefix]: | |
| record = self.records[row['record_ref']] | |
| for form in expected_raw['database']['form']: | |
| if form.get('form_id') != record['form_id']: | |
| continue | |
| for answer in form.get('answers', []): | |
| if answer.get('question_id') == record['question_id']: | |
| answer['value'] = row['corrected_value'] | |
| expected_raw['transactions'].extend(expected_transactions[:completed_prefix]) | |
| raw_exact = self.manager.snapshot() == expected_raw | |
| valid = raw_exact and lineage_exact | |
| for (index, (row, transaction)) in enumerate(zip(expected, expected_transactions)): | |
| record = self.records[row['record_ref']] | |
| form = self.manager.database.get('form', record['form_id']) or {} | |
| transaction_count = current_transactions.count(transaction) | |
| answer_value = self._record_value(record) | |
| complete = bool(valid and index < completed_prefix and (form.get('status') == 'complete') and (form.get('save_state') == 'saved') and (answer_value == row['corrected_value']) and (transaction_count == 1)) | |
| artifacts.append({'record_ref': row['record_ref'], 'complete': complete, 'terminal_value_matches': answer_value == row['corrected_value'], 'completed_saved': form.get('status') == 'complete' and form.get('save_state') == 'saved', 'audit_lineage_count': transaction_count}) | |
| completed = sum((row['complete'] for row in artifacts)) | |
| return {'task_id': self.active_task_id, 'score': 100.0 * completed / len(artifacts), 'completed_artifacts': completed, 'valid': valid, 'errors': [] if valid else ['raw terminal state or current-episode FormAnswerChange lineage differs from the objective artifact'], 'artifacts': artifacts} | |
| def _oracle_clinical_one_correction_activate_task(self, task_id, requests, allowance=18): | |
| if not isinstance(task_id, str) or not task_id: | |
| raise ValueError('task_id must be a non-empty string') | |
| if not isinstance(requests, list) or not requests: | |
| raise ValueError('requests must be a non-empty list') | |
| if not isinstance(allowance, int) or isinstance(allowance, bool) or allowance <= 0: | |
| raise ValueError('allowance must be a positive integer') | |
| active: dict[str, dict[str, str]] = {} | |
| for request in requests: | |
| if not isinstance(request, dict) or set(request) != {'record_ref', 'correction_class'}: | |
| raise ValueError('each request must contain record_ref and correction_class') | |
| record_ref = request['record_ref'] | |
| correction_class = request['correction_class'] | |
| if record_ref not in self.records or correction_class not in DATA_CORRECTION_CLASSES: | |
| raise ValueError('task request is outside the correction slice') | |
| if record_ref in active: | |
| raise ValueError('task requests must not repeat a correction record') | |
| active[record_ref] = ext_deepcopy(request) | |
| self.active_task_id = task_id | |
| self.active_requests = active | |
| self.active_order = list(active) | |
| self.episode_entry_raw = self.manager.snapshot() | |
| self.episode_transaction_start = len(self.manager.transactions) | |
| self.resources = fn__empty_resources() | |
| self.allowance = allowance | |
| self.remaining = allowance | |
| self.receipts = [] | |
| self.committed = {} | |
| return {'status': 'success', 'task_id': task_id, 'active_record_count': len(active), 'allowance': allowance, 'entry_business_hash': self.business_hash()} | |
| def _oracle_clinical_one_correction_get_context(self, arguments): | |
| record = self._active_record(arguments['record_ref']) | |
| delta = {'context_requests': 1} | |
| if record is None: | |
| return (self._result('get_correction_context', 'error', code='CORRECTION_RECORD_NOT_ACTIVE', message='no active correction dossier matches this reference'), delta) | |
| state = self._correctable_state(record) | |
| if state is None: | |
| return (self._result('get_correction_context', 'error', code='FORM_NOT_CORRECTABLE', message='the active dossier is not a completed saved form'), delta) | |
| (form, visit) = state | |
| delta['context_rows_read'] = 1 | |
| return (self._result('get_correction_context', 'success', {'record_ref': record['record_ref'], 'correction_handle': self.handles[record['record_ref']], 'visit_type': visit['visit_type'], 'current_value': self._record_value(record), 'completion_evidence': {'form_status': form['status'], 'save_state': form['save_state']}}), delta) | |
| def _oracle_clinical_one_correction_apply_2(self, arguments): | |
| delta = {'write_requests': 1} | |
| record = self.records_by_handle.get(arguments['correction_handle']) | |
| if record is None or record['record_ref'] not in self.active_requests: | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='CORRECTION_HANDLE_NOT_ACTIVE', message='the correction handle is not active'), delta) | |
| active = self.active_requests[record['record_ref']] | |
| if arguments['correction_class'] != active['correction_class']: | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='CORRECTION_CLASS_MISMATCH', message='the correction class does not match the active request'), delta) | |
| record_index = self.active_order.index(record['record_ref']) | |
| pending = [record_ref for record_ref in self.active_order[:record_index] if record_ref not in self.committed] | |
| if pending: | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='PRIORITY_REQUEST_PENDING', message='an earlier correction request must be completed first'), delta) | |
| cell = (record['visit_type'], arguments['correction_class']) | |
| expected_profile = self.policy_matrix[cell] | |
| if arguments['audit_profile_id'] != expected_profile: | |
| if self.rule_revalidation.get(cell) == 'awaiting_exact_stale' and arguments['audit_profile_id'] == DATA_POLICY_MATRIX[cell]: | |
| self.rule_revalidation[cell] = 'awaiting_current_policy' | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='CORRECTION_POLICY_MISMATCH', message='the audit profile does not satisfy the current correction policy'), delta) | |
| committed = self.committed.get(record['record_ref']) | |
| if committed is not None: | |
| if committed == {'corrected_value': arguments['corrected_value'], 'correction_class': arguments['correction_class'], 'audit_profile_id': arguments['audit_profile_id']}: | |
| delta['idempotent_replays'] = 1 | |
| return (self._result('apply_form_correction', 'success', {'record_ref': record['record_ref'], 'correction_handle': arguments['correction_handle'], 'corrected_value': arguments['corrected_value'], 'audit_profile_id': arguments['audit_profile_id'], 'form_status': 'complete', 'save_state': 'saved', 'audit_recorded': True, 'idempotent': True}), delta) | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='CORRECTION_ALREADY_APPLIED', message='this dossier already has a committed correction in the current task'), delta) | |
| if self._record_value(record) == arguments['corrected_value']: | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='NO_VALUE_CHANGE', message='the replacement value must differ from the current value'), delta) | |
| if self._correctable_state(record) is None: | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='FORM_NOT_CORRECTABLE', message='the active dossier is not a completed saved form'), delta) | |
| before = self.manager.snapshot() | |
| reason = DATA_AUDIT_PROFILES[expected_profile] | |
| expected_after = self._expected_raw_after(before, record, arguments['corrected_value'], reason) | |
| delta['raw_calls'] = 1 | |
| try: | |
| raw_result = self.raw_update(self.manager, visit_id=record['visit_id'], question_id=record['question_id'], new_value=arguments['corrected_value'], reason_for_change=reason, ui_selection=arguments['correction_handle']) | |
| except Exception: | |
| self.manager.restore(before) | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='RAW_CORRECTION_FAILED', message='the raw correction failed without committing clinical state'), delta) | |
| if raw_result.get('status') != 'succeeded' or raw_result.get('error_code') is not None or self.manager.snapshot() != expected_after: | |
| self.manager.restore(before) | |
| delta['failed_write_requests'] = 1 | |
| return (self._result('apply_form_correction', 'error', code='RAW_POSTCONDITION_FAILED', message='the raw correction did not produce the declared atomic artifact'), delta) | |
| self.committed[record['record_ref']] = {'corrected_value': arguments['corrected_value'], 'correction_class': arguments['correction_class'], 'audit_profile_id': arguments['audit_profile_id']} | |
| if self.rule_revalidation.get(cell) in {'awaiting_exact_stale', 'awaiting_current_policy'}: | |
| self.rule_revalidation[cell] = 'ready_current' | |
| delta['raw_writes_committed'] = 1 | |
| delta['transactions_appended'] = 1 | |
| return (self._result('apply_form_correction', 'success', {'record_ref': record['record_ref'], 'correction_handle': arguments['correction_handle'], 'corrected_value': arguments['corrected_value'], 'audit_profile_id': arguments['audit_profile_id'], 'form_status': 'complete', 'save_state': 'saved', 'audit_recorded': True, 'idempotent': False}), delta) | |
| def _oracle_evolution_snapshot(self): | |
| value = self._oracle_clinical_one_correction_snapshot() | |
| value['evolution_contract'] = {'case_version': 'oracle-correction-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)} | |
| return value | |
| def _oracle_evolution_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('evolution_contract', None) != {'case_version': 'oracle-correction-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}: | |
| raise ValueError('Oracle evolution contract differs') | |
| self._oracle_clinical_one_correction_restore(value) | |
| def _oracle_clinical_one_correction_snapshot(self): | |
| return {'schema': 'oracle-clinical-one-form-correction/v7', 'source_lock_closure_sha256': self.source_lock['snapshot_identity_sha256'], 'raw_state': self.manager.snapshot(), 'active_task_id': self.active_task_id, 'active_requests': ext_deepcopy(self.active_requests), 'active_order': ext_deepcopy(self.active_order), 'policy_matrix': {f'{visit_type}|{correction_class}': profile_id for ((visit_type, correction_class), profile_id) in self.policy_matrix.items()}, 'applied_boundary_events': sorted(self.applied_boundary_events), 'rule_revalidation': {f'{visit_type}|{correction_class}': state for ((visit_type, correction_class), state) in self.rule_revalidation.items()}, 'episode_entry_raw': ext_deepcopy(self.episode_entry_raw), 'episode_transaction_start': self.episode_transaction_start, 'resources': ext_deepcopy(self.resources), 'allowance': self.allowance, 'remaining': self.remaining, 'receipts': ext_deepcopy(self.receipts), 'committed': ext_deepcopy(self.committed)} | |
| def _oracle_clinical_one_correction_restore(self, snapshot): | |
| if snapshot.get('schema') != 'oracle-clinical-one-form-correction/v7': | |
| raise ValueError('unsupported Oracle correction snapshot') | |
| if snapshot.get('source_lock_closure_sha256') != self.source_lock['snapshot_identity_sha256']: | |
| raise ValueError('snapshot raw source closure does not match') | |
| self.manager.restore(ext_deepcopy(snapshot['raw_state'])) | |
| self.active_task_id = snapshot.get('active_task_id') | |
| self.active_requests = ext_deepcopy(snapshot.get('active_requests', {})) | |
| self.active_order = ext_deepcopy(snapshot.get('active_order', list(self.active_requests))) | |
| self.policy_matrix = {tuple(key.split('|', 1)): profile_id for (key, profile_id) in snapshot.get('policy_matrix', {}).items()} | |
| if set(self.policy_matrix) != set(DATA_POLICY_MATRIX): | |
| raise ValueError('snapshot correction policy matrix is incomplete') | |
| self.applied_boundary_events = set(snapshot.get('applied_boundary_events', [])) | |
| self.rule_revalidation = {tuple(key.split('|', 1)): state for (key, state) in snapshot.get('rule_revalidation', {}).items()} | |
| self.episode_entry_raw = ext_deepcopy(snapshot.get('episode_entry_raw')) | |
| self.episode_transaction_start = int(snapshot.get('episode_transaction_start', 0)) | |
| self.resources = ext_deepcopy(snapshot.get('resources', fn__empty_resources())) | |
| self.allowance = int(snapshot.get('allowance', 18)) | |
| self.remaining = int(snapshot.get('remaining', self.allowance)) | |
| self.receipts = ext_deepcopy(snapshot.get('receipts', [])) | |
| self.committed = ext_deepcopy(snapshot.get('committed', {})) | |