ReScopeBench / cases /redcap /runtime.py
JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
83.8 kB
"""Released environment operations and snapshot validation."""
from __future__ import annotations
from copy import deepcopy as ext_deepcopy
from functools import lru_cache
from pathlib import Path as ext_Path
from typing import Any as ext_Any
import hashlib as mod_hashlib
import importlib as mod_importlib
import json as mod_json
import jsonschema as mod_jsonschema
import sys as mod_sys
from .spec import CASE_DIR, DATA_GROUP_BY_ATOM, DATA_ENTITY_ID_FIELDS, DATA_TASK_IDS, DATA_TOOLS_2, DATA_SYNTHETIC_ASSIGNEES, DATA_PRE_STRUCTURE_AUTHORITY, DATA_TASK_IDS_2, DATA_PROFILE_SPECS, DATA_SCHEDULE_2, DATA_CHANGED_STRUCTURE_ATOMS, DATA_POST_STRUCTURE_AUTHORITY, DATA_PRE_STRUCTURE_AUTHORITY_2, DATA_STREAM_BLUEPRINT, DATA_WORKFLOW_CLASS, DATA_LIST_TOOLS, DATA_STRUCTURE_GROUPS, DATA_TOOL_BY_NAME, DATA_WRITE_TOOLS, DATA_DRIFT_CHANGED_STRUCTURES, DATA_STREAM_TASK_BLUEPRINT, DATA_DEV_BLUEPRINT
def fn_public_task(task_id):
packet = fn_public_task_2(task_id)
if packet['objective'].count('Close as many listed REDCap work packets as possible in priority order.') != 1:
raise ValueError('Parent REDCap order statement differs')
packet['objective'] = packet['objective'].replace('Close as many listed REDCap work packets as possible in priority order.', 'Close as many listed REDCap work packets as possible. Packets may be processed in any order; an unfinished record does not block an unrelated record.')
packet['completion'].update(mode='independent', priority_order='none', started_item_must_close=False)
return packet
def fn_activate_task(self, task_id, *, apply_boundary=True):
if task_id not in DATA_TASK_IDS_2:
return fn__error('TASK_NOT_AVAILABLE', 'the request event is unavailable')
expected = DATA_TASK_IDS_2[len(self._activated_tasks)] if len(self._activated_tasks) < len(DATA_TASK_IDS_2) else None
if task_id != expected:
raise ValueError(f'expected {expected}, got {task_id}')
self._task_id = task_id
self._events = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._targets = [self._inject_target(target) for target in fn_stream_targets(task_id)]
boundary = self.apply_structure_event() if task_id == 'T09' and apply_boundary else None
self._entry_entities = self._state.snapshot()
self._activated_tasks.append(task_id)
self._assert_invariants()
return {'status': 'success', 'event_id': fn_opaque_event_id(task_id), 'boundary_event_applied': bool(boundary and boundary['applied']), 'public_notice': '', 'world_reset': False, 'budget_reset': True, 'entry_business_hash': self.business_hash()}
def fn__workflow_recipe(target, compact):
field = compact['target_field']
query = compact['query']
event = compact['record_event']
forms = {row['form_instance_id']: row for row in compact['forms']}
handles = {'primary': target['primary_form_id'], 'companion': target['companion_form_id']}
complete_roles = []
if not event['locked']:
for (role, handle) in handles.items():
if forms[handle]['completion_status'] not in {'complete', 'locked'}:
complete_roles.append(role)
return {'workflow_class': target['workflow_class'], 'unlock_first': bool(event['locked']), 'update_field': not (field.get('value') == target['corrected_value'] and field.get('status') == 'verified'), 'answer_query': query.get('status') == 'open', 'resolve_query': query.get('status') != 'resolved', 'complete_form_roles': complete_roles, 'lock_final': True}
def fn__error(code, message):
return {'status': 'error', 'data': {'error_code': code}, 'message': message}
def fn__packet_entities(target, assignee):
group = DATA_GROUP_BY_ATOM[target['structure_atom']]
profile = DATA_PROFILE_SPECS[target['profile_id']]
query_status = profile['query_status']
primary_value = profile['target_value']
if primary_value == 'correct':
primary_value = target['corrected_value']
elif primary_value == 'wrong':
primary_value = f"stale-{target['target_id'][-6:]}"
primary_missing = 0 if str(primary_value).strip() else 1
primary_status = profile['primary_form']
companion_status = profile['companion_form']
locked = bool(profile['locked'])
complete_count = sum((status in {'complete', 'locked'} for status in (primary_status, companion_status)))
event_status = 'locked' if locked else 'complete' if complete_count == 2 else 'in_progress' if complete_count else 'not_started'
answer_text = 'Source confirmation received.' if query_status in {'answered', 'resolved'} else ''
companion_value = f"reviewed-{target['target_id'][-6:]}"
rows = {name: [] for name in DATA_ENTITY_ID_FIELDS}
rows['record'].append({'record_id': target['record_id'], 'project_id': target['project_id'], 'redcap_record_id': target['redcap_record_id'], 'subject_label': target['subject_label'], 'data_access_group': group['data_access_group'], 'site_id': group['data_access_group'], 'site_name': group['project_title'], 'enrollment_status': 'enrolled', 'consent_status': 'signed', 'open_query_count': 1 if query_status == 'open' else 0, 'locked_event_count': 1 if locked else 0, 'last_event_id': target['event_id'], 'created_at': '2026-05-18T10:30:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
rows['record_event'].append({'record_event_id': target['record_event_id'], 'project_id': target['project_id'], 'record_id': target['record_id'], 'event_id': target['event_id'], 'event_status': event_status, 'form_complete_count': complete_count, 'form_incomplete_count': 2 - complete_count, 'locked': locked, 'lock_reason': 'Prior closeout lock' if locked else '', 'last_verified_by': assignee if locked else '', 'last_verified_at': '2026-05-18T10:30:00Z' if locked else None, 'created_at': '2026-05-18T10:30:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
for (form_id, instrument_id, status, missing) in ((target['primary_form_id'], target['primary_instrument_id'], primary_status, primary_missing), (target['companion_form_id'], target['companion_instrument_id'], companion_status, 0)):
rows['form_instance'].append({'form_instance_id': form_id, 'project_id': target['project_id'], 'record_id': target['record_id'], 'event_id': target['event_id'], 'instrument_id': instrument_id, 'completion_status': status, 'completion_code': 0 if status == 'incomplete' else 1 if status == 'unverified' else 2, 'missing_required_count': missing, 'entered_by': assignee if status != 'incomplete' else '', 'created_at': '2026-05-18T10:30:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
for (value_id, instrument_id, field_id, value) in ((target['primary_value_id'], target['primary_instrument_id'], target['primary_field_id'], primary_value), (target['companion_value_id'], target['companion_instrument_id'], target['companion_field_id'], companion_value)):
rows['field_value'].append({'value_id': value_id, 'project_id': target['project_id'], 'record_id': target['record_id'], 'event_id': target['event_id'], 'instrument_id': instrument_id, 'field_id': field_id, 'value': value, 'source': 'manual', 'status': 'verified' if str(value).strip() else 'draft', 'updated_by': assignee if str(value).strip() else '', 'updated_at': '2026-05-18T10:30:00Z'})
rows['data_query'].append({'query_id': target['query_id'], 'project_id': target['project_id'], 'record_id': target['record_id'], 'event_id': target['event_id'], 'instrument_id': target['primary_instrument_id'], 'field_id': target['primary_field_id'], 'status': query_status, 'priority': 'high', 'query_text': f"Confirm {target['primary_field_label']} before closeout.", 'answer_text': answer_text, 'opened_by': target['resolver'], 'assigned_to': assignee, 'opened_at': '2026-05-18T10:30:00Z', 'answered_at': '2026-05-18T10:30:00Z' if query_status in {'answered', 'resolved'} else None, 'resolved_at': '2026-05-18T10:30:00Z' if query_status == 'resolved' else None, 'updated_at': '2026-05-18T10:30:00Z'})
return rows
def fn__actor_bindings(target, assignee):
group = DATA_GROUP_BY_ATOM[target['structure_atom']]
if group['mode'] == 'manager':
actor = group['resolver']
return {'field_actor_user_id': actor, 'query_answer_actor_user_id': actor, 'query_resolver_user_id': actor, 'lock_actor_user_id': actor}
return {'field_actor_user_id': assignee, 'query_answer_actor_user_id': assignee, 'query_resolver_user_id': group['resolver'], 'lock_actor_user_id': assignee}
def fn__digest(value):
return mod_hashlib.sha256(fn__canonical(value).encode('utf-8')).hexdigest()
def fn__hash(value):
encoded = mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
return mod_hashlib.sha256(encoded.encode('utf-8')).hexdigest()
def fn__normalize(result):
value = ext_deepcopy(result)
if value.get('status') == 'error':
message = str(value.get('message') or '')
value.setdefault('data', {})['error_code'] = message.split(':', 1)[0] if ':' in message else 'OPERATION_FAILED'
return value
def fn_public_task_2(task_id):
task = fn_public_task_3(task_id)
task['completion'].pop('verification_required')
task['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': "the final successful lock response's packet-completion receipt", 'proves': "the committed packet's completed forms, resolved query, verified field and locked event as reported"}
task['budget']['charging'].append('An exact project_id/record_id profile request for your own completed packet in this episode returns only the previously issued closeout receipt, at zero read/write/call quota. Other profile and authority discovery remains paid.')
return task
def fn_stream_targets(task_id):
if task_id not in DATA_STREAM_BLUEPRINT:
raise ValueError(f'unknown REDCap stream task: {task_id}')
targets = []
for (slot, (structure_id, profile_id, rule_id)) in enumerate(DATA_STREAM_BLUEPRINT[task_id], 1):
group = DATA_GROUP_BY_ATOM[structure_id]
ids = fn__dynamic_ids(task_id, structure_id)
targets.append({'target_id': fn__opaque('packet', task_id, slot, length=12), 'task_id': task_id, 'slot': slot, 'structure_atom': structure_id, 'profile_id': profile_id, 'rule_atom': rule_id, 'workflow_class': DATA_WORKFLOW_CLASS[profile_id], 'project_id': group['project_id'], 'project_title': group['project_title'], 'subject_label': fn__subject_label(task_id, structure_id), 'redcap_record_id': fn__opaque_2('RC', task_id, structure_id, length=8).upper(), 'event_id': group['event_id'], 'primary_instrument_id': group['primary_instrument_id'], 'primary_field_id': group['primary_field_id'], 'primary_field_label': group['primary_field_label'], 'companion_instrument_id': group['companion_instrument_id'], 'companion_field_id': group['companion_field_id'], 'corrected_value': group['corrected_value'], 'old_assignee': DATA_PRE_STRUCTURE_AUTHORITY[structure_id], 'new_assignee': DATA_POST_STRUCTURE_AUTHORITY[structure_id], 'resolver': group['resolver'], 'reference_writes': DATA_PROFILE_SPECS[profile_id]['reference_writes'], **ids})
return tuple(targets)
def fn_opaque_event_id(task_id):
if task_id not in DATA_TASK_IDS_2:
raise ValueError(f'unknown REDCap stream task: {task_id}')
return fn__opaque('EV', task_id, 'closeout').upper()
def fn__canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn_public_task_3(task_id):
targets = []
for target in fn_stream_targets(task_id):
targets.append({'request_ref': target['target_id'], 'priority': target['slot'], 'workflow_class': target['workflow_class'], 'project_title': target['project_title'], 'subject_label': target['subject_label'], 'required_field_label': target['primary_field_label'], 'corrected_value': target['corrected_value'], 'experience_keys': {'project_binding': target['project_title'], 'workflow_procedure': target['workflow_class']}, 'operation_handles': {'query_id': target['query_id'], 'record_event_id': target['record_event_id'], 'event_id': target['event_id'], 'primary_form_id': target['primary_form_id'], 'companion_form_id': target['companion_form_id']}, 'requested_state': 'required value verified, query resolved, both forms complete, and the record event locked with a nonempty reason'})
return {'schema': 'rescopebench-redcap-reusable-authority-task/v7', 'event_id': fn_opaque_event_id(task_id), 'objective': 'Close as many listed REDCap work packets as possible in priority order. For a new project binding, resolve the exact project and subject and inspect the active packet. A verified project binding and workflow-class procedure may be reused for later packets with the same experience keys; only the current subject record and supplied task-scoped handles then need binding. A successful final lock returns authoritative packet-completion evidence, so an extra readback is optional. Current business evidence overrides retained authority. Do not alter unrelated records.', 'targets': targets, 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': False}, 'budget': fn_budget_contract()}
def fn__workflow_recipe_from_profile(target):
spec = DATA_PROFILE_SPECS[target['profile_id']]
unlock_first = bool(spec['locked'])
complete_roles = []
if not unlock_first:
if spec['primary_form'] not in {'complete', 'locked'}:
complete_roles.append('primary')
if spec['companion_form'] not in {'complete', 'locked'}:
complete_roles.append('companion')
return {'workflow_class': target['workflow_class'], 'unlock_first': unlock_first, 'update_field': spec['target_value'] != 'correct', 'answer_query': spec['query_status'] == 'open', 'resolve_query': spec['query_status'] != 'resolved', 'complete_form_roles': complete_roles, 'lock_final': True}
def fn__dynamic_ids(task_id, structure_id):
return {'record_id': fn__opaque_2('rec', task_id, structure_id, 'record'), 'record_event_id': fn__opaque_2('rev', task_id, structure_id, 'record-event'), 'primary_form_id': fn__opaque_2('frm', task_id, structure_id, 'primary-form'), 'companion_form_id': fn__opaque_2('frm', task_id, structure_id, 'companion-form'), 'primary_value_id': fn__opaque_2('val', task_id, structure_id, 'primary-value'), 'companion_value_id': fn__opaque_2('val', task_id, structure_id, 'companion-value'), 'query_id': fn__opaque_2('qry', task_id, structure_id, 'query')}
def fn__opaque(prefix, *parts, length=14):
material = '|'.join(['redcap-reusable-authority-v7', *(str(part) for part in parts)])
token = mod_hashlib.sha256(material.encode('ascii')).hexdigest()[:length]
return f'{prefix}-{token}'
def fn__subject_label(task_id, structure_id):
group = DATA_GROUP_BY_ATOM[structure_id]
stem = group['project_title'].split()[0]
token = fn__opaque_2('case', task_id, structure_id, length=8).split('-', 1)[1].upper()
return f'{stem} closeout case {token}'
def fn__opaque_2(prefix, *parts, length=12):
payload = '|'.join((str(part) for part in parts))
token = mod_hashlib.sha256(f'redcap-stream|{payload}'.encode('utf-8')).hexdigest()
return f'{prefix}-{token[:length]}'
def fn_budget_contract():
return {'limits': [{'resource': 'read_units', 'allowance': 6}, {'resource': 'write_attempts', 'allowance': 17}, {'resource': 'maximum_tool_calls', 'allowance': 48}], 'charging': ['A successful bounded listing charges at least one read unit and otherwise one unit per matched row before pagination.', 'An exact active-packet get_record_profile projection charges two read units during discovery.', 'After a packet has closed, an optional exact profile read is served from the current episode cache and charges zero read units.', 'An exact record-scoped current-query lookup charges two read units for the query and assignment-authority join.', 'A failed read charges one read unit. Every attempted mutation charges one write attempt, including rejected mutations.'], 'exhaustion': 'An unfunded business call fails without changing business state.', 'persistence': 'Project-title bindings, project-level field and authority bindings, and workflow-class procedures persist until contradicted. Request, subject, record, query, form, and record-event handles are task-scoped. Business state persists across episodes; all allowances replenish.'}
def fn__base_entities():
fixture = fn_fixture_for_task('T01')
static_types = {'project', 'project_user', 'dictionary_version', 'event', 'instrument', 'instrument_field'}
entities = {name: [] for name in DATA_ENTITY_ID_FIELDS}
for entity_type in static_types:
entities[entity_type] = ext_deepcopy(fixture['entities'][entity_type])
for project in entities['project']:
project.update({'record_count': 0, 'open_query_count': 0})
for user in entities['project_user']:
user['status'] = 'active'
by_user = {row['user_id']: row for row in entities['project_user']}
compared = ('project_id', 'role', 'data_access_group', 'can_export_identifiers', 'can_manage_dictionary', 'can_lock_records', 'status')
for structure_id in DATA_DRIFT_CHANGED_STRUCTURES:
group = DATA_GROUP_BY_ATOM[structure_id]
old = by_user[group['editor_old']]
new = by_user[group['editor_new']]
if any((old[key] != new[key] for key in compared)):
raise AssertionError(f'non-equivalent drift assignees for {structure_id}')
return entities
@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_raw_logic(source_root):
prefix = 'mcp_servers'
saved = {name: module for (name, module) in list(mod_sys.modules.items()) if name == prefix or name.startswith(f'{prefix}.')}
for name in saved:
mod_sys.modules.pop(name, None)
mod_sys.path.insert(0, source_root)
try:
module = mod_importlib.import_module('mcp_servers.redcap')
finally:
mod_sys.path.remove(source_root)
for name in list(mod_sys.modules):
if name == prefix or name.startswith(f'{prefix}.'):
mod_sys.modules.pop(name, None)
mod_sys.modules.update(saved)
return module
def fn_fixture_for_task(task_id):
if task_id != 'DEV01' and task_id not in DATA_STREAM_TASK_BLUEPRINT:
raise ValueError(f'unknown task: {task_id}')
post_drift = task_id != 'DEV01' and int(task_id[1:]) >= 9
blueprint = DATA_DEV_BLUEPRINT if task_id == 'DEV01' else DATA_STREAM_TASK_BLUEPRINT[task_id]
profile_by_atom = fn__profile_assignments(task_id)
entities = {name: [] for name in DATA_ENTITY_ID_FIELDS}
targets_by_atom: dict[str, dict[str, ext_Any]] = {}
for (ordinal, group) in enumerate(DATA_STRUCTURE_GROUPS, 1):
atom_id = group['atom_id']
profile_id = profile_by_atom[atom_id]
profile = DATA_PROFILE_SPECS[profile_id]
project_id = group['project_id']
current_editor = fn__current_editor(group, post_drift)
users: list[dict[str, ext_Any]] = []
if group['mode'] == 'entry':
old_active = not (post_drift and atom_id in DATA_DRIFT_CHANGED_STRUCTURES)
users.extend([fn__user_row(group['editor_old'], project_id, role='data_entry', group=group['data_access_group'], status='active' if old_active else 'inactive', can_lock=True), fn__user_row(group['editor_new'], project_id, role='data_entry', group=group['data_access_group'], status='inactive' if old_active else 'active', can_lock=True), fn__user_row(group['resolver'], project_id, role='monitor', group='central')])
elif group['mode'] == 'coordinator':
users.extend([fn__user_row(group['editor_old'], project_id, role='clinical_coordinator', group='central', can_lock=True), fn__user_row(group['resolver'], project_id, role='monitor', group='central')])
else:
users.extend([fn__user_row(group['editor_old'], project_id, role='data_entry', group='external-site'), fn__user_row(group['resolver'], project_id, role='data_manager', group='central', can_lock=True, can_manage_dictionary=True, can_export_identifiers=True), fn__user_row(group['pi'], project_id, role='principal_investigator', group='central', can_lock=True, can_manage_dictionary=True, can_export_identifiers=True)])
entities['project_user'].extend(users)
query_status = profile['query_status']
target_value = profile['target_value']
if target_value == 'correct':
target_value = group['corrected_value']
elif target_value == 'wrong':
target_value = f'stale-{ordinal:02d}'
companion_value = f'reviewed-{ordinal:02d}'
primary_missing = 0 if str(target_value).strip() else 1
primary_status = profile['primary_form']
companion_status = profile['companion_form']
locked = bool(profile['locked'])
complete_count = sum((status in {'complete', 'locked'} for status in (primary_status, companion_status)))
event_status = 'locked' if locked else 'complete' if complete_count == 2 else 'in_progress' if complete_count else 'not_started'
open_count = 1 if query_status == 'open' else 0
entities['project'].append({'project_id': project_id, 'title': group['project_title'], 'purpose': 'clinical research closeout', 'status': 'production', 'availability': 'active', 'design': 'longitudinal', 'primary_site': group['project_title'], 'surveys_enabled': False, 'record_autonumbering': True, 'record_count': 1, 'open_query_count': open_count, 'pending_export_count': 0, 'active_instrument_count': 2, 'data_access_group_count': 1, 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z', 'last_activity_at': '2026-05-18T10:30:00Z'})
entities['event'].append({'event_id': group['event_id'], 'project_id': project_id, 'unique_event_name': f'closeout_{ordinal:02d}', 'event_label': group['event_label'], 'arm_num': 1, 'day_offset': ordinal * 7, 'offset_min': 0, 'offset_max': 30, 'status': 'active', 'sequence': 1, 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
dictionary_id = fn__opaque_3('dict', atom_id, 'dictionary-v1')
draft_dictionary_id = fn__opaque_3('dict', atom_id, 'dictionary-v2')
entities['dictionary_version'].extend([{'dictionary_version_id': dictionary_id, 'project_id': project_id, 'version_number': 1, 'status': 'applied', 'created_by': group['resolver'], 'applied_by': group['resolver'], 'change_summary': 'Initial closeout dictionary', 'created_at': '2026-02-01T09:00:00Z', 'applied_at': '2026-02-02T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'}, {'dictionary_version_id': draft_dictionary_id, 'project_id': project_id, 'version_number': 2, 'status': 'draft', 'created_by': group['resolver'], 'applied_by': '', 'change_summary': 'Pending closeout dictionary update', 'created_at': '2026-02-10T09:00:00Z', 'applied_at': None, 'updated_at': '2026-05-18T10:30:00Z'}])
for which in ('primary', 'companion'):
instrument_id = group[f'{which}_instrument_id']
field_id = group[f'{which}_field_id']
entities['instrument'].append({'instrument_id': instrument_id, 'project_id': project_id, 'instrument_name': group[f'{which}_instrument_name'], 'instrument_label': group[f'{which}_instrument_label'], 'category': 'clinical', 'status': 'active', 'version': 1, 'field_count': 1, 'is_survey': False, 'mapped_event_ids': [group['event_id']], 'last_dictionary_version': dictionary_id, 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
entities['instrument_field'].append({'field_id': field_id, 'project_id': project_id, 'instrument_id': instrument_id, 'field_name': group[f'{which}_field_name'], 'field_label': group[f'{which}_field_label'], 'field_type': 'text', 'required': True, 'identifier': False, 'validation': 'none', 'select_choices': 'none', 'branching_logic': 'None', 'ordinal': 1, 'status': 'active', 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
entities['record'].append({'record_id': group['record_id'], 'project_id': project_id, 'redcap_record_id': group['redcap_record_id'], 'subject_label': group['subject_label'], 'data_access_group': group['data_access_group'], 'site_id': group['data_access_group'], 'site_name': group['project_title'], 'enrollment_status': 'enrolled', 'consent_status': 'signed', 'open_query_count': open_count, 'locked_event_count': 1 if locked else 0, 'last_event_id': group['event_id'], 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
entities['record_event'].append({'record_event_id': group['record_event_id'], 'project_id': project_id, 'record_id': group['record_id'], 'event_id': group['event_id'], 'event_status': event_status, 'form_complete_count': complete_count, 'form_incomplete_count': 2 - complete_count, 'locked': locked, 'lock_reason': 'Prior closeout lock' if locked else '', 'last_verified_by': current_editor if locked else '', 'last_verified_at': '2026-05-18T10:30:00Z' if locked else None, 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
for (form_id, instrument_id, status, missing) in ((group['primary_form_id'], group['primary_instrument_id'], primary_status, primary_missing), (group['companion_form_id'], group['companion_instrument_id'], companion_status, 0)):
entities['form_instance'].append({'form_instance_id': form_id, 'project_id': project_id, 'record_id': group['record_id'], 'event_id': group['event_id'], 'instrument_id': instrument_id, 'completion_status': status, 'completion_code': fn__completion_code(status), 'missing_required_count': missing, 'entered_by': current_editor if status != 'incomplete' else '', 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'})
for (value_id, instrument_id, field_id, value) in ((fn__opaque_3('val', atom_id, 'primary-value'), group['primary_instrument_id'], group['primary_field_id'], target_value), (fn__opaque_3('val', atom_id, 'companion-value'), group['companion_instrument_id'], group['companion_field_id'], companion_value)):
entities['field_value'].append({'value_id': value_id, 'project_id': project_id, 'record_id': group['record_id'], 'event_id': group['event_id'], 'instrument_id': instrument_id, 'field_id': field_id, 'value': value, 'source': 'manual', 'status': 'verified' if str(value).strip() else 'draft', 'updated_by': current_editor if str(value).strip() else '', 'updated_at': '2026-05-18T10:30:00Z'})
answer_text = 'Source confirmation received.' if query_status in {'answered', 'resolved'} else ''
entities['data_query'].append({'query_id': group['query_id'], 'project_id': project_id, 'record_id': group['record_id'], 'event_id': group['event_id'], 'instrument_id': group['primary_instrument_id'], 'field_id': group['primary_field_id'], 'status': query_status, 'priority': 'high', 'query_text': f"Confirm {group['primary_field_label']} before closeout.", 'answer_text': answer_text, 'opened_by': group['resolver'], 'assigned_to': current_editor, 'opened_at': '2026-05-15T09:00:00Z', 'answered_at': '2026-05-18T10:30:00Z' if query_status in {'answered', 'resolved'} else None, 'resolved_at': '2026-05-18T10:30:00Z' if query_status == 'resolved' else None, 'updated_at': '2026-05-18T10:30:00Z'})
targets_by_atom[atom_id] = {'structure_atom': atom_id, 'profile_id': profile_id, 'project_id': project_id, 'record_id': group['record_id'], 'record_event_id': group['record_event_id'], 'event_id': group['event_id'], 'primary_instrument_id': group['primary_instrument_id'], 'primary_field_id': group['primary_field_id'], 'primary_form_id': group['primary_form_id'], 'companion_form_id': group['companion_form_id'], 'query_id': group['query_id'], 'corrected_value': group['corrected_value'], 'reference_writes': profile['reference_writes'], **fn__selected_actors(group, post_drift)}
targets = []
for (index, (atom_id, profile_id, rule_atom)) in enumerate(blueprint, 1):
target = ext_deepcopy(targets_by_atom[atom_id])
target.update({'target_id': f'closeout-{task_id.lower()}-{index}', 'profile_id': profile_id, 'rule_atom': rule_atom})
targets.append(target)
return {'task_id': task_id, 'post_drift': post_drift, 'entities': entities, 'targets': targets}
def fn__profile_assignments(task_id):
defaults = {f'S{index:02d}': f'P{index:02d}' for index in range(1, 9)}
blueprint = DATA_DEV_BLUEPRINT if task_id == 'DEV01' else DATA_STREAM_TASK_BLUEPRINT[task_id]
for (atom_id, profile_id, _) in blueprint:
defaults[atom_id] = profile_id
return defaults
def fn__current_editor(group, post_drift):
if post_drift and group['atom_id'] in DATA_DRIFT_CHANGED_STRUCTURES:
return group['editor_new']
return group['editor_old']
def fn__user_row(user_id, project_id, *, role, group, status='active', can_lock=False, can_manage_dictionary=False, can_export_identifiers=False):
return {'user_id': user_id, 'project_id': project_id, 'username': user_id.replace('usr-', 'staff.'), 'full_name': f'Project staff {user_id[-4:].upper()}', 'email': f'{user_id}@example.invalid', 'role': role, 'data_access_group': group, 'can_export_identifiers': can_export_identifiers, 'can_manage_dictionary': can_manage_dictionary, 'can_lock_records': can_lock, 'status': status, 'last_login_at': '2026-05-18T10:30:00Z', 'created_at': '2026-02-01T09:00:00Z', 'updated_at': '2026-05-18T10:30:00Z'}
def fn__opaque_3(prefix, atom_id, label):
token = mod_hashlib.sha256(f'redcap-query-lock-v1|{atom_id}|{label}'.encode('ascii')).hexdigest()[:8]
return f'{prefix}-{token}'
def fn__completion_code(status):
return {'incomplete': 0, 'unverified': 1, 'complete': 2, 'locked': 2}[status]
def fn__selected_actors(group, post_drift):
if group['mode'] == 'manager':
actor = group['resolver']
return {'field_actor_user_id': actor, 'query_answer_actor_user_id': actor, 'query_resolver_user_id': actor, 'lock_actor_user_id': actor}
editor = fn__current_editor(group, post_drift)
return {'field_actor_user_id': editor, 'query_answer_actor_user_id': editor, 'query_resolver_user_id': group['resolver'], 'lock_actor_user_id': editor}
class World:
_legacy_staff_projection = False
def _first_incomplete_slot(self):
return None
def public_task(self):
return fn_public_task(self._task_id)
def snapshot(self):
value = self._redcap_authority_evolution_snapshot()
value['independent_packet_contract'] = 'redcap-independent-packets-evolution-v3'
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('independent_packet_contract', None) != 'redcap-independent-packets-evolution-v3':
raise ValueError('REDCap independent packet contract differs')
self._redcap_authority_evolution_restore(value)
def apply_structure_event(self):
result = self._redcap_reusable_authority_apply_structure_event()
self.authority_revalidation.clear()
return result
def dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
result = self._redcap_evolution_dispatch(name, arguments, actor_user_id)
self.authority_revalidation.clear()
return result
def __init__(self, *args, **kwargs):
self._own_closeouts = {}
self._redcap_authority_successor_init(*args, **kwargs)
def activate_task(self, task_id, *, apply_boundary=True):
result = fn_activate_task(self, task_id, apply_boundary=apply_boundary)
if result.get('status') == 'success':
self._own_closeouts = {}
return result
def _target_complete(self, target):
if self._task_id is None:
return False
grade = self.grade(self._task_id)
return any((row['target_id'] == target['target_id'] and row['complete'] for row in grade['deliverables']))
def _read_cost(self, name, result):
if name == 'get_record_profile' and result.get('status') == 'success':
target = self._active_target_from_profile(result)
if target is not None and self._target_complete(target):
return 0
return self._redcap_actionable_authority_read_cost(name, result)
def _compact_profile(self, target, result):
value = self._redcap_actionable_authority_compact_profile(target, result)
compact = value['data']
authority = compact['workflow_authority']
compact['evidence_scope'] = {'persistent_until_contradicted': {'project_binding_key': target['project_title'], 'project_title': target['project_title'], 'project_id': target['project_id'], 'instrument_id': compact['target_field']['instrument_id'], 'field_id': compact['target_field']['field_id'], **ext_deepcopy(authority)}, 'reusable_workflow_procedure': fn__workflow_recipe(target, compact), 'task_scoped': {'request_ref': target['target_id'], 'subject_label': target['subject_label'], 'record_id': compact['record']['record_id'], 'query_id': compact['query']['query_id'], 'form_instance_ids': sorted((row['form_instance_id'] for row in compact['forms'])), 'record_event_id': compact['record_event']['record_event_id']}}
return value
def apply_assignment_drift(self, event_id='evt-redcap-authority-rotation-v7'):
if event_id not in {'evt-redcap-authority-rotation-v7', 'evt-redcap-authority-rotation-v5'}:
raise ValueError('unknown REDCap authority event')
return self.apply_structure_event()
def apply_drift(self, drift_id='evt-redcap-authority-rotation-v7'):
return self.apply_assignment_drift(drift_id)
def apply_boundary(self, event_id):
if event_id in {'T09', 'evt-redcap-authority-rotation-v7', 'evt-redcap-authority-rotation-v5'}:
return self.apply_structure_event()
return {'event_id': event_id, 'application_count': self._drift_application_count, 'applied': False, 'idempotent_noop': True, 'before_world_sha256': self.business_hash(), 'after_world_sha256': self.business_hash(), 'registered_delta_sha256': 'c906f6670e3358b8460d789cc5d65113fcdba816ef2ee8d83c2ef6f871ec3c00'}
def _active_target_from_profile(self, result):
record = result.get('data', {}).get('record', {})
record_id = record.get('record_id')
project_id = record.get('project_id')
return next((target for target in self._targets if target['record_id'] == record_id and target['project_id'] == project_id), None)
@staticmethod
def _workflow_authority(target, query):
return {'field_actor_user_id': target['field_actor_user_id'], 'form_actor_user_id': target['field_actor_user_id'], 'query_answer_actor_user_id': target['query_answer_actor_user_id'], 'query_resolver_user_id': target['query_resolver_user_id'], 'lock_actor_user_id': target['lock_actor_user_id'], 'evidence_basis': 'record_scoped_query_and_assignment_authority'}
def _target_for_arguments(self, name, arguments):
key_by_tool = {'update_record_field': ('record_id', 'record_id'), 'update_data_query_answer': ('query_id', 'query_id'), 'resolve_data_query': ('query_id', 'query_id'), 'mark_form_complete': ('form_instance_id', None), 'set_record_event_lock': ('record_event_id', 'record_event_id')}
selected = key_by_tool.get(name)
if selected is None:
return None
(argument_key, target_key) = selected
value = arguments.get(argument_key)
for target in self._targets:
if target_key is None:
if value in {target['primary_form_id'], target['companion_form_id']}:
return target
elif target.get(target_key) == value:
return target
return None
def _target_for_read(self, arguments):
record_id = arguments.get('record_id')
project_id = arguments.get('project_id')
return next((target for target in self._targets if target['record_id'] == record_id and target['project_id'] == project_id), None)
def _charged_guard_error(self, name, code, message):
if self._calls >= 48:
result = fn__error('CALL_BUDGET_EXHAUSTED', 'task call safeguard is exhausted')
result['budget'] = self._budget_receipt()
return result
if self._write_attempts >= 17:
result = fn__error('WRITE_BUDGET_EXHAUSTED', 'task mutation-attempt allowance is exhausted')
result['budget'] = self._budget_receipt()
return result
before = self.business_hash()
self._calls += 1
self._write_attempts += 1
result = fn__error(code, message)
self._record_adapter_event(name, 'session-redcap-closeout-4x9', result, before, before, cost=1)
result['budget'] = self._budget_receipt()
result['receipt_index'] = len(self._events)
return result
def _budget_receipt(self):
return {'read_limit': 6, 'read_used': self._read_units, 'read_remaining': max(0, 6 - self._read_units), 'write_limit': 17, 'writes_used': self._write_attempts, 'writes_remaining': max(0, 17 - self._write_attempts), 'call_limit': 48, 'calls_used': self._calls}
@property
def calls(self):
return self._calls
@property
def read_units(self):
return self._read_units
@property
def writes(self):
return self._write_attempts
def _current_assignee(self, structure_id):
group = DATA_GROUP_BY_ATOM[structure_id]
if group['mode'] == 'manager':
return group['editor_old']
return self._assignee_by_structure[structure_id]
def _inject_target(self, target):
assignee = self._current_assignee(target['structure_atom'])
for (entity_type, rows) in fn__packet_entities(target, assignee).items():
for row in rows:
self._state.add_entity(entity_type, row, DATA_ENTITY_ID_FIELDS[entity_type])
project = self._state.get_entity('project', target['project_id'], 'project_id')
project_records = self._state.query_entities('record', lambda row: row.get('project_id') == target['project_id'])
project_queries = self._state.query_entities('data_query', lambda row: row.get('project_id') == target['project_id'])
self._state.update_entity('project', target['project_id'], {'record_count': len(project_records), 'open_query_count': sum((row.get('status') == 'open' for row in project_queries)), 'last_activity_at': '2026-05-18T10:30:00Z', 'updated_at': '2026-05-18T10:30:00Z'}, 'project_id')
if project is None:
raise AssertionError('target project disappeared during injection')
return {**ext_deepcopy(target), **fn__actor_bindings(target, assignee), 'current_assignee': assignee}
def current_episode_events(self):
return ext_deepcopy(self._events)
def business_hash(self):
return fn__digest({'entities': self._state.snapshot(), 'assignee_by_structure': self._assignee_by_structure})
def _business_hash(self):
return self.business_hash()
def lineage_hash(self):
return fn__digest(self.snapshot())
def grade(self, task_id=None):
selected = task_id or self._task_id
if selected != self._task_id or selected not in DATA_TASK_IDS:
raise ValueError('only the active stream task can be graded')
deliverables = []
for target in self._targets:
value = self._state.get_entity('field_value', target['primary_value_id'], 'value_id')
query = self._state.get_entity('data_query', target['query_id'], 'query_id')
record = self._state.get_entity('record', target['record_id'], 'record_id')
record_event = self._state.get_entity('record_event', target['record_event_id'], 'record_event_id')
forms = [self._state.get_entity('form_instance', form_id, 'form_instance_id') for form_id in (target['primary_form_id'], target['companion_form_id'])]
field_correct = bool(value and value.get('value') == target['corrected_value'] and (value.get('status') == 'verified'))
query_resolved = bool(query and query.get('status') == 'resolved' and record and (int(record.get('open_query_count') or 0) == 0))
forms_complete = bool(all((form and form.get('completion_status') in {'complete', 'locked'} and (int(form.get('missing_required_count') or 0) == 0) for form in forms)))
event_locked = bool(record_event and record_event.get('locked') is True and all((form and form.get('completion_status') == 'locked' for form in forms)))
complete = field_correct and query_resolved and forms_complete and event_locked
deliverables.append({'target_id': target['target_id'], 'score': 25.0 if complete else 0.0, 'complete': complete, 'field_correct': field_correct, 'query_resolved': query_resolved, 'forms_complete': forms_complete, 'event_locked': event_locked})
return {'task_id': selected, 'score': sum((row['score'] for row in deliverables)), 'max_score': 100.0, 'completed_artifacts': sum((row['complete'] for row in deliverables)), 'deliverables': deliverables, 'budget': self._budget_receipt()}
def public_tool_schemas(self, role):
return ext_deepcopy(DATA_TOOLS_2) if role == 'redcap_closeout_coordinator' else []
def task_targets(self):
return ext_deepcopy(self._targets)
def semantic_hash(self, snapshot=None):
return fn__hash(snapshot if snapshot is not None else self.snapshot())
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._events[since:])
def _record_adapter_event(self, name, actor, result, before_hash, after_hash, *, channel='learner', cost=0):
self._events.append({'sequence': len(self._events) + 1, 'channel': channel, 'tool': name, 'actor_user_id': actor, 'status': result.get('status'), 'error_code': result.get('data', {}).get('error_code'), 'cost': cost, 'state_hash_before': before_hash, 'state_hash_after': after_hash})
def _repair_required_counts(self, record_id, event_id, instrument_id):
required_fields = [row for row in self._state.list_entities('instrument_field') if row.get('instrument_id') == instrument_id and row.get('required') is True and (row.get('status') == 'active')]
values = self._state.list_entities('field_value')
missing = 0
for field in required_fields:
match = next((row for row in values if row.get('record_id') == record_id and row.get('event_id') == event_id and (row.get('instrument_id') == instrument_id) and (row.get('field_id') == field['field_id'])), None)
if match is None or not str(match.get('value') or '').strip():
missing += 1
for form in self._state.list_entities('form_instance'):
if form.get('record_id') == record_id and form.get('event_id') == event_id and (form.get('instrument_id') == instrument_id):
self._state.update_entity('form_instance', form['form_instance_id'], {'missing_required_count': missing}, 'form_instance_id')
def _assert_invariants(self):
entities = self._state.snapshot()
indexes: dict[str, dict[str, dict[str, ext_Any]]] = {}
for (entity_type, identity_field) in DATA_ENTITY_ID_FIELDS.items():
rows = entities.get(entity_type, [])
identities = [row.get(identity_field) for row in rows]
if None in identities or len(identities) != len(set(identities)):
raise ValueError(f'{entity_type} identities are not unique')
indexes[entity_type] = {row[identity_field]: row for row in rows}
projects = indexes['project']
users = indexes['project_user']
events = indexes['event']
instruments = indexes['instrument']
fields = indexes['instrument_field']
records = indexes['record']
record_events = indexes['record_event']
forms = indexes['form_instance']
values = indexes['field_value']
queries = indexes['data_query']
for (entity_type, rows) in entities.items():
if entity_type == 'project':
continue
for row in rows:
project_id = row.get('project_id')
if project_id and project_id not in projects:
raise ValueError(f'{entity_type} references a missing project')
for instrument in instruments.values():
for event_id in instrument.get('mapped_event_ids', []):
event = events.get(event_id)
if not event or event.get('project_id') != instrument.get('project_id'):
raise ValueError('instrument event mapping diverged')
for field in fields.values():
instrument = instruments.get(field.get('instrument_id'))
if not instrument or instrument.get('project_id') != field.get('project_id'):
raise ValueError('field instrument reference diverged')
for record_event in record_events.values():
record = records.get(record_event.get('record_id'))
event = events.get(record_event.get('event_id'))
if not record or not event or (not record.get('project_id') == event.get('project_id') == record_event.get('project_id')):
raise ValueError('record-event reference diverged')
for form in forms.values():
record = records.get(form.get('record_id'))
event = events.get(form.get('event_id'))
instrument = instruments.get(form.get('instrument_id'))
if not record or not event or (not instrument) or (not record.get('project_id') == event.get('project_id') == instrument.get('project_id') == form.get('project_id')):
raise ValueError('form reference diverged')
if event['event_id'] not in instrument.get('mapped_event_ids', []):
raise ValueError('form instrument is not mapped to event')
required = [field for field in fields.values() if field.get('instrument_id') == instrument['instrument_id'] and field.get('required') is True and (field.get('status') == 'active')]
missing = 0
for field in required:
match = next((value for value in values.values() if value.get('record_id') == record['record_id'] and value.get('event_id') == event['event_id'] and (value.get('instrument_id') == instrument['instrument_id']) and (value.get('field_id') == field['field_id'])), None)
if match is None or not str(match.get('value') or '').strip():
missing += 1
if int(form.get('missing_required_count') or 0) != missing:
raise ValueError('form missing-required counter diverged')
if form.get('completion_status') in {'complete', 'locked'} and missing:
raise ValueError('complete form has missing required values')
for value in values.values():
record = records.get(value.get('record_id'))
event = events.get(value.get('event_id'))
instrument = instruments.get(value.get('instrument_id'))
field = fields.get(value.get('field_id'))
if not record or not event or (not instrument) or (not field) or (not record.get('project_id') == event.get('project_id') == instrument.get('project_id') == field.get('project_id') == value.get('project_id')):
raise ValueError('field value reference diverged')
if field.get('instrument_id') != instrument.get('instrument_id'):
raise ValueError('field value instrument diverged')
for query in queries.values():
record = records.get(query.get('record_id'))
event = events.get(query.get('event_id'))
instrument = instruments.get(query.get('instrument_id'))
field = fields.get(query.get('field_id'))
opened_by = users.get(query.get('opened_by'))
assigned_to = users.get(query.get('assigned_to'))
if not record or not event or (not instrument) or (not field) or (not opened_by) or (not assigned_to):
raise ValueError('query reference is missing')
if not record.get('project_id') == event.get('project_id') == instrument.get('project_id') == field.get('project_id') == opened_by.get('project_id') == assigned_to.get('project_id') == query.get('project_id'):
raise ValueError('query project scope diverged')
if field.get('instrument_id') != instrument.get('instrument_id'):
raise ValueError('query field instrument diverged')
for project in projects.values():
project_id = project['project_id']
project_records = [row for row in records.values() if row.get('project_id') == project_id]
project_queries = [row for row in queries.values() if row.get('project_id') == project_id]
project_instruments = [row for row in instruments.values() if row.get('project_id') == project_id]
if int(project.get('record_count') or 0) != len(project_records):
raise ValueError('project record counter diverged')
if int(project.get('open_query_count') or 0) != sum((row.get('status') == 'open' for row in project_queries)):
raise ValueError('project query counter diverged')
if int(project.get('active_instrument_count') or 0) != sum((row.get('status') == 'active' for row in project_instruments)):
raise ValueError('project instrument counter diverged')
for record in records.values():
record_id = record['record_id']
if int(record.get('open_query_count') or 0) != sum((row.get('status') == 'open' for row in queries.values() if row.get('record_id') == record_id)):
raise ValueError('record query counter diverged')
if int(record.get('locked_event_count') or 0) != sum((row.get('locked') is True for row in record_events.values() if row.get('record_id') == record_id)):
raise ValueError('record lock counter diverged')
for record_event in record_events.values():
related = [row for row in forms.values() if row.get('record_id') == record_event['record_id'] and row.get('event_id') == record_event['event_id']]
complete = sum((row.get('completion_status') in {'complete', 'locked'} for row in related))
if int(record_event.get('form_complete_count') or 0) != complete:
raise ValueError('record-event complete counter diverged')
if int(record_event.get('form_incomplete_count') or 0) != len(related) - complete:
raise ValueError('record-event incomplete counter diverged')
if record_event.get('locked') and any((row.get('completion_status') != 'locked' for row in related)):
raise ValueError('locked record event has unlocked forms')
def _prepare(self, name, arguments):
prepared = ext_deepcopy(arguments)
if name == 'get_record_profile':
prepared.update({'include_field_values': True, 'include_queries': True, 'field_value_limit': 100})
elif name == 'resolve_data_query':
prepared['allow_open_resolution'] = False
elif name == 'mark_form_complete':
prepared['require_no_missing_fields'] = True
return prepared
def _precheck_lock(self, arguments):
if not arguments.get('locked'):
return None
record_event = self._state.get_entity('record_event', arguments.get('record_event_id'), 'record_event_id')
if not record_event:
return None
forms = [row for row in self._state.list_entities('form_instance') if row.get('record_id') == record_event.get('record_id') and row.get('event_id') == record_event.get('event_id')]
if any((row.get('completion_status') not in {'complete', 'locked'} for row in forms)):
return fn__error('INCOMPLETE_FORMS_CONFLICT', 'all related forms must be complete before locking')
return None
def private_raw_call(self, name, arguments):
"""Run an excluded raw tool transactionally for private rule witnesses."""
before = self.snapshot()
before_hash = self._business_hash()
try:
result = fn__normalize(self._logic.run_tool(name, self._state, ext_deepcopy(arguments)))
if result.get('status') != 'success':
self.restore(before)
else:
self._assert_invariants()
except Exception:
self.restore(before)
result = fn__error('ADAPTER_EXECUTION_FAILED', 'private witness failed without committing state')
self._record_adapter_event(name, str(arguments.get('actor_user_id') or arguments.get('requested_by') or arguments.get('approved_by') or 'private'), result, before_hash, self._business_hash(), channel='private_probe')
return ext_deepcopy(result)
def cost(self, before, action, result, after):
del action, result
return {'read_units': int(after.get('read_units') or 0) - int(before.get('read_units') or 0), 'write_attempts': int(after.get('write_attempts') or 0) - int(before.get('write_attempts') or 0)}
def _redcap_reusable_authority_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-redcap-structure-world/v7':
raise ValueError('unsupported REDCap reusable authority v7 snapshot')
value = ext_deepcopy(snapshot)
extra = value.pop('successor_v7', {})
if extra.get('provider_tools_sha256') != 'ce93692a925a9261962b6dc349b1446d425e93a516663ce04fb9b1330674c2bb':
raise ValueError('provider tool surface differs from REDCap v7')
if extra.get('cached_closeout_profile_cost') != 0:
raise ValueError('cached verification cost differs from REDCap v7')
if extra.get('registered_structure_delta_sha256') != 'c906f6670e3358b8460d789cc5d65113fcdba816ef2ee8d83c2ef6f871ec3c00':
raise ValueError('registered authority delta differs from REDCap v7')
value['schema'] = 'rescopebench-redcap-structure-world/v6'
self._redcap_actionable_authority_restore(value)
def _redcap_authority_evolution_snapshot(self):
value = self._redcap_evolution_snapshot()
value['authority_contract'] = 'redcap-authority-lifecycle-evolution-v2'
return value
def _redcap_authority_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('authority_contract', None) != 'redcap-authority-lifecycle-evolution-v2':
raise ValueError('REDCap authority contract differs')
self._redcap_evolution_restore(value)
if self.authority_revalidation:
raise ValueError('Unexpected legacy observation-order ledger in v2 snapshot')
def _redcap_reusable_authority_apply_structure_event(self):
result = self._redcap_authority_successor_apply_structure_event()
result = ext_deepcopy(result)
result['event_id'] = 'evt-redcap-authority-rotation-v7'
result['registered_delta_sha256'] = 'c906f6670e3358b8460d789cc5d65113fcdba816ef2ee8d83c2ef6f871ec3c00'
if result.get('applied'):
self._applied_boundary_events.add('evt-redcap-authority-rotation-v7')
self._applied_drifts = ['evt-redcap-authority-rotation-v7']
return result
def _redcap_evolution_dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
exact = name == 'get_record_profile' and isinstance(arguments, dict) and (set(arguments) == {'project_id', 'record_id'}) and all((isinstance(v, str) for v in arguments.values())) and (actor_user_id == 'session-redcap-closeout-4x9')
key = mod_json.dumps(arguments, sort_keys=True) if exact else None
issued = self._own_closeouts.get(key)
if issued is not None:
before = self.business_hash()
result = {'status': 'success', 'data': {'confirmation_only': True, 'authoritative_closeout': ext_deepcopy(issued)}, 'budget': self._budget_receipt()}
self._record_adapter_event(name, actor_user_id, result, before, before, cost=0)
result['receipt_index'] = len(self._events)
return result
result = self._redcap_reusable_authority_dispatch(name, arguments, actor_user_id)
if result.get('status') == 'success':
target = self._target_for_arguments(name, arguments)
if target is not None:
key = mod_json.dumps({k: target[k] for k in ('project_id', 'record_id')}, sort_keys=True)
self._own_closeouts.pop(key, None)
receipt = result.get('data', {}).get('authoritative_closeout')
if receipt is not None and actor_user_id == 'session-redcap-closeout-4x9':
self._own_closeouts[key] = ext_deepcopy(receipt)
return result
def _redcap_authority_successor_init(self, source_root=CASE_DIR / 'raw'):
self._redcap_structure_successor_init(source_root=source_root)
for (atom_id, new_user_id) in DATA_SYNTHETIC_ASSIGNEES.items():
if self._state.get_entity('project_user', new_user_id, 'user_id') is not None:
continue
old = self._state.get_entity('project_user', DATA_PRE_STRUCTURE_AUTHORITY[atom_id], 'user_id')
if old is None:
raise AssertionError(f'missing predecessor assignee for {atom_id}')
replacement = ext_deepcopy(old)
replacement.update({'user_id': new_user_id, 'username': new_user_id.replace('usr-', 'staff.'), 'full_name': f'Project staff {new_user_id[-4:].upper()}', 'email': f'{new_user_id}@example.invalid', 'status': 'active'})
self._state.add_entity('project_user', replacement, 'user_id')
self.authority_revalidation: dict[str, str] = {}
self._entry_entities = self._state.snapshot()
self._assert_invariants()
def _redcap_actionable_authority_read_cost(self, name, result):
if name == 'get_record_profile' and result.get('status') == 'success' and (self._active_target_from_profile(result) is not None):
return 2
return self._redcap_authority_successor_read_cost(name, result)
def _redcap_actionable_authority_compact_profile(self, target, result):
data = result['data']
query = next((row for row in data['queries'] if row['query_id'] == target['query_id']))
field = next((row for row in data['field_values'] if row['field_id'] == target['primary_field_id'] and row['instrument_id'] == target['primary_instrument_id']))
record_event = next((row for row in data['record_events'] if row['record_event_id'] == target['record_event_id']))
form_ids = {target['primary_form_id'], target['companion_form_id']}
forms = [row for row in data['forms'] if row['form_instance_id'] in form_ids]
compact = {'request_ref': target['target_id'], 'workflow_class': target['workflow_class'], 'project_id': target['project_id'], 'record': ext_deepcopy(data['record']), 'record_event': ext_deepcopy(record_event), 'forms': ext_deepcopy(forms), 'target_field': ext_deepcopy(field), 'query': ext_deepcopy(query), 'workflow_authority': self._workflow_authority(target, query)}
value = ext_deepcopy(result)
value['data'] = compact
return value
def _redcap_actionable_authority_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-redcap-structure-world/v6':
raise ValueError('unsupported REDCap actionable authority v6 snapshot')
value = ext_deepcopy(snapshot)
extra = value.pop('successor_v6', {})
if extra.get('provider_tools_sha256') != 'cea2749468a89c15de9ca78832ea2f7dd0540faa66b5df73eccbe544d7edf29b':
raise ValueError('provider tool surface differs from REDCap v6')
if extra.get('compact_profile_cost') != 2:
raise ValueError('compact profile cost differs from REDCap v6')
value['schema'] = 'rescopebench-redcap-structure-world/v5'
self._redcap_authority_successor_restore(value)
def _redcap_evolution_snapshot(self):
value = self._redcap_reusable_authority_snapshot()
value['evolution_contract'] = {'case_version': 'redcap-authority-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)}
value['own_closeout_receipts'] = ext_deepcopy(self._own_closeouts)
return value
def _redcap_evolution_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('evolution_contract', None) != {'case_version': 'redcap-authority-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}:
raise ValueError('REDCap evolution contract differs')
receipts = value.pop('own_closeout_receipts')
self._redcap_reusable_authority_restore(value)
self._own_closeouts = ext_deepcopy(receipts)
def _redcap_authority_successor_apply_structure_event(self):
before = self.business_hash()
if 'evt-redcap-authority-rotation-v5' in self._applied_boundary_events:
return {'event_id': 'evt-redcap-authority-rotation-v5', 'application_count': self._drift_application_count, 'applied': False, 'idempotent_noop': True, 'before_world_sha256': before, 'after_world_sha256': before, 'registered_delta_sha256': '33dc4558c52ad984b3a2f0cc5cb6ffb6252a95e6262bf035a93a901a30f4176f'}
for atom_id in DATA_CHANGED_STRUCTURE_ATOMS:
old = DATA_PRE_STRUCTURE_AUTHORITY[atom_id]
new = DATA_POST_STRUCTURE_AUTHORITY[atom_id]
self._assignee_by_structure[atom_id] = new
self._state.update_entity('project_user', old, {'status': 'inactive', 'updated_at': '2026-05-18T10:30:00Z'}, 'user_id')
self._state.update_entity('project_user', new, {'status': 'active', 'updated_at': '2026-05-18T10:30:00Z'}, 'user_id')
self.authority_revalidation[atom_id] = 'awaiting_exact_stale'
for target in self._targets:
atom_id = target['structure_atom']
if atom_id not in DATA_CHANGED_STRUCTURE_ATOMS:
continue
new = DATA_POST_STRUCTURE_AUTHORITY[atom_id]
self._state.update_entity('data_query', target['query_id'], {'assigned_to': new, 'updated_at': '2026-05-18T10:30:00Z'}, 'query_id')
target.update({'current_assignee': new, 'field_actor_user_id': new, 'query_answer_actor_user_id': new, 'lock_actor_user_id': new})
self._applied_boundary_events.add('evt-redcap-authority-rotation-v5')
self._applied_drifts = ['evt-redcap-authority-rotation-v5']
self._drift_application_count = 1
self._assert_invariants()
after = self.business_hash()
return {'event_id': 'evt-redcap-authority-rotation-v5', 'application_count': self._drift_application_count, 'applied': True, 'idempotent_noop': False, 'before_world_sha256': before, 'after_world_sha256': after, 'registered_delta_sha256': '33dc4558c52ad984b3a2f0cc5cb6ffb6252a95e6262bf035a93a901a30f4176f'}
def _redcap_reusable_authority_dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
result = self._redcap_actionable_authority_dispatch(name, arguments, actor_user_id)
if name == 'set_record_event_lock' and result.get('status') == 'success' and (arguments.get('locked') is True):
target = self._target_for_arguments(name, arguments)
if target is not None and self._target_complete(target):
value = ext_deepcopy(result)
value.setdefault('data', {})['authoritative_closeout'] = {'request_ref': target['target_id'], 'complete': True, 'field_verified': True, 'query_resolved': True, 'forms_complete': True, 'record_event_locked': True, 'additional_readback_required': False, 'reusable_evidence': {'persistent_until_contradicted': {'project_binding_key': target['project_title'], 'project_title': target['project_title'], 'project_id': target['project_id'], 'instrument_id': target['primary_instrument_id'], 'field_id': target['primary_field_id'], 'field_actor_user_id': target['field_actor_user_id'], 'form_actor_user_id': target['field_actor_user_id'], 'query_answer_actor_user_id': target['query_answer_actor_user_id'], 'query_resolver_user_id': target['query_resolver_user_id'], 'lock_actor_user_id': target['lock_actor_user_id']}, 'reusable_workflow_procedure': fn__workflow_recipe_from_profile(target), 'task_scoped': {'request_ref': target['target_id'], 'subject_label': target['subject_label'], 'record_id': target['record_id'], 'query_id': target['query_id'], 'form_instance_ids': sorted([target['primary_form_id'], target['companion_form_id']]), 'record_event_id': target['record_event_id']}}}
return value
return result
def _redcap_structure_successor_init(self, source_root=CASE_DIR / 'raw'):
self._redcap_structure_successor_init_2(source_root=source_root)
old = self._state.get_entity('project_user', DATA_PRE_STRUCTURE_AUTHORITY_2['S02'], 'user_id')
if old is None:
raise AssertionError('S02 predecessor assignee is missing')
if self._state.get_entity('project_user', 'usr-b018b8d3dcf7d6', 'user_id') is None:
replacement = ext_deepcopy(old)
replacement.update({'user_id': 'usr-b018b8d3dcf7d6', 'username': 'usr-b018b8d3dcf7d6'.replace('usr-', 'staff.'), 'full_name': f"Project staff {'usr-b018b8d3dcf7d6'[-4:].upper()}", 'email': f"{'usr-b018b8d3dcf7d6'}@example.invalid"})
self._state.add_entity('project_user', replacement, 'user_id')
self._entry_entities = self._state.snapshot()
self._assert_invariants()
def _redcap_authority_successor_read_cost(self, name, result):
cost = self._redcap_query_lock_adapter_read_cost(name, result)
if name == 'list_data_queries' and result.get('status') == 'success':
return max(2, cost)
return cost
def _redcap_authority_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-redcap-structure-world/v5':
raise ValueError('unsupported REDCap authority v5 snapshot')
value = ext_deepcopy(snapshot)
extra = value.pop('successor_v5', {})
if extra.get('provider_tools_sha256') != 'ccda3f97d34b50376e9bbed96390d1a430d9980a47bb8bccfe4cc9ca84c6fb5b':
raise ValueError('provider tool surface differs from REDCap v5')
if extra.get('synthetic_assignees') != DATA_SYNTHETIC_ASSIGNEES:
raise ValueError('synthetic authority identities differ from REDCap v5')
value['schema'] = 'rescopebench-redcap-structure-world/v4'
self._redcap_structure_successor_restore(value)
self.authority_revalidation = ext_deepcopy(extra.get('authority_revalidation', {}))
def _redcap_reusable_authority_snapshot(self):
value = self._redcap_actionable_authority_snapshot()
value['schema'] = 'rescopebench-redcap-structure-world/v7'
value['successor_v7'] = {'provider_tools_sha256': 'ce93692a925a9261962b6dc349b1446d425e93a516663ce04fb9b1330674c2bb', 'cached_closeout_profile_cost': 0, 'registered_structure_delta_sha256': 'c906f6670e3358b8460d789cc5d65113fcdba816ef2ee8d83c2ef6f871ec3c00'}
return value
def _redcap_actionable_authority_dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
result = self._redcap_authority_successor_dispatch(name, arguments, actor_user_id)
if result.get('status') != 'success':
return result
if name == 'get_record_profile':
target = self._active_target_from_profile(result)
if target is not None:
return self._compact_profile(target, result)
elif name == 'list_data_queries':
target = self._target_for_read(arguments)
if target is not None:
value = ext_deepcopy(result)
for query in value.get('data', {}).get('queries', []):
if query.get('query_id') != target['query_id']:
continue
query['project_id'] = target['project_id']
query['workflow_class'] = target['workflow_class']
query['workflow_authority'] = self._workflow_authority(target, query)
return value
return result
def _redcap_structure_successor_init_2(self, source_root=CASE_DIR / 'raw'):
self._persistent_redcap_adapter_init(source_root=source_root)
self._drift_application_count = 0
def _redcap_query_lock_adapter_read_cost(self, name, result):
if result.get('status') != 'success':
return 1
data = result.get('data') or {}
if name in DATA_LIST_TOOLS:
return max(1, int(data.get('total_count') or 0))
if name == 'get_record_profile':
return 1 + len(data.get('record_events') or []) + len(data.get('forms') or []) + len(data.get('field_values') or []) + len(data.get('queries') or [])
if name == 'inspect_instrument_dictionary':
return max(1, 1 + len(data.get('mapped_events') or []) + len(data.get('fields') or []))
return 1
def _redcap_structure_successor_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-redcap-structure-world/v4':
raise ValueError('unsupported REDCap frontier snapshot')
World._persistent_redcap_adapter_restore(self, snapshot['base'])
successor = snapshot['successor']
if successor.get('provider_tools_sha256') != '5b8d114f107021ca6fe690b78ab91fb09fbe5b9f873e50f8fce0603ac143fe8f':
raise ValueError('provider tool surface differs from the frozen successor')
if successor.get('s02_new_assignee') != 'usr-b018b8d3dcf7d6':
raise ValueError('S02 alternate assignee differs from the frozen successor')
self._drift_application_count = int(successor.get('drift_application_count') or 0)
def _redcap_actionable_authority_snapshot(self):
value = self._redcap_authority_successor_snapshot()
value['schema'] = 'rescopebench-redcap-structure-world/v6'
value['successor_v6'] = {'provider_tools_sha256': 'cea2749468a89c15de9ca78832ea2f7dd0540faa66b5df73eccbe544d7edf29b', 'compact_profile_cost': 2}
return value
def _redcap_authority_successor_dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
target = self._target_for_arguments(name, arguments)
if target is not None:
first = self._first_incomplete_slot()
if first is not None and int(target['slot']) > first:
return self._charged_guard_error(name, 'PRIORITY_PACKET_PENDING', 'an earlier listed REDCap packet must be completed first')
atom_id = target['structure_atom']
if atom_id in DATA_CHANGED_STRUCTURE_ATOMS and arguments.get('actor_user_id') == DATA_POST_STRUCTURE_AUTHORITY[atom_id] and (self.authority_revalidation.get(atom_id) in {'awaiting_current_query', 'awaiting_active_staff'}):
return self._charged_guard_error(name, 'AUTHORITY_REVALIDATION_REQUIRED', 'current query and active staff evidence are both required after a stale authority rejection')
result = self._redcap_structure_successor_dispatch(name, arguments, actor_user_id)
if name == 'list_data_queries' and result.get('status') == 'success':
read_target = self._target_for_read(arguments)
if read_target is not None:
atom_id = read_target['structure_atom']
state = self.authority_revalidation.get(atom_id)
queries = result.get('data', {}).get('queries', [])
if state == 'awaiting_current_query':
self.authority_revalidation[atom_id] = 'awaiting_active_staff'
if name == 'list_project_users' and result.get('status') == 'success':
project_id = arguments.get('project_id')
atom_id = next((atom for atom in DATA_CHANGED_STRUCTURE_ATOMS if DATA_GROUP_BY_ATOM[atom]['project_id'] == project_id), None)
if atom_id is not None:
state = self.authority_revalidation.get(atom_id)
data = result.get('data', {})
if state == 'awaiting_current_query' and self._legacy_staff_projection:
old = self._state.get_entity('project_user', DATA_PRE_STRUCTURE_AUTHORITY[atom_id], 'user_id')
if old is not None:
visible = ext_deepcopy(old)
visible['status'] = 'active'
data['users'] = [visible]
data['user_ids'] = [visible['user_id']]
data['total_count'] = 1
elif state == 'awaiting_active_staff':
users = data.get('users', [])
if any((row.get('user_id') == DATA_POST_STRUCTURE_AUTHORITY[atom_id] and row.get('status') == 'active' for row in users)):
self.authority_revalidation[atom_id] = 'ready_current'
if target is not None and target['structure_atom'] in DATA_CHANGED_STRUCTURE_ATOMS:
atom_id = target['structure_atom']
actor = arguments.get('actor_user_id')
code = result.get('data', {}).get('error_code')
if self.authority_revalidation.get(atom_id) == 'awaiting_exact_stale' and actor == DATA_PRE_STRUCTURE_AUTHORITY[atom_id] and (code in {'USER_INACTIVE', 'PERMISSION_DENIED'}):
self.authority_revalidation[atom_id] = 'awaiting_current_query'
elif result.get('status') == 'success' and actor == DATA_POST_STRUCTURE_AUTHORITY[atom_id]:
self.authority_revalidation[atom_id] = 'validated_current'
return result
def _persistent_redcap_adapter_init(self, source_root=None):
self._redcap_query_lock_adapter_init(source_root or CASE_DIR / 'raw')
self._state.restore(fn__base_entities())
self._task_id = None
self._targets = []
self._entry_entities = self._state.snapshot()
self._events = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._applied_drifts = []
self._activated_tasks: list[str] = []
self._applied_boundary_events: set[str] = set()
self._assignee_by_structure = {group['atom_id']: group['editor_old'] for group in DATA_STRUCTURE_GROUPS if group['mode'] != 'manager'}
self._assert_invariants()
def _persistent_redcap_adapter_restore(self, snapshot):
if snapshot.get('schema') != 'rescopebench-redcap-persistent-stream-snapshot/v1':
raise ValueError('unsupported persistent REDCap stream snapshot schema')
self._task_id = snapshot.get('task_id')
self._targets = ext_deepcopy(snapshot.get('targets') or [])
self._entry_entities = ext_deepcopy(snapshot.get('entry_entities') or {})
self._state.restore(snapshot.get('entities') or {})
self._events = ext_deepcopy(snapshot.get('events') or [])
self._calls = int(snapshot.get('calls') or 0)
self._read_units = int(snapshot.get('read_units') or 0)
self._write_attempts = int(snapshot.get('write_attempts') or 0)
self._applied_drifts = list(snapshot.get('applied_drifts') or [])
self._activated_tasks = list(snapshot.get('activated_tasks') or [])
self._applied_boundary_events = set(snapshot.get('applied_boundary_events') or [])
self._assignee_by_structure = ext_deepcopy(snapshot.get('assignee_by_structure') or {})
self._assert_invariants()
def _redcap_authority_successor_snapshot(self):
value = self._redcap_structure_successor_snapshot()
value['schema'] = 'rescopebench-redcap-structure-world/v5'
value['successor_v5'] = {'authority_revalidation': ext_deepcopy(self.authority_revalidation), 'provider_tools_sha256': 'ccda3f97d34b50376e9bbed96390d1a430d9980a47bb8bccfe4cc9ca84c6fb5b', 'synthetic_assignees': ext_deepcopy(DATA_SYNTHETIC_ASSIGNEES)}
return value
def _redcap_structure_successor_dispatch(self, name, arguments, actor_user_id='session-redcap-closeout-4x9'):
if self._task_id is None:
return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
tool = DATA_TOOL_BY_NAME.get(name)
if tool is None:
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
if actor_user_id != 'session-redcap-closeout-4x9':
return fn__error('ACTOR_NOT_AUTHORIZED', 'caller is not the closeout coordinator')
try:
mod_jsonschema.validate(arguments, tool['input_schema'])
except mod_jsonschema.ValidationError:
return fn__error('INVALID_ARGUMENTS', 'arguments do not match the public tool schema')
if self._calls >= 48:
result = fn__error('CALL_BUDGET_EXHAUSTED', 'task call safeguard is exhausted')
result['budget'] = self._budget_receipt()
return result
is_write = name in DATA_WRITE_TOOLS
if is_write and self._write_attempts >= 17:
result = fn__error('WRITE_BUDGET_EXHAUSTED', 'task mutation-attempt allowance is exhausted')
result['budget'] = self._budget_receipt()
return result
if not is_write and self._read_units >= 6:
result = fn__error('READ_BUDGET_EXHAUSTED', 'task returned-work allowance is exhausted')
result['budget'] = self._budget_receipt()
return result
before = self.snapshot()
before_calls = self._calls
before_reads = self._read_units
before_writes = self._write_attempts
before_hash = self.business_hash()
try:
precheck = self._precheck_lock(arguments) if name == 'set_record_event_lock' else None
result = precheck if precheck is not None else fn__normalize(self._logic.run_tool(name, self._state, self._prepare(name, arguments)))
if result.get('status') == 'success':
if name == 'update_record_field':
self._repair_required_counts(arguments['record_id'], arguments['event_id'], arguments['instrument_id'])
self._assert_invariants()
except Exception:
result = fn__error('ADAPTER_EXECUTION_FAILED', 'operation failed without committing state')
cost = 1 if is_write else self._read_cost(name, result)
if not is_write and before_reads + cost > 6:
self.restore(before)
self._calls = before_calls + 1
self._read_units = 6
exhausted = fn__error('READ_BUDGET_EXHAUSTED', 'the remaining returned-work allowance cannot cover this response')
after_hash = self.business_hash()
self._record_adapter_event(name, actor_user_id, exhausted, before_hash, after_hash, cost=6 - before_reads)
exhausted['budget'] = self._budget_receipt()
exhausted['receipt_index'] = len(self._events)
return exhausted
if result.get('status') != 'success':
self.restore(before)
self._calls = before_calls + 1
self._read_units = before_reads + (0 if is_write else cost)
self._write_attempts = before_writes + (1 if is_write else 0)
after_hash = self.business_hash()
self._record_adapter_event(name, actor_user_id, result, before_hash, after_hash, cost=cost)
result['budget'] = self._budget_receipt()
result['receipt_index'] = len(self._events)
return ext_deepcopy(result)
def _redcap_query_lock_adapter_init(self, source_root=CASE_DIR / 'raw'):
self._logic = fn__load_raw_logic(str(ext_Path(source_root).resolve()))
self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS})
self._task_id: str | None = None
self._targets: list[dict[str, ext_Any]] = []
self._entry_entities: dict[str, list[dict[str, ext_Any]]] = {}
self._events: list[dict[str, ext_Any]] = []
self._calls = 0
self._read_units = 0
self._write_attempts = 0
self._applied_drifts: list[str] = []
def _redcap_structure_successor_snapshot(self):
return {'schema': 'rescopebench-redcap-structure-world/v4', 'base': World._persistent_redcap_adapter_snapshot(self), 'successor': {'drift_application_count': self._drift_application_count, 'provider_tools_sha256': '5b8d114f107021ca6fe690b78ab91fb09fbe5b9f873e50f8fce0603ac143fe8f', 's02_new_assignee': 'usr-b018b8d3dcf7d6'}}
def _persistent_redcap_adapter_snapshot(self):
return {'schema': 'rescopebench-redcap-persistent-stream-snapshot/v1', 'task_id': self._task_id, 'targets': ext_deepcopy(self._targets), 'entry_entities': ext_deepcopy(self._entry_entities), 'entities': self._state.snapshot(), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'read_units': self._read_units, 'write_attempts': self._write_attempts, 'applied_drifts': list(self._applied_drifts), 'activated_tasks': list(self._activated_tasks), 'applied_boundary_events': sorted(self._applied_boundary_events), 'assignee_by_structure': ext_deepcopy(self._assignee_by_structure)}
class MemoryState:
def __init__(self, entities):
self._entities = ext_deepcopy(entities)
def get_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
return next((ext_deepcopy(row) for row in self._entities.get(entity_type, []) if row.get(field) == entity_id), None)
def list_entities(self, entity_type):
return ext_deepcopy(self._entities.get(entity_type, []))
def query_entities(self, entity_type, predicate):
return [ext_deepcopy(row) for row in self._entities.get(entity_type, []) if predicate(row)]
def add_entity(self, entity_type, record, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
identity = record.get(field)
if identity is None or self.get_entity(entity_type, identity, field) is not None:
raise ValueError(f'duplicate or missing identity for {entity_type}')
self._entities.setdefault(entity_type, []).append(ext_deepcopy(record))
return ext_deepcopy(record)
def update_entity(self, entity_type, entity_id, patch, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
for row in self._entities.get(entity_type, []):
if row.get(field) == entity_id:
row.update(ext_deepcopy(patch))
return ext_deepcopy(row)
return None
def delete_entity(self, entity_type, entity_id, id_field='id'):
field = DATA_ENTITY_ID_FIELDS.get(entity_type, id_field) if id_field == 'id' else id_field
rows = self._entities.get(entity_type, [])
kept = [row for row in rows if row.get(field) != entity_id]
self._entities[entity_type] = kept
return len(rows) != len(kept)
def snapshot(self):
return ext_deepcopy(self._entities)
def restore(self, entities):
self._entities = ext_deepcopy(entities)