Download cases/backup_recovery/runtime.py from JoeYing/ReScopeBench: direct link, hf CLI and curl.
- Browser
- Download file 73.2 kB
-
https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/backup_recovery/runtime.py
- Command line
-
hf download hf://datasets/JoeYing/ReScopeBench/cases/backup_recovery/runtime.py
-
curl -L -o runtime.py https://huggingface.co/datasets/JoeYing/ReScopeBench/resolve/main/cases/backup_recovery/runtime.py
73.2 kB
| """Released environment operations and snapshot validation.""" | |
| from __future__ import annotations | |
| from contextlib import contextmanager | |
| from copy import deepcopy as ext_deepcopy | |
| from functools import lru_cache | |
| from types import SimpleNamespace | |
| 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_POST_POLICY_CELLS, DATA_POLICY_CELLS, DATA_WRITE_TOOLS, DATA_PRE_RULES, DATA_TOOLS_2, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_CHANGED_RULE_IDS, DATA_ENTITY_ID_FIELDS, DATA_TOOL_BY_NAME, DATA_STRUCTURE_SCHEDULE, DATA_RULE_SCHEDULE, DATA_STRUCTURE_BY_ID, DATA_PROFILES, DATA_DRIFTED_POLICY_CELLS, DATA_POST_RULES, DATA_LIST_KEYS, DATA_FIXED_COSTS, DATA_RULE_SCHEDULE_2, DATA_STRUCTURE_SCHEDULE_2, DATA_COMPLETION, DATA_RULE_SCHEDULE_3, DATA_STRUCTURE_SCHEDULE_3, DATA_STRUCTURE_CLUSTERS, DATA_RULE_SCHEDULE_4, DATA_STRUCTURE_SCHEDULE_4 | |
| _SCHEDULE_STATE = SimpleNamespace(RULE_SCHEDULE=DATA_RULE_SCHEDULE_4, STRUCTURE_SCHEDULE=DATA_STRUCTURE_SCHEDULE_4) | |
| def fn_digest(value): | |
| return mod_hashlib.sha256(fn__canonical_2(value).encode('utf-8')).hexdigest() | |
| def fn__error(code, message): | |
| return {'status': 'error', 'data': {'error_code': code}, 'message': message} | |
| def fn__canonical(value): | |
| return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':')) | |
| def fn__canonical_hash(value): | |
| payload = mod_json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False) | |
| return mod_hashlib.sha256(payload.encode('utf-8')).hexdigest() | |
| def fn__task_entities(task_id): | |
| entities: dict[str, list[dict[str, ext_Any]]] = {name: [] for name in DATA_ENTITY_ID_FIELDS} | |
| for target in fn_stream_targets(task_id): | |
| entities['backup_policy'].append({'policy_id': target['policy_id'], 'site_id': target['site_id'], 'name': target['policy_name'], 'policy_type': 'full_incremental', 'backup_method': 'agent', 'retention': {'daily': 7, 'weekly': 2, 'monthly': 1, 'legal_hold_days': 0}, 'encryption_required': True, 'immutable_required': True, 'replication_required': False, 'schedule_timezone': 'UTC', 'service_tier': target['service_tier'], 'data_class': target['data_class'], 'repository_pool': target['repository_pool'], 'status': 'draft', 'created_by_user_id': 'user-stream-backup-admin', 'created_at': '2026-05-16T12:00:00Z', 'updated_at': '2026-05-16T12:00:00Z'}) | |
| entities['workload_asset'].append({'asset_id': target['asset_id'], 'asset_name': target['workload_name'], 'asset_type': 'database', 'classification': target['data_class'], 'environment': 'production', 'owner_team': 'Data Protection', 'platform': 'postgresql', 'site_id': target['site_id'], 'size_gb': 128, 'status': 'paused', 'tags': [target['target_id'].lower()], 'created_at': '2026-05-16T12:00:00Z', 'updated_at': '2026-05-16T12:00:00Z'}) | |
| return entities | |
| def fn_stream_targets(task_id): | |
| if task_id not in DATA_TASK_IDS: | |
| raise ValueError(f'unknown stream task: {task_id}') | |
| rules = fn__rule_by_id() | |
| rows = [] | |
| for (slot, (structure_id, rule_id)) in enumerate(zip(DATA_STRUCTURE_SCHEDULE[task_id], DATA_RULE_SCHEDULE[task_id]), 1): | |
| cluster = DATA_STRUCTURE_BY_ID[structure_id] | |
| cell = rules[rule_id] | |
| token = fn__opaque('obj', task_id, slot, length=10) | |
| rows.append({'target_id': fn__opaque('PR', task_id, slot, length=10).upper(), 'task_id': task_id, 'slot': slot, 'structure_atom': structure_id, 'rule_atom': rule_id, 'site_id': cluster['site_id'], 'site_name': cluster['site_name'], 'repository_pool': cluster['repository_pool'], 'candidate_repository_ids': [fn__repository_id(structure_id, profile) for profile in DATA_PROFILES], 'policy_id': f'policy-{token}', 'policy_name': f'Protection Policy {token.upper()}', 'asset_id': f'asset-{token}', 'workload_name': f'Workload {token.upper()}', 'service_tier': cell['service_tier'], 'data_class': cell['data_class'], 'schedule_name': f'Window {token.upper()}', 'start_time_local': f'{(slot * 4 + int(task_id[1:])) % 24:02d}:00'}) | |
| return tuple(rows) | |
| def fn_public_task(task_id): | |
| task = fn_public_task_2(task_id) | |
| task['requests'] = [{key: row[key] for key in ('target_id', 'site_name', 'policy_id', 'policy_name', 'asset_id', 'workload_name', 'service_tier', 'data_class', 'schedule_name', 'start_time_local')} for row in fn_stream_targets(task_id)] | |
| task['targets'] = [row['target_id'] for row in task['requests']] | |
| task['task_id'] = 'EV-' + fn_digest(['backup-lifecycle-evolution-v1', task['requests']])[:16].upper() | |
| task['completion'].pop('verification_required') | |
| task['completion']['evidence'] = {'mode': 'narrow_status', 'source': 'list_policy_assignments with exact site_id, policy_id, asset_id, limit=1 and offset=0 after your own successful assignment in this episode', 'proves': "the submitted assignment's current active protection state"} | |
| task['budget']['mechanism'] = task['budget']['mechanism'].replace('filtered assignment verification costs 6;', 'assignment reads cost 6 except exact current-episode own-assignment confirmation (site_id, policy_id, asset_id, limit=1, offset=0), which costs 0 work units and no call/write quota;') | |
| return task | |
| def fn__canonical_2(value): | |
| return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':')) | |
| def fn__rule_by_id(*, drifted=False): | |
| source = DATA_DRIFTED_POLICY_CELLS if drifted else DATA_POLICY_CELLS | |
| return {row['rule_atom']: ext_deepcopy(row) for row in source.values()} | |
| def fn__opaque(prefix, *parts, length=12): | |
| payload = '|'.join((str(part) for part in parts)) | |
| digest = mod_hashlib.sha256(f'backup-recovery-stream|{payload}'.encode('utf-8')).hexdigest() | |
| return f'{prefix}-{digest[:length]}' | |
| def fn__repository_id(structure_id, profile): | |
| return fn__opaque('repo', structure_id, profile) | |
| def fn_public_task_2(task_id): | |
| task = ext_deepcopy(fn_public_task_3(task_id)) | |
| requests = [{key: target[key] for key in ('target_id', 'site_name', 'policy_id', 'policy_name', 'asset_id', 'workload_name', 'service_tier', 'data_class', 'schedule_name', 'start_time_local')} for target in fn_stream_targets_2(task_id)] | |
| with fn__schedule(): | |
| task['task_id'] = fn_opaque_event_id(task_id) | |
| task['schema'] = 'rescopebench-public-task/v6' | |
| task['requests'] = requests | |
| task['targets'] = [row['target_id'] for row in requests] | |
| task['allowed_tools'] = [row['function']['name'] for row in fn_provider_tools()] | |
| task['budget']['allowance'] = 126 | |
| task['budget']['mechanism'] = 'Site-directory, exact workload, or exact policy reads cost 32 units; exact policy evidence costs 20 units, while the repeated exact refresh after observing the global current routing epoch costs 14; one recovery dashboard costs 7 per episode and establishes that global epoch for all sites; repository listings cost 4 plus 2 per returned row; filtered assignment verification costs 6; schedule, activation, and assignment attempts cost 6, 6, and 8 units, including rejected writes.' | |
| return task | |
| def fn_public_task_3(task_id): | |
| task = ext_deepcopy(fn_public_task_4(task_id)) | |
| task['schema'] = 'rescopebench-public-task/v5' | |
| task['budget']['mechanism'] = 'Site-directory, exact workload, or exact policy reads cost 32 units; exact policy evidence costs 20 units, or 14 for a condition-specific refresh after the current routing epoch has already been established through ordinary recovery; a recovery dashboard costs 7; repository listings cost 4 plus 2 per returned row; filtered assignment verification costs 6; schedule, activation, and assignment attempts cost 6, 6, and 8 units, including rejected writes.' | |
| return task | |
| def fn_stream_targets_2(task_id): | |
| with fn__schedule(): | |
| return tuple(ext_deepcopy(fn_stream_targets_3(task_id))) | |
| def fn__schedule(): | |
| old_rules = _SCHEDULE_STATE.RULE_SCHEDULE | |
| old_structures = _SCHEDULE_STATE.STRUCTURE_SCHEDULE | |
| _SCHEDULE_STATE.RULE_SCHEDULE = DATA_RULE_SCHEDULE_2 | |
| _SCHEDULE_STATE.STRUCTURE_SCHEDULE = DATA_STRUCTURE_SCHEDULE_2 | |
| try: | |
| yield | |
| finally: | |
| _SCHEDULE_STATE.RULE_SCHEDULE = old_rules | |
| _SCHEDULE_STATE.STRUCTURE_SCHEDULE = old_structures | |
| def fn_opaque_event_id(task_id): | |
| return fn__opaque('EV', task_id, [row['target_id'] for row in fn_stream_targets_4(task_id)]).upper() | |
| def fn_provider_tools(): | |
| tools = ext_deepcopy(fn_provider_tools_2()) | |
| by_name = {row['function']['name']: row['function'] for row in tools} | |
| by_name['get_site_recovery_dashboard']['description'] = 'Return bounded site recovery status. The returned routing_policy_epoch is the current routing epoch shared by all protection sites in this episode, so one successful dashboard observation is sufficient; it does not reveal a route, repository profile, or repository selection.' | |
| by_name['search_protection_policy_evidence']['description'] = 'Resolve route, repository profile, rule identity, and effective epoch for one exact service-tier and data-class condition. After a newer global routing epoch has been observed, the first exact lookup can return the retained stale snapshot; repeat the same exact lookup once to refresh current evidence.' | |
| return tools | |
| def fn_public_task_4(task_id): | |
| requests = [{key: target[key] for key in ('target_id', 'site_name', 'policy_id', 'policy_name', 'asset_id', 'workload_name', 'service_tier', 'data_class', 'schedule_name', 'start_time_local')} for target in fn_stream_targets_5(task_id)] | |
| with fn__schedule_2(): | |
| event_id = fn_opaque_event_id(task_id) | |
| return {'schema': 'rescopebench-public-task/v4', 'case_id': 'backup_recovery', 'task_id': event_id, 'objective': 'Create one complete active protection assignment for each request. The supplied policy_id and asset_id are authoritative handles for that request; expensive policy or workload pre-reads are optional unless a tool reports a binding mismatch. Create the named daily schedule, activate the policy, and select a site-compatible repository under current routing. Successful write responses establish those mutation results; close verification with one assignment read filtered to the policy and asset. Process requests in listed priority order; a later request cannot be mutated until every earlier request is complete and verified.', 'requests': requests, 'targets': [row['target_id'] for row in requests], 'allowed_tools': [row['function']['name'] for row in fn_provider_tools_3()], 'completion': ext_deepcopy(DATA_COMPLETION), 'budget': {'kind': 'backup_work_quota', 'allowance': 126, 'call_attempt_limit': 40, 'write_attempt_limit': 20, 'mechanism': 'Site-directory, exact workload, or exact policy reads cost 42 units; exact policy evidence costs 20; a recovery dashboard costs 7; repository listings cost 4 plus 2 per returned row; filtered assignment verification costs 6; schedule, activation, and assignment attempts cost 6, 6, and 8 units, including rejected writes.'}} | |
| def fn_stream_targets_3(task_id): | |
| targets = list(fn_stream_targets_4(task_id)) | |
| if task_id in {'T08', 'T09'}: | |
| targets = [targets[1], targets[3], targets[0], targets[2]] | |
| return tuple(ext_deepcopy(targets)) | |
| def fn_stream_targets_4(task_id): | |
| if task_id not in DATA_TASK_IDS: | |
| raise ValueError(f'unknown stream task: {task_id}') | |
| rules = fn__rule_by_id() | |
| rows = [] | |
| for (slot, (structure_id, rule_id)) in enumerate(zip(_SCHEDULE_STATE.STRUCTURE_SCHEDULE[task_id], _SCHEDULE_STATE.RULE_SCHEDULE[task_id]), 1): | |
| cluster = DATA_STRUCTURE_BY_ID[structure_id] | |
| cell = rules[rule_id] | |
| token = fn__opaque('obj', task_id, slot, length=10) | |
| rows.append({'target_id': fn__opaque('PR', task_id, slot, length=10).upper(), 'task_id': task_id, 'slot': slot, 'structure_atom': structure_id, 'rule_atom': rule_id, 'site_id': cluster['site_id'], 'site_name': cluster['site_name'], 'repository_pool': cluster['repository_pool'], 'candidate_repository_ids': [fn__repository_id(structure_id, profile) for profile in DATA_PROFILES], 'policy_id': f'policy-{token}', 'policy_name': f'Protection Policy {token.upper()}', 'asset_id': f'asset-{token}', 'workload_name': f'Workload {token.upper()}', 'service_tier': cell['service_tier'], 'data_class': cell['data_class'], 'schedule_name': f'Window {token.upper()}', 'start_time_local': f'{(slot * 4 + int(task_id[1:])) % 24:02d}:00'}) | |
| return tuple(rows) | |
| def fn_provider_tools_2(): | |
| tools = ext_deepcopy(fn_provider_tools_3()) | |
| by_name = {row['function']['name']: row['function'] for row in tools} | |
| by_name['get_site_recovery_dashboard']['description'] = 'Return bounded site recovery status, including the currently effective routing policy epoch. After a retained routing tuple is rejected as stale, this is the ordinary site-level observation used before refreshing exact policy evidence. It does not reveal a route or repository selection.' | |
| by_name['search_protection_policy_evidence']['description'] = 'Resolve route, repository profile, rule identity, and effective epoch for one exact service-tier and data-class condition. Evidence for a newer epoch becomes admissible only after the current site epoch has been established.' | |
| return tools | |
| def fn_stream_targets_5(task_id): | |
| with fn__schedule_2(): | |
| return tuple(ext_deepcopy(fn_stream_targets_3(task_id))) | |
| def fn__schedule_2(): | |
| old_rules = _SCHEDULE_STATE.RULE_SCHEDULE | |
| old_structures = _SCHEDULE_STATE.STRUCTURE_SCHEDULE | |
| _SCHEDULE_STATE.RULE_SCHEDULE = DATA_RULE_SCHEDULE_3 | |
| _SCHEDULE_STATE.STRUCTURE_SCHEDULE = DATA_STRUCTURE_SCHEDULE_3 | |
| try: | |
| yield | |
| finally: | |
| _SCHEDULE_STATE.RULE_SCHEDULE = old_rules | |
| _SCHEDULE_STATE.STRUCTURE_SCHEDULE = old_structures | |
| def fn_provider_tools_3(): | |
| """Expose only valid, decision-relevant arguments on the learner surface.""" | |
| tools = ext_deepcopy(fn_provider_tools_4()) | |
| by_name = {row['function']['name']: row['function'] for row in tools} | |
| repositories = by_name['list_backup_repositories'] | |
| repositories['description'] = 'List repositories for one site. Returned rows include the stable repository ID, pool, online status, and protection profile needed to evaluate a routing tuple.' | |
| repositories['parameters']['properties'].pop('storage_tier_filter', None) | |
| repositories['parameters']['properties']['status_filter'] = {'type': 'string', 'enum': ['online']} | |
| by_name['list_protection_sites']['description'] = 'List the stable protection-site name and ID directory visible to the operator.' | |
| by_name['get_workload_asset']['description'] = 'Optional expensive audit read for one workload. Task-supplied asset IDs are authoritative handles and do not require a pre-read.' | |
| by_name['get_backup_policy']['description'] = 'Optional expensive audit read for one backup policy. Task-supplied policy IDs identify the requested draft policies and do not require a pre-read.' | |
| by_name['search_protection_policy_evidence']['description'] = 'Resolve route, repository profile, rule identity, and effective epoch for one exact service-tier and data-class condition.' | |
| schedule = by_name['create_schedule_window'] | |
| schedule['description'] = 'Create an enabled daily schedule window for the supplied draft policy.' | |
| schedule['parameters']['properties']['frequency'] = {'type': 'string', 'enum': ['daily']} | |
| for key in ('blackout_dates', 'concurrency_limit', 'status'): | |
| schedule['parameters']['properties'].pop(key, None) | |
| status = by_name['update_backup_policy_status'] | |
| status['parameters']['properties']['new_status'] = {'type': 'string', 'enum': ['active']} | |
| assignment = by_name['assign_policy_to_asset'] | |
| assignment['description'] = 'Create an active assignment for the supplied policy and asset using an exact repository ID and current protection route.' | |
| for key in ('priority', 'protection_state'): | |
| assignment['parameters']['properties'].pop(key, None) | |
| verification = by_name['list_policy_assignments'] | |
| verification['description'] = 'Read back assignments for one site; filter by the task-supplied policy and asset IDs to verify a completed protection chain.' | |
| for key in ('state_filter', 'priority_filter'): | |
| verification['parameters']['properties'].pop(key, None) | |
| return tools | |
| def fn_provider_tools_4(): | |
| return [{'type': 'function', 'function': {'name': row['name'], 'description': row['description'], 'parameters': ext_deepcopy(row['input_schema'])}} for row in DATA_TOOLS_2] | |
| def fn__base_entities(): | |
| entities: dict[str, list[dict[str, ext_Any]]] = {name: [] for name in DATA_ENTITY_ID_FIELDS} | |
| entities['operator_user'] = [{'user_id': 'user-stream-backup-admin', 'full_name': 'Stream Backup Administrator', 'email_address': 'stream-backup-admin@example.invalid', 'role': 'backup_admin', 'site_ids': [row['site_id'] for row in DATA_STRUCTURE_CLUSTERS], 'status': 'active', 'team': 'Data Protection', 'created_at': '2026-05-16T12:00:00Z', 'updated_at': '2026-05-16T12:00:00Z'}] | |
| for cluster in DATA_STRUCTURE_CLUSTERS: | |
| entities['protection_site'].append({'site_id': cluster['site_id'], 'name': cluster['site_name'], 'site_type': 'recovery', 'region': cluster['region'], 'criticality': 'high', 'status': 'active', 'rpo_target_minutes': 30, 'rto_target_minutes': 120, 'timezone': 'UTC', 'created_at': '2026-05-16T12:00:00Z', 'updated_at': '2026-05-16T12:00:00Z'}) | |
| for (profile_index, profile) in enumerate(DATA_PROFILES, 1): | |
| entities['backup_repository'].append({'repository_id': fn__repository_id(cluster['atom_id'], profile), 'site_id': cluster['site_id'], 'name': f"{cluster['site_name']} Repository {profile_index}", 'repository_pool': cluster['repository_pool'], 'protection_profile': profile, 'storage_tier': 'object', 'status': 'online', 'capacity_tb': 8.0, 'used_tb': 1.0, 'reserved_tb': 0.0, 'quota_warning_pct': 90, 'encryption_state': 'platform_managed', 'immutable_until': '2027-05-16T12:00:00Z', 'region': cluster['region'], 'created_at': '2026-05-16T12:00:00Z', 'updated_at': '2026-05-16T12:00:00Z'}) | |
| return entities | |
| def fn__load_raw_logic(): | |
| 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, str(CASE_DIR / 'raw')) | |
| try: | |
| module = mod_importlib.import_module('mcp_servers.tool_logic.backup') | |
| finally: | |
| mod_sys.path.remove(str(CASE_DIR / 'raw')) | |
| 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 | |
| class World: | |
| def activate_task(self, task_id, **kwargs): | |
| observed_epoch = self._observed_global_epoch | |
| result = self._backup_evolution_activate_task(task_id, **kwargs) | |
| if observed_epoch == self._policy_version: | |
| self._observed_global_epoch = observed_epoch | |
| result['entry_semantic_hash'] = fn_digest(self.snapshot()) | |
| return result | |
| def _policy_evidence(self, arguments): | |
| result = self._backup_evidence_evolution_policy_evidence(arguments) | |
| if result.get('status') != 'success': | |
| return result | |
| data = result['data'] | |
| scope = {key: arguments[key] for key in ('service_tier', 'data_class')} | |
| current = self.policy_cells.get((scope['service_tier'], scope['data_class'])) | |
| verified = bool(current and data['snapshot_epoch'] == self._policy_version and any((all((row.get(key) == value for (key, value) in current.items())) for row in data['evidence']))) | |
| if verified: | |
| atom = current['rule_atom'] | |
| if atom in self.rule_revalidation and self.rule_revalidation[atom] != 'validated': | |
| self.rule_revalidation[atom] = 'ready_current' | |
| data['evidence_validation'] = {'scope': scope, 'status': 'current' if verified else 'retained_snapshot' if current else 'no_matching_rule', 'valid_until': 'routing_policy_changes' if verified else None} | |
| return result | |
| def snapshot(self): | |
| value = self._backup_independent_world_snapshot() | |
| value['epoch_freshness_contract'] = 'backup-epoch-freshness-evolution-v4' | |
| return value | |
| def restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('epoch_freshness_contract', None) != 'backup-epoch-freshness-evolution-v4': | |
| raise ValueError('Backup epoch freshness snapshot identity differs') | |
| self._backup_independent_world_restore(value) | |
| def _priority_guard(self, name, arguments): | |
| return None | |
| def __init__(self, *args, **kwargs): | |
| self._own_assignments = {} | |
| self._backup_rule_successor_init(*args, **kwargs) | |
| def _confirm_own_assignment(self, arguments, actor_user_id): | |
| keys = {'site_id', 'policy_id', 'asset_id', 'limit', 'offset'} | |
| if not isinstance(arguments, dict) or set(arguments) != keys or type(arguments['limit']) is not int or (arguments['limit'] != 1) or (type(arguments['offset']) is not int) or (arguments['offset'] != 0): | |
| return None | |
| actor = self._actor(actor_user_id) | |
| if actor is None or arguments['site_id'] not in set(actor.get('site_ids') or []): | |
| return None | |
| issued = next((row for row in self._own_assignments.values() if row['actor_user_id'] == actor_user_id and row['task_id'] == self._task_id and all((row[key] == arguments[key] for key in ('site_id', 'policy_id', 'asset_id')))), None) | |
| if issued is None: | |
| return None | |
| before = self._business_hash() | |
| assignment = self._state.get_entity('policy_assignment', issued['assignment_id'], 'assignment_id') | |
| rows = [] if assignment is None else [{key: assignment[key] for key in ('assignment_id', 'policy_id', 'asset_id', 'protection_state')}] | |
| if rows and rows[0]['protection_state'] == 'active': | |
| for target in self._task_targets: | |
| if target['policy_id'] == arguments['policy_id'] and target['asset_id'] == arguments['asset_id']: | |
| self.verified_target_ids.add(target['target_id']) | |
| result = self._with_budget({'status': 'success', 'data': {'assignments': rows, 'total_count': len(rows), 'limit': 1, 'offset': 0, 'confirmation_only': True}, 'message': 'Current status of your submitted assignment.'}, 0) | |
| self._record_event('list_policy_assignments', actor_user_id, result, before, self._business_hash()) | |
| return result | |
| def dispatch(self, name, arguments, actor_user_id): | |
| if name == 'list_policy_assignments': | |
| confirmation = self._confirm_own_assignment(arguments, actor_user_id) | |
| if confirmation is not None: | |
| return confirmation | |
| result = self._backup_rule_successor_dispatch(name, arguments, actor_user_id) | |
| if name == 'assign_policy_to_asset' and result.get('status') == 'success': | |
| assignment = result['data']['assignment'] | |
| self._own_assignments[assignment['assignment_id']] = {**{key: assignment[key] for key in ('assignment_id', 'site_id', 'policy_id', 'asset_id')}, 'actor_user_id': actor_user_id, 'task_id': self._task_id} | |
| return result | |
| def apply_stream_drift(self, event_id='evt-protection-routing-evidence-2026-09-v8'): | |
| return World._backup_rule_successor_apply_stream_drift(self, event_id) | |
| def _target_for_atom(self, atom_id): | |
| return next((row for row in self._task_targets if row['rule_atom'] == atom_id), None) | |
| def _cost(self, name, result): | |
| if name == 'search_protection_policy_evidence' and self._safe_refresh_discount: | |
| return 14 | |
| return self._backup_rule_successor_cost(name, result) | |
| def _known_current_epoch(self, *, excluding=None): | |
| return any((atom_id != excluding and state == 'validated' for (atom_id, state) in self.rule_revalidation.items())) | |
| def grade(self, task_id=None): | |
| grade = self._persistent_backup_recovery_adapter_grade(task_id) | |
| deliverables = [] | |
| for row in grade['deliverables']: | |
| item = ext_deepcopy(row) | |
| item['state_complete'] = bool(item['complete']) | |
| item['verification_complete'] = item['target_id'] in self.verified_target_ids | |
| item['complete'] = item['state_complete'] and item['verification_complete'] | |
| item['score'] = 25.0 if item['complete'] else 0.0 | |
| deliverables.append(item) | |
| completed = sum((row['complete'] for row in deliverables)) | |
| return {**grade, 'score': completed * 25.0, 'completed_artifacts': completed, 'deliverables': deliverables} | |
| def policy_cells(self): | |
| source = DATA_POST_POLICY_CELLS if self._policy_version == 'routing-epoch-9a27' else DATA_POLICY_CELLS | |
| return ext_deepcopy(source) | |
| def _target_for_policy(self, policy_id): | |
| return next((target for target in self._task_targets if target['policy_id'] == policy_id), None) | |
| def _target_complete(self, target): | |
| grade = self.grade(self._task_id) | |
| row = next((item for item in grade['deliverables'] if item['target_id'] == target['target_id'])) | |
| return bool(row['complete']) | |
| def _charged_error(self, name, code, message): | |
| if self._calls >= 40: | |
| return self._with_budget(fn__error('CALL_BUDGET_EXHAUSTED', 'task call budget is exhausted'), 0) | |
| if name in DATA_WRITE_TOOLS and self._writes >= 20: | |
| return self._with_budget(fn__error('WRITE_BUDGET_EXHAUSTED', 'task write budget is exhausted'), 0) | |
| before_hash = self.business_hash() | |
| result = fn__error(code, message) | |
| charged = self._cost(name, result) | |
| if charged > self._remaining: | |
| self._calls += 1 | |
| exhausted = self._with_budget(fn__error('WORK_BUDGET_EXHAUSTED', 'insufficient work units for this operation'), 0) | |
| self._record_event(name, 'user-stream-backup-admin', exhausted, before_hash, before_hash) | |
| return exhausted | |
| self._remaining -= charged | |
| self._calls += 1 | |
| if name in DATA_WRITE_TOOLS: | |
| self._writes += 1 | |
| value = self._with_budget(result, charged) | |
| self._record_event(name, 'user-stream-backup-admin', value, before_hash, before_hash) | |
| return value | |
| def _exact_stale_tuple(self, target, arguments): | |
| atom_id = target['rule_atom'] | |
| repository = self._state.get_entity('backup_repository', arguments.get('repository_id'), 'repository_id') | |
| return bool(arguments.get('protection_route') == DATA_PRE_RULES[atom_id]['protection_route'] and repository and (repository.get('protection_profile') == DATA_PRE_RULES[atom_id]['repository_profile'])) | |
| def _revalidation_assignment_guard(self, name, arguments): | |
| if not self._enforce_revalidation or name != 'assign_policy_to_asset': | |
| return None | |
| target = self._target_for_policy(str(arguments.get('policy_id') or '')) | |
| if target is None or target['rule_atom'] not in self.rule_revalidation: | |
| return None | |
| atom_id = target['rule_atom'] | |
| state = self.rule_revalidation[atom_id] | |
| if state == 'awaiting_exact_stale': | |
| if self._exact_stale_tuple(target, arguments): | |
| return None | |
| return self._charged_error(name, 'REVALIDATION_STALE_ATTEMPT_REQUIRED', 'the retained routing tuple must be tested before replacement evidence is admissible') | |
| if state not in {'ready_current', 'validated'}: | |
| return self._charged_error(name, 'REVALIDATION_EVIDENCE_REQUIRED', 'current epoch, policy, and repository evidence must be observed before retry') | |
| return None | |
| def activated_tasks(self): | |
| return tuple(self._activated_tasks) | |
| def applied_boundary_events(self): | |
| return frozenset(self._applied_boundary_events) | |
| def current_episode_events(self): | |
| return ext_deepcopy(self._events[self._active_event_start:]) | |
| def business_hash(self): | |
| return self._business_hash() | |
| def lineage_hash(self): | |
| return mod_hashlib.sha256(fn__canonical(self.snapshot()).encode('utf-8')).hexdigest() | |
| def public_tool_schemas(self, role): | |
| return ext_deepcopy(DATA_TOOLS_2) if role == 'backup_admin' else [] | |
| def remaining(self): | |
| return self._remaining | |
| def task_targets(self): | |
| return ext_deepcopy(self._task_targets) | |
| def apply_policy_drift(self, version='protection-policy-v2'): | |
| if version != 'protection-policy-v2': | |
| raise ValueError('unsupported protection policy version') | |
| self._policy_version = version | |
| def semantic_hash(self, snapshot=None): | |
| return fn__canonical_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 _actor(self, actor_user_id): | |
| actor = self._state.get_entity('operator_user', actor_user_id, 'user_id') | |
| if not actor or actor.get('status') != 'active' or actor.get('role') != 'backup_admin': | |
| return None | |
| return actor | |
| def _target_site(self, name, arguments): | |
| if name in {'get_site_recovery_dashboard', 'list_backup_repositories', 'list_workload_assets', 'list_backup_policies', 'list_policy_assignments', 'create_backup_policy'}: | |
| return arguments.get('site_id') | |
| if name == 'get_workload_asset': | |
| row = self._state.get_entity('workload_asset', arguments.get('asset_id'), 'asset_id') | |
| return row.get('site_id') if row else None | |
| if name in {'get_backup_policy', 'update_backup_policy_status', 'create_schedule_window'}: | |
| row = self._state.get_entity('backup_policy', arguments.get('policy_id'), 'policy_id') | |
| return row.get('site_id') if row else None | |
| if name == 'assign_policy_to_asset': | |
| row = self._state.get_entity('backup_policy', arguments.get('policy_id'), 'policy_id') | |
| return row.get('site_id') if row else None | |
| if name == 'remove_policy_assignment': | |
| row = self._state.get_entity('policy_assignment', arguments.get('assignment_id'), 'assignment_id') | |
| return row.get('site_id') if row else None | |
| return None | |
| def _record_event(self, name, actor_user_id, result, before_hash, after_hash): | |
| message = str(result.get('message') or '') | |
| error_code = (result.get('data') or {}).get('error_code') or message.split(':', 1)[0] if result.get('status') == 'error' else None | |
| self._events.append({'sequence': len(self._events) + 1, 'tool': name, 'actor_user_id': actor_user_id, 'status': result.get('status'), 'error_code': error_code, 'state_hash_before': before_hash, 'state_hash_after': after_hash}) | |
| def _business_hash(self): | |
| return fn__canonical_hash(self._state.snapshot()) | |
| def _reserve_for_assignment(self, arguments): | |
| asset = self._state.get_entity('workload_asset', arguments['asset_id'], 'asset_id') | |
| repository = self._state.get_entity('backup_repository', arguments['repository_id'], 'repository_id') | |
| if not asset or not repository: | |
| return None | |
| reserve_tb = round(float(asset.get('size_gb') or 0) / 1024.0, 6) | |
| free_tb = float(repository.get('capacity_tb') or 0) - float(repository.get('used_tb') or 0) - float(repository.get('reserved_tb') or 0) | |
| if reserve_tb <= 0 or reserve_tb > free_tb: | |
| return fn__error('REPOSITORY_QUOTA_EXCEEDED', 'repository capacity is insufficient') | |
| arguments['_reserve_tb'] = reserve_tb | |
| return None | |
| def _apply_assignment_reservation(self, arguments, result): | |
| reserve_tb = float(arguments.pop('_reserve_tb')) | |
| repository_id = arguments['repository_id'] | |
| repository = self._state.get_entity('backup_repository', repository_id, 'repository_id') | |
| assignment_id = result['data']['assignment']['assignment_id'] | |
| updated_repository = self._state.update_entity('backup_repository', repository_id, {'reserved_tb': round(float(repository.get('reserved_tb') or 0) + reserve_tb, 6)}, 'repository_id') | |
| updated_assignment = self._state.update_entity('policy_assignment', assignment_id, {'reserved_tb': reserve_tb}, 'assignment_id') | |
| self._state.update_entity('workload_asset', arguments['asset_id'], {'status': 'protected'}, 'asset_id') | |
| result['data']['assignment'] = updated_assignment | |
| result['data']['repository'] = updated_repository | |
| return result | |
| def _release_assignment_reservation(self, before, result): | |
| assignment = next((row for row in before['entities'].get('policy_assignment', []) if row.get('assignment_id') == result['data'].get('assignment_id')), None) | |
| if not assignment or not result['data'].get('changed'): | |
| return result | |
| repository_id = assignment['repository_id'] | |
| repository = self._state.get_entity('backup_repository', repository_id, 'repository_id') | |
| reserve_tb = float(assignment.get('reserved_tb') or 0) | |
| self._state.update_entity('backup_repository', repository_id, {'reserved_tb': round(max(0.0, float(repository.get('reserved_tb') or 0) - reserve_tb), 6)}, 'repository_id') | |
| active_for_asset = [row for row in self._state.list_entities('policy_assignment') if row.get('asset_id') == assignment['asset_id'] and row.get('protection_state') != 'removed'] | |
| if not active_for_asset: | |
| self._state.update_entity('workload_asset', assignment['asset_id'], {'status': 'paused'}, 'asset_id') | |
| return result | |
| def _with_budget(self, result, charged): | |
| value = ext_deepcopy(result) | |
| value['budget'] = {'unit': 'backup_work_units', 'charged': charged, 'remaining': self._remaining} | |
| return value | |
| def _enrich_list_result(self, name, result): | |
| if result.get('status') != 'success': | |
| return result | |
| data = result.get('data') or {} | |
| entity_by_tool = {'list_backup_repositories': ('repositories', 'backup_repository', 'repository_id'), 'list_backup_policies': ('policies', 'backup_policy', 'policy_id')} | |
| descriptor = entity_by_tool.get(name) | |
| if descriptor is None: | |
| return result | |
| (rows_key, entity_type, id_field) = descriptor | |
| enriched = [] | |
| for row in data.get(rows_key) or []: | |
| source = self._state.get_entity(entity_type, row[id_field], id_field) or {} | |
| merged = ext_deepcopy(row) | |
| for field in ('repository_pool', 'protection_profile', 'service_tier', 'data_class', 'encryption_required', 'immutable_required'): | |
| if field in source: | |
| merged[field] = ext_deepcopy(source[field]) | |
| enriched.append(merged) | |
| result = ext_deepcopy(result) | |
| result['data'][rows_key] = enriched | |
| return result | |
| def _validate_protection_route(self, arguments): | |
| policy = self._state.get_entity('backup_policy', arguments['policy_id'], 'policy_id') | |
| repository = self._state.get_entity('backup_repository', arguments['repository_id'], 'repository_id') | |
| if not policy or not repository: | |
| return None | |
| cell = self.policy_cells.get((policy.get('service_tier'), policy.get('data_class'))) | |
| if cell is None: | |
| return fn__error('POLICY_CELL_NOT_FOUND', 'no current policy evidence exists for this condition') | |
| if arguments.get('protection_route') != cell['protection_route']: | |
| return fn__error('PROTECTION_ROUTE_MISMATCH', 'the submitted protection route is not current') | |
| if repository.get('repository_pool') != policy.get('repository_pool'): | |
| return fn__error('REPOSITORY_POOL_MISMATCH', 'repository is outside the policy resource pool') | |
| if repository.get('protection_profile') != cell['repository_profile']: | |
| return fn__error('REPOSITORY_PROFILE_MISMATCH', 'repository does not satisfy the current policy cell') | |
| arguments.pop('protection_route', None) | |
| return None | |
| def _backup_evolution_activate_task(self, task_id, *, apply_boundary_drift=True): | |
| index = len(self._activated_tasks) | |
| if index >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[index]: | |
| raise ValueError('out-of-order Backup task activation') | |
| event_task = f"T{DATA_SCHEDULE_2['events'][0]['before_task']:02d}" | |
| boundary = self.apply_stream_drift() if task_id == event_task and apply_boundary_drift else None | |
| if boundary: | |
| for atom in DATA_CHANGED_RULE_IDS: | |
| self.rule_revalidation.setdefault(atom, 'awaiting_exact_stale') | |
| for (kind, rows) in fn__task_entities(task_id).items(): | |
| for row in rows: | |
| self._state.add_entity(kind, row, DATA_ENTITY_ID_FIELDS[kind]) | |
| (self._task_id, self._task_targets) = (task_id, list(fn_stream_targets(task_id))) | |
| self._calls = self._writes = 0 | |
| self._remaining = self._initial_budget | |
| self._active_event_start = len(self._events) | |
| self._activated_tasks.append(task_id) | |
| self._episode_repository_sites = set() | |
| self.verified_target_ids = set() | |
| self._own_assignments = {} | |
| self._observed_global_epoch = None | |
| self._safe_refresh_discount = False | |
| return {'status': 'success', 'event_id': fn_public_task(task_id)['task_id'], 'world_reset': False, 'budget_reset': True, 'public_notice': '', 'boundary_event_applied': bool(boundary and boundary['applied']), 'entry_business_hash': self.business_hash(), 'entry_lineage_hash': self.lineage_hash(), 'entry_semantic_hash': fn_digest(self.snapshot())} | |
| def _backup_evidence_evolution_policy_evidence(self, arguments): | |
| result = self._backup_rule_successor_policy_evidence(arguments) | |
| if result.get('status') != 'success': | |
| return result | |
| rows = result.get('data', {}).get('evidence', []) | |
| is_changed = any((row['rule_atom'] in DATA_CHANGED_RULE_IDS for row in rows)) | |
| retained = self._policy_version == 'routing-epoch-9a27' and is_changed and (not any((row['effective_epoch'] == 'routing-epoch-9a27' for row in rows))) | |
| result['data']['snapshot_epoch'] = 'routing-epoch-61c4' if retained else self._policy_version | |
| return result | |
| def _backup_independent_world_snapshot(self): | |
| value = self._backup_evidence_evolution_snapshot() | |
| value['independent_protection_contract'] = 'backup-independent-protection-evolution-v3' | |
| return value | |
| def _backup_independent_world_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('independent_protection_contract', None) != 'backup-independent-protection-evolution-v3': | |
| raise ValueError('Backup independent protection contract differs') | |
| self._backup_evidence_evolution_restore(value) | |
| def _backup_rule_successor_init(self, budget=126, *, enforce_priority=True, enforce_revalidation=True): | |
| self._observed_global_epoch: str | None = None | |
| self._safe_refresh_discount = False | |
| self._backup_rule_successor_init_2(budget=budget, enforce_priority=enforce_priority, enforce_revalidation=enforce_revalidation) | |
| def _backup_rule_successor_dispatch(self, name, arguments, actor_user_id): | |
| if name == 'assign_policy_to_asset': | |
| actor = self._actor(actor_user_id) | |
| try: | |
| mod_jsonschema.validate(arguments, DATA_TOOL_BY_NAME[name]['input_schema']) | |
| valid = True | |
| except mod_jsonschema.ValidationError: | |
| valid = False | |
| site = self._target_site(name, arguments) if valid else None | |
| denied = self._task_id is None or actor is None or (not valid) or (self._calls >= 40) or (self._writes >= 20) or (actor is not None and site is not None and (site not in set(actor.get('site_ids') or []))) or (self._remaining < self._cost(name, {})) | |
| if denied: | |
| return World._backup_recovery_adapter_dispatch(self, name, arguments, actor_user_id) | |
| return self._backup_rule_successor_dispatch_2(name, arguments, actor_user_id) | |
| def _backup_rule_successor_apply_stream_drift(self, event_id='evt-protection-routing-evidence-2026-09-v6'): | |
| before = self.business_hash() | |
| if event_id in self._applied_boundary_events: | |
| return {'status': 'success', 'event_id': 'EV-' + fn_digest(event_id)[:16].upper(), 'applied': False, 'idempotent': True, 'before_world_sha256': before, 'after_world_sha256': self.business_hash(), 'public_notice': ''} | |
| self._policy_version = 'routing-epoch-9a27' | |
| self._applied_boundary_events.add(event_id) | |
| return {'status': 'success', 'event_id': 'EV-' + fn_digest(event_id)[:16].upper(), 'applied': True, 'idempotent': False, 'before_world_sha256': before, 'after_world_sha256': self.business_hash(), 'public_notice': ''} | |
| def _backup_rule_successor_cost(self, name, result): | |
| if name in {'list_protection_sites', 'get_workload_asset', 'get_backup_policy'}: | |
| return 32 | |
| if name == 'search_protection_policy_evidence' and self._discount_policy_evidence: | |
| return 14 | |
| return self._backup_rule_successor_cost_2(name, result) | |
| def _persistent_backup_recovery_adapter_grade(self, task_id=None): | |
| active = task_id or self._task_id | |
| if active != self._task_id or active not in DATA_TASK_IDS: | |
| raise ValueError('only the active stream task can be graded') | |
| deliverables = [] | |
| cells = self.policy_cells | |
| assignments = self._state.list_entities('policy_assignment') | |
| schedules = self._state.list_entities('schedule_window') | |
| for target in self._task_targets: | |
| policy = self._state.get_entity('backup_policy', target['policy_id'], 'policy_id') | |
| asset = self._state.get_entity('workload_asset', target['asset_id'], 'asset_id') | |
| schedule_ok = any((row.get('policy_id') == target['policy_id'] and row.get('status') == 'enabled' for row in schedules)) | |
| assignment = next((row for row in assignments if row.get('policy_id') == target['policy_id'] and row.get('asset_id') == target['asset_id'] and (row.get('protection_state') == 'active')), None) | |
| repository = self._state.get_entity('backup_repository', assignment['repository_id'], 'repository_id') if assignment else None | |
| current = cells[target['service_tier'], target['data_class']] | |
| complete = bool(policy and policy.get('status') == 'active' and schedule_ok and assignment and asset and (asset.get('status') == 'protected') and repository and (len({policy.get('site_id'), asset.get('site_id'), repository.get('site_id')}) == 1) and (repository.get('repository_pool') == target['repository_pool']) and (repository.get('protection_profile') == current['repository_profile'])) | |
| deliverables.append({'target_id': target['target_id'], 'structure_atom': target['structure_atom'], 'rule_atom': target['rule_atom'], 'complete': complete, 'score': 25.0 if complete else 0.0}) | |
| completed = sum((row['complete'] for row in deliverables)) | |
| return {'task_id': active, 'score': completed * 25.0, 'max_score': 100.0, 'completed_artifacts': completed, 'deliverables': deliverables, 'remaining_budget': self._remaining} | |
| def _backup_rule_successor_policy_evidence(self, arguments): | |
| atom_id = next((key for (key, row) in DATA_PRE_RULES.items() if row['service_tier'] == arguments['service_tier'] and row['data_class'] == arguments['data_class']), None) | |
| state_before = self.rule_revalidation.get(atom_id or '') | |
| self._safe_refresh_discount = state_before == 'awaiting_safe_exact_refresh' | |
| result = self._backup_rule_successor_policy_evidence_2(arguments) | |
| if not atom_id or self._observed_global_epoch != 'routing-epoch-9a27': | |
| return result | |
| if state_before == 'awaiting_exact_stale': | |
| result['data']['evidence'] = [row for row in result['data']['evidence'] if row['effective_epoch'] == 'routing-epoch-61c4'] | |
| self.rule_revalidation[atom_id] = 'awaiting_safe_exact_refresh' | |
| target = self._target_for_atom(atom_id) | |
| if target is not None: | |
| self.revalidation_targets[atom_id] = target['target_id'] | |
| elif state_before == 'awaiting_safe_exact_refresh': | |
| if any((row['effective_epoch'] == self._observed_global_epoch for row in result['data']['evidence'])): | |
| self.rule_revalidation[atom_id] = 'ready_current' | |
| return result | |
| def _backup_evidence_evolution_snapshot(self): | |
| value = self._backup_evolution_snapshot() | |
| value['evidence_contract'] = 'backup-lifecycle-evidence-evolution-v2' | |
| return value | |
| def _backup_evidence_evolution_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('evidence_contract', None) != 'backup-lifecycle-evidence-evolution-v2': | |
| raise ValueError('Backup evidence-snapshot contract differs') | |
| self._backup_evolution_restore(value) | |
| def _backup_rule_successor_init_2(self, budget=126, *, enforce_priority=True, enforce_revalidation=True): | |
| self._discount_policy_evidence = False | |
| self._backup_rule_successor_init_3(budget=budget, enforce_priority=enforce_priority, enforce_revalidation=enforce_revalidation) | |
| def _backup_recovery_adapter_dispatch(self, name, arguments, actor_user_id): | |
| 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') | |
| actor = self._actor(actor_user_id) | |
| if actor is None: | |
| return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an active backup administrator') | |
| 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 >= 40: | |
| return self._with_budget(fn__error('CALL_BUDGET_EXHAUSTED', 'task call budget is exhausted'), 0) | |
| if name in DATA_WRITE_TOOLS and self._writes >= 20: | |
| return self._with_budget(fn__error('WRITE_BUDGET_EXHAUSTED', 'task write budget is exhausted'), 0) | |
| target_site = self._target_site(name, arguments) | |
| if target_site is not None and target_site not in set(actor.get('site_ids') or []): | |
| return self._with_budget(fn__error('ACTOR_SITE_SCOPE_DENIED', 'actor is not assigned to the target site'), 0) | |
| before = self.snapshot() | |
| before_hash = self._business_hash() | |
| prepared = ext_deepcopy(arguments) | |
| if name == 'create_backup_policy': | |
| prepared['created_by_user_id'] = actor_user_id | |
| elif name in {'update_backup_policy_status', 'remove_policy_assignment'}: | |
| prepared['actor_user_id'] = actor_user_id | |
| route_error = None | |
| capacity_error = None | |
| if name == 'assign_policy_to_asset': | |
| route_error = self._validate_protection_route(prepared) | |
| if route_error is None: | |
| capacity_error = self._reserve_for_assignment(prepared) | |
| raw_arguments = {key: value for (key, value) in prepared.items() if not key.startswith('_')} | |
| try: | |
| if name == 'search_protection_policy_evidence': | |
| result = self._policy_evidence(prepared) | |
| elif route_error is not None: | |
| result = route_error | |
| elif capacity_error is not None: | |
| result = capacity_error | |
| else: | |
| result = getattr(self._logic, name)(self._state, **raw_arguments) | |
| if result.get('status') == 'success' and name == 'assign_policy_to_asset': | |
| result = self._apply_assignment_reservation(prepared, result) | |
| elif result.get('status') == 'success' and name == 'remove_policy_assignment': | |
| result = self._release_assignment_reservation(before, result) | |
| result = self._enrich_list_result(name, result) | |
| except Exception: | |
| self.restore(before) | |
| result = fn__error('ADAPTER_EXECUTION_FAILED', 'the operation failed without committing state') | |
| if result.get('status') != 'success': | |
| self.restore(before) | |
| charged = self._cost(name, result) | |
| if charged > self._remaining: | |
| self.restore(before) | |
| self._calls += 1 | |
| exhausted = self._with_budget(fn__error('WORK_BUDGET_EXHAUSTED', 'insufficient work units for this operation'), 0) | |
| self._record_event(name, actor_user_id, exhausted, before_hash, before_hash) | |
| return exhausted | |
| self._remaining -= charged | |
| self._calls += 1 | |
| if name in DATA_WRITE_TOOLS: | |
| self._writes += 1 | |
| after_hash = self._business_hash() | |
| result = self._with_budget(result, charged) | |
| self._record_event(name, actor_user_id, result, before_hash, after_hash) | |
| return result | |
| def _backup_rule_successor_dispatch_2(self, name, arguments, actor_user_id): | |
| if name == 'assign_policy_to_asset' and self._enforce_revalidation: | |
| priority_error = self._priority_guard(name, arguments) | |
| if priority_error is not None: | |
| return priority_error | |
| target = self._target_for_policy(str(arguments.get('policy_id') or '')) | |
| if target is not None and self.rule_revalidation.get(target['rule_atom']) == 'awaiting_safe_exact_refresh' and self._exact_stale_tuple(target, arguments): | |
| result = self._charged_error(name, 'ROUTING_EPOCH_STALE', 'the retained routing tuple is stale for the observed global routing epoch; repeat exact policy evidence refresh for this condition') | |
| self.revalidation_targets[target['rule_atom']] = target['target_id'] | |
| return result | |
| self._safe_refresh_discount = False | |
| try: | |
| result = self._backup_rule_successor_dispatch_3(name, arguments, actor_user_id) | |
| finally: | |
| self._safe_refresh_discount = False | |
| if name == 'get_site_recovery_dashboard' and result.get('status') == 'success': | |
| self._observed_global_epoch = result.get('data', {}).get('routing_policy_epoch') | |
| return result | |
| def _backup_rule_successor_cost_2(self, name, result): | |
| if name in {'list_protection_sites', 'get_workload_asset', 'get_backup_policy'}: | |
| return 42 | |
| if name == 'search_protection_policy_evidence': | |
| return 20 | |
| return self._backup_recovery_adapter_cost(name, result) | |
| def _backup_rule_successor_policy_evidence_2(self, arguments): | |
| old = DATA_PRE_RULES.get((arguments['service_tier'], arguments['data_class'])) | |
| atom_id = next((key for (key, row) in DATA_PRE_RULES.items() if row['service_tier'] == arguments['service_tier'] and row['data_class'] == arguments['data_class']), None) | |
| state_before = self.rule_revalidation.get(atom_id or '') | |
| result = self._backup_rule_successor_policy_evidence_3(arguments) | |
| if atom_id and state_before == 'awaiting_fresh_policy' and (DATA_PRE_RULES[atom_id]['repository_profile'] == DATA_POST_RULES[atom_id]['repository_profile']): | |
| self.rule_revalidation[atom_id] = 'ready_current' | |
| return result | |
| def _backup_evolution_snapshot(self): | |
| value = self._backup_confirmation_snapshot() | |
| value['evolution_contract'] = {'case_version': 'backup-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2)} | |
| return value | |
| def _backup_evolution_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| if value.pop('evolution_contract', None) != {'case_version': 'backup-lifecycle-evolution-v1', 'schedule': DATA_SCHEDULE_2}: | |
| raise ValueError('Backup evolution contract differs') | |
| self._backup_confirmation_restore(value) | |
| def _backup_rule_successor_init_3(self, budget=126, *, enforce_priority=True, enforce_revalidation=True): | |
| self.verified_target_ids: set[str] = set() | |
| self._backup_rule_successor_init_4(budget=budget, enforce_priority=enforce_priority, enforce_revalidation=enforce_revalidation) | |
| def _backup_rule_successor_dispatch_3(self, name, arguments, actor_user_id): | |
| if name == 'assign_policy_to_asset' and self._enforce_revalidation: | |
| priority_error = self._priority_guard(name, arguments) | |
| if priority_error is not None: | |
| return priority_error | |
| target = self._target_for_policy(str(arguments.get('policy_id') or '')) | |
| if target is not None: | |
| atom_id = target['rule_atom'] | |
| if self.rule_revalidation.get(atom_id) == 'awaiting_exact_stale' and self._exact_stale_tuple(target, arguments): | |
| epoch_known = self._known_current_epoch(excluding=atom_id) | |
| message = 'the retained routing tuple is stale; the current site policy epoch was already established, so refresh exact policy evidence for this condition' if epoch_known else "the retained routing tuple is stale for the site's current policy epoch; inspect site recovery status, then refresh exact policy evidence for this condition" | |
| result = self._charged_error(name, 'ROUTING_EPOCH_STALE', message) | |
| self.rule_revalidation[atom_id] = 'awaiting_fresh_policy' if epoch_known else 'awaiting_current_epoch' | |
| self.revalidation_targets[atom_id] = target['target_id'] | |
| return result | |
| discounted = False | |
| if name == 'search_protection_policy_evidence': | |
| atom_id = next((key for (key, row) in DATA_PRE_RULES.items() if row['service_tier'] == arguments.get('service_tier') and row['data_class'] == arguments.get('data_class')), None) | |
| discounted = bool(atom_id and self.rule_revalidation.get(atom_id) == 'awaiting_fresh_policy' and self._known_current_epoch(excluding=atom_id)) | |
| self._discount_policy_evidence = discounted | |
| try: | |
| return self._backup_rule_successor_dispatch_4(name, arguments, actor_user_id) | |
| finally: | |
| self._discount_policy_evidence = False | |
| def _backup_recovery_adapter_cost(self, name, result): | |
| if name in DATA_LIST_KEYS: | |
| rows = (result.get('data') or {}).get(DATA_LIST_KEYS[name]) or [] | |
| return 4 + 2 * len(rows) | |
| return DATA_FIXED_COSTS.get(name, 4) | |
| def _backup_rule_successor_policy_evidence_3(self, arguments): | |
| result = self._backup_rule_successor_policy_evidence_4(arguments) | |
| old = DATA_POLICY_CELLS.get((arguments['service_tier'], arguments['data_class'])) | |
| atom_id = old['rule_atom'] if old else None | |
| state = self.rule_revalidation.get(atom_id or '') | |
| if state in {'awaiting_exact_stale', 'awaiting_current_epoch'}: | |
| result['data']['evidence'] = [row for row in result['data']['evidence'] if row['effective_epoch'] == 'routing-epoch-61c4'] | |
| elif state == 'awaiting_fresh_policy': | |
| target_id = self.revalidation_targets.get(atom_id or '') | |
| target = next((row for row in self._task_targets if row['target_id'] == target_id), None) | |
| self.rule_revalidation[atom_id] = 'ready_current' if target and target['site_id'] in self._episode_repository_sites else 'awaiting_fresh_repository' | |
| return result | |
| def _backup_confirmation_snapshot(self): | |
| snapshot = self._backup_rule_successor_snapshot() | |
| snapshot['own_assignment_confirmations'] = ext_deepcopy(self._own_assignments) | |
| return snapshot | |
| def _backup_confirmation_restore(self, snapshot): | |
| value = ext_deepcopy(snapshot) | |
| self._own_assignments = value.pop('own_assignment_confirmations', {}) | |
| self._backup_rule_successor_restore(value) | |
| def _backup_rule_successor_init_4(self, budget=132, *, enforce_priority=True, enforce_revalidation=True): | |
| self.rule_revalidation: dict[str, str] = {} | |
| self.revalidation_targets: dict[str, str] = {} | |
| self._episode_repository_sites: set[str] = set() | |
| self._enforce_priority = enforce_priority | |
| self._enforce_revalidation = enforce_revalidation | |
| self._backup_rule_successor_init_5(budget=budget) | |
| def _backup_rule_successor_dispatch_4(self, name, arguments, actor_user_id): | |
| result = self._backup_rule_successor_dispatch_5(name, arguments, actor_user_id) | |
| if name == 'list_policy_assignments' and result.get('status') == 'success': | |
| policy_id = str(arguments.get('policy_id') or '') | |
| asset_id = str(arguments.get('asset_id') or '') | |
| target = next((row for row in self._task_targets if row['policy_id'] == policy_id and row['asset_id'] == asset_id), None) | |
| assignments = result.get('data', {}).get('assignments') or [] | |
| if target is not None and any((row.get('policy_id') == policy_id and row.get('asset_id') == asset_id and (row.get('protection_state') == 'active') for row in assignments)): | |
| self.verified_target_ids.add(target['target_id']) | |
| return result | |
| def _backup_rule_successor_policy_evidence_4(self, arguments): | |
| key = (arguments['service_tier'], arguments['data_class']) | |
| old = DATA_POLICY_CELLS.get(key) | |
| current = self.policy_cells.get(key) | |
| evidence = [] | |
| if old is not None: | |
| evidence.append({**ext_deepcopy(old), 'effective_epoch': 'routing-epoch-61c4'}) | |
| if current is not None and current != old: | |
| evidence.append({**ext_deepcopy(current), 'effective_epoch': 'routing-epoch-9a27'}) | |
| return {'status': 'success', 'data': {'evidence': evidence}, 'message': ''} | |
| def _backup_rule_successor_snapshot(self): | |
| value = self._backup_rule_successor_snapshot_2() | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v8.2' | |
| return value | |
| def _backup_rule_successor_restore(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v8.2': | |
| raise ValueError('unsupported Backup Recovery v8.2 snapshot') | |
| value = ext_deepcopy(snapshot) | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v8' | |
| self._backup_rule_successor_restore_2(value) | |
| def _backup_rule_successor_init_5(self, budget=132): | |
| self._persistent_backup_recovery_adapter_init(budget=budget) | |
| self._policy_version = 'routing-epoch-61c4' | |
| def _backup_rule_successor_dispatch_5(self, name, arguments, actor_user_id): | |
| priority_error = self._priority_guard(name, arguments) | |
| if priority_error is not None: | |
| return priority_error | |
| revalidation_error = self._revalidation_assignment_guard(name, arguments) | |
| if revalidation_error is not None: | |
| return revalidation_error | |
| target = None | |
| stale_attempt = False | |
| state_before = None | |
| if name == 'assign_policy_to_asset': | |
| target = self._target_for_policy(str(arguments.get('policy_id') or '')) | |
| if target is not None: | |
| state_before = self.rule_revalidation.get(target['rule_atom']) | |
| stale_attempt = state_before == 'awaiting_exact_stale' and self._exact_stale_tuple(target, arguments) | |
| result = self._backup_rule_successor_dispatch_6(name, arguments, actor_user_id) | |
| success = result.get('status') == 'success' | |
| if name == 'list_backup_repositories' and success: | |
| site_id = str(arguments.get('site_id') or '') | |
| self._episode_repository_sites.add(site_id) | |
| for (atom_id, state) in list(self.rule_revalidation.items()): | |
| if state != 'awaiting_fresh_repository': | |
| continue | |
| target_id = self.revalidation_targets.get(atom_id) | |
| pending = next((row for row in self._task_targets if row['target_id'] == target_id), None) | |
| if pending and pending['site_id'] == site_id: | |
| self.rule_revalidation[atom_id] = 'ready_current' | |
| if name == 'get_site_recovery_dashboard' and success: | |
| site_id = str(arguments.get('site_id') or '') | |
| for (atom_id, state) in list(self.rule_revalidation.items()): | |
| if state != 'awaiting_current_epoch': | |
| continue | |
| target_id = self.revalidation_targets.get(atom_id) | |
| pending = next((row for row in self._task_targets if row['target_id'] == target_id), None) | |
| if pending and pending['site_id'] == site_id: | |
| self.rule_revalidation[atom_id] = 'awaiting_fresh_policy' | |
| if target is not None and stale_attempt and (not success): | |
| error_code = result.get('data', {}).get('error_code') | |
| if error_code in {'PROTECTION_ROUTE_MISMATCH', 'REPOSITORY_PROFILE_MISMATCH'}: | |
| atom_id = target['rule_atom'] | |
| self.rule_revalidation[atom_id] = 'awaiting_current_epoch' | |
| self.revalidation_targets[atom_id] = target['target_id'] | |
| if target is not None and success and (state_before in {'ready_current', 'validated'}): | |
| self.rule_revalidation[target['rule_atom']] = 'validated' | |
| return result | |
| def _backup_rule_successor_snapshot_2(self): | |
| value = self._backup_rule_successor_snapshot_3() | |
| value.update({'schema': 'rescopebench-backup-recovery-rule-stream/v8', 'provider_tools_sha256': 'f0ac996f2fa0dff9d8b176eaf7134b483ab74db75f6839ce294c85d0515f6791', 'observed_global_epoch': self._observed_global_epoch}) | |
| return value | |
| def _backup_rule_successor_restore_2(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v8': | |
| raise ValueError('unsupported Backup Recovery v8 snapshot') | |
| if snapshot.get('provider_tools_sha256') != 'f0ac996f2fa0dff9d8b176eaf7134b483ab74db75f6839ce294c85d0515f6791': | |
| raise ValueError('Backup Recovery v8 provider tool identity changed') | |
| if 'observed_global_epoch' not in snapshot: | |
| raise ValueError('Backup Recovery v8 snapshot missing global epoch state') | |
| value = ext_deepcopy(snapshot) | |
| self._observed_global_epoch = value.pop('observed_global_epoch') | |
| self._safe_refresh_discount = False | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v7' | |
| value['provider_tools_sha256'] = 'ea7e74c932e441f15145772390c47f81663f1f7264fad3e489ccfce5e2cb9dda' | |
| self._backup_rule_successor_restore_3(value) | |
| def _persistent_backup_recovery_adapter_init(self, budget=100): | |
| self._backup_recovery_adapter_init(budget=budget) | |
| self._state = MemoryState(fn__base_entities()) | |
| self._task_id = None | |
| self._task_targets = [] | |
| self._events = [] | |
| self._calls = 0 | |
| self._writes = 0 | |
| self._remaining = self._initial_budget | |
| self._policy_version = 'protection-policy-v1' | |
| self._activated_tasks: list[str] = [] | |
| self._applied_boundary_events: set[str] = set() | |
| self._active_event_start = 0 | |
| def _backup_rule_successor_dispatch_6(self, name, arguments, actor_user_id): | |
| result = self._backup_recovery_adapter_dispatch(name, arguments, actor_user_id) | |
| if name == 'get_site_recovery_dashboard' and result.get('status') == 'success': | |
| result = ext_deepcopy(result) | |
| result.setdefault('data', {})['routing_policy_epoch'] = self._policy_version | |
| return result | |
| def _backup_rule_successor_snapshot_3(self): | |
| value = self._backup_rule_successor_snapshot_4() | |
| value.update({'schema': 'rescopebench-backup-recovery-rule-stream/v7', 'provider_tools_sha256': 'ea7e74c932e441f15145772390c47f81663f1f7264fad3e489ccfce5e2cb9dda'}) | |
| return value | |
| def _backup_rule_successor_restore_3(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v7': | |
| raise ValueError('unsupported Backup Recovery v7 snapshot') | |
| if snapshot.get('provider_tools_sha256') != 'ea7e74c932e441f15145772390c47f81663f1f7264fad3e489ccfce5e2cb9dda': | |
| raise ValueError('Backup Recovery v7 provider tool identity changed') | |
| value = ext_deepcopy(snapshot) | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v6' | |
| value['provider_tools_sha256'] = 'b9a4ce5a6bce3a0f087d3acd1085e3576395829f9079bd7c50315c4890f30116' | |
| self._backup_rule_successor_restore_4(value) | |
| def _backup_recovery_adapter_init(self, budget=100): | |
| if type(budget) is not int or budget <= 0: | |
| raise ValueError('budget must be a positive integer') | |
| self._logic = fn__load_raw_logic() | |
| self._state = MemoryState({name: [] for name in DATA_ENTITY_ID_FIELDS}) | |
| self._task_id: str | None = None | |
| self._task_targets: list[dict[str, ext_Any]] = [] | |
| self._events: list[dict[str, ext_Any]] = [] | |
| self._calls = 0 | |
| self._writes = 0 | |
| self._initial_budget = budget | |
| self._remaining = budget | |
| self._policy_version = 'protection-policy-v1' | |
| def _backup_rule_successor_snapshot_4(self): | |
| value = self._backup_rule_successor_snapshot_5() | |
| value.update({'schema': 'rescopebench-backup-recovery-rule-stream/v6', 'provider_tools_sha256': 'b9a4ce5a6bce3a0f087d3acd1085e3576395829f9079bd7c50315c4890f30116', 'verified_target_ids': sorted(self.verified_target_ids)}) | |
| return value | |
| def _backup_rule_successor_restore_4(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v6': | |
| raise ValueError('unsupported Backup Recovery v6 snapshot') | |
| if snapshot.get('provider_tools_sha256') != 'b9a4ce5a6bce3a0f087d3acd1085e3576395829f9079bd7c50315c4890f30116': | |
| raise ValueError('Backup Recovery v6 provider tool identity changed') | |
| if 'verified_target_ids' not in snapshot: | |
| raise ValueError('Backup Recovery v6 snapshot is missing verified_target_ids') | |
| value = ext_deepcopy(snapshot) | |
| self.verified_target_ids = set(value.pop('verified_target_ids')) | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v5' | |
| value['provider_tools_sha256'] = 'b002266a4d83cff047d26f18419a42fdf3a6d9d38138d17c4fba7e36e3e4e3b8' | |
| self._backup_rule_successor_restore_5(value) | |
| def _backup_rule_successor_snapshot_5(self): | |
| value = self._backup_rule_successor_snapshot_6() | |
| value.update({'schema': 'rescopebench-backup-recovery-rule-stream/v5', 'rule_revalidation': ext_deepcopy(self.rule_revalidation), 'revalidation_targets': ext_deepcopy(self.revalidation_targets), 'episode_repository_sites': sorted(self._episode_repository_sites)}) | |
| return value | |
| def _backup_rule_successor_restore_5(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v5': | |
| raise ValueError('unsupported Backup Recovery v5 snapshot') | |
| for key in ('rule_revalidation', 'revalidation_targets', 'episode_repository_sites'): | |
| if key not in snapshot: | |
| raise ValueError(f'Backup Recovery v5 snapshot is missing {key}') | |
| value = ext_deepcopy(snapshot) | |
| self.rule_revalidation = ext_deepcopy(value.pop('rule_revalidation')) | |
| self.revalidation_targets = ext_deepcopy(value.pop('revalidation_targets')) | |
| self._episode_repository_sites = set(value.pop('episode_repository_sites')) | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v2' | |
| self._backup_rule_successor_restore_6(value) | |
| def _backup_rule_successor_snapshot_6(self): | |
| value = self._persistent_backup_recovery_adapter_snapshot() | |
| value['schema'] = 'rescopebench-backup-recovery-rule-stream/v2' | |
| value['provider_tools_sha256'] = 'b002266a4d83cff047d26f18419a42fdf3a6d9d38138d17c4fba7e36e3e4e3b8' | |
| return value | |
| def _backup_rule_successor_restore_6(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-rule-stream/v2': | |
| raise ValueError('unsupported Backup rule successor snapshot') | |
| value = ext_deepcopy(snapshot) | |
| value['schema'] = 'rescopebench-backup-recovery-stream-snapshot/v1' | |
| value.pop('provider_tools_sha256', None) | |
| self._persistent_backup_recovery_adapter_restore(value) | |
| def _persistent_backup_recovery_adapter_snapshot(self): | |
| value = self._backup_recovery_adapter_snapshot() | |
| value.update({'schema': 'rescopebench-backup-recovery-stream-snapshot/v1', 'activated_tasks': list(self._activated_tasks), 'applied_boundary_events': sorted(self._applied_boundary_events), 'active_event_start': self._active_event_start}) | |
| return value | |
| def _persistent_backup_recovery_adapter_restore(self, snapshot): | |
| if snapshot.get('schema') != 'rescopebench-backup-recovery-stream-snapshot/v1': | |
| raise ValueError('unsupported persistent stream snapshot schema') | |
| self._task_id = snapshot.get('task_id') | |
| self._task_targets = ext_deepcopy(snapshot.get('task_targets') 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._writes = int(snapshot.get('writes') or 0) | |
| self._initial_budget = int(snapshot.get('initial_budget') or 100) | |
| self._remaining = int(snapshot.get('remaining') or 0) | |
| self._policy_version = str(snapshot.get('policy_version') or 'protection-policy-v1') | |
| self._activated_tasks = list(snapshot.get('activated_tasks') or []) | |
| self._applied_boundary_events = set(snapshot.get('applied_boundary_events') or []) | |
| self._active_event_start = int(snapshot.get('active_event_start') or 0) | |
| def _backup_recovery_adapter_snapshot(self): | |
| return {'schema': 'rescopebench-backup-recovery-snapshot/v2', 'task_id': self._task_id, 'task_targets': ext_deepcopy(self._task_targets), 'entities': self._state.snapshot(), 'events': ext_deepcopy(self._events), 'calls': self._calls, 'writes': self._writes, 'initial_budget': self._initial_budget, 'remaining': self._remaining, 'policy_version': self._policy_version} | |
| 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 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(kept) != len(rows) | |
| def delete_many(self, entity_type, predicate): | |
| rows = self._entities.get(entity_type, []) | |
| kept = [row for row in rows if not predicate(ext_deepcopy(row))] | |
| 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) | |