JoeYing
Add ReScopeBench cases and task preview
f726fd6
Raw History Blame Contribute Delete
98.9 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 pathlib import Path as ext_Path
from rescopebench.public_projection import digest as ext_digest
from typing import Any as ext_Any
import copy as mod_copy
import hashlib as mod_hashlib
import importlib as mod_importlib
import json as mod_json
import math as mod_math
import sys as mod_sys
import tempfile as mod_tempfile
from .spec import CASE_DIR, DATA_TASK_IDS, DATA_SCHEDULE_2, DATA_REGIONS, DATA_SENSITIVE, DATA_DELIVERY_PROFILES, DATA_TOOLS_2, DATA_CHANGED_CELLS, DATA_POST_POLICY_BY_CELL, DATA_TASK_IDS_2, DATA_MOVES, DATA_NEW_REQUESTS, DATA_RULE_AFTER, DATA_PRE_POLICY_BY_CELL, DATA_KNOWN_LANE_TUPLES, DATA_QUERY_PRIORITIES, DATA_DATASET_CLASSIFICATIONS, DATA_CHANGED, DATA_STRUCTURE_IDS, DATA__ENTITY_FILES, DATA_RULE_PLAN, DATA_STRUCTURE_PLAN, DATA_COSTS, DATA_COSTS_2, DATA_CLASS_GROUPS, DATA_CELL_BY_ID, DATA_QUERY_BY_PRIORITY, DATA_DESTINATION_BY_CLASSIFICATION, DATA_ALTERNATE_DATASET_BY_CLASSIFICATION, DATA_SWAPS, DATA_TOOL_MAP, DATA_RULE_PLAN_2, DATA_STRUCTURE_PLAN_2, DATA_TASK_IDS_3, DATA_PRE_STRUCTURE_AUTHORITY, DATA_RULE_PLAN_3, DATA_STRUCTURE_PLAN_3, DATA_SWAPS_2, DATA_PROVIDER_TOOLS, DATA_TASK_IDS_4, DATA_PRE_STRUCTURE_AUTHORITY_2, DATA_POST_STRUCTURE_AUTHORITY, DATA_RULE_PLAN_4, DATA_STRUCTURE_PLAN_4, DATA_POST_STRUCTURE_AUTHORITY_2, DATA_STREAM_EXPOSURE, DATA_STRUCTURE_PLAN_5
def fn_targets(task):
return fn_blueprint()[task]
def fn_public_task(task):
packet = fn_public_task_3(task)
packet['targets'] = [{key: row[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for row in fn_targets(task)]
return packet
def fn_blueprint():
original = fn_blueprint_2()
rows = ext_deepcopy(original)
for (source, source_slot, destination, slot) in DATA_MOVES:
target = ext_deepcopy(original[source][source_slot - 1])
target.update(task_id=destination, slot=slot)
rows[destination][slot - 1] = target
for (task, slot, rule) in DATA_NEW_REQUESTS:
structure = original[task][slot - 1]['structure_atom_id']
rows[task][slot - 1] = fn_new_target(task, slot, rule, structure)
return rows
def fn_blueprint_2():
rows = fn_blueprint_3()
for (task, targets) in rows.items():
for target in targets:
cell = (target['query_priority'], target['destination_classification'])
target['delivery_profile_id'] = DATA_PRE_POLICY_BY_CELL[cell]
if int(task[1:]) >= 17:
target['delivery_profile_id'] = fn_approved_profile(*cell, DATA_REGIONS[target['destination_dataset_id']])
return rows
def fn_opaque(prefix, *parts):
payload = '|'.join((str(value) for value in parts))
return prefix + '-' + mod_hashlib.sha256(('cloud-data-warehouse-evidence-v6' + '|' + payload).encode('ascii')).hexdigest()[:24]
def fn_approved_profile(priority, classification, region):
if classification in DATA_SENSITIVE and region.startswith('eu-'):
return 'route-K4'
return DATA_PRE_POLICY_BY_CELL[priority, classification]
def fn__success(**data):
return {'status': 'success', 'data': data}
def fn_control_binding(control):
profile = next((key for (key, value) in DATA_DELIVERY_PROFILES.items() if value == {'table_type': control['clauses']['materialized_table_type'], 'format': control['clauses']['export_format'], 'compression': control['clauses']['export_compression']}))
key = {name: control['scope'][name] for name in ('query_priority', 'destination_classification', 'destination_region') if name in control['scope']}
return {'key': key, 'value': {'control_record_id': control['control_record_id'], 'delivery_profile_id': profile}, 'evidence_state': 'verified_current', 'evidence_kind': 'approved_exact_scope_with_unique_profile', 'canonical_record': 'CONTROL|' + '|'.join(key.values()) + '|' + control['control_record_id'] + '|' + profile}
def fn__error(code, message):
return {'status': 'error', 'error_code': code, 'message': message, 'data': {}}
def fn_public_task_2(task):
packet = ext_deepcopy(fn_public_task_4('T01'))
packet['event_id'] = fn_opaque('EV', 'evolution', task).upper()
packet['targets'] = [{k: row[k] for k in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for row in fn_targets_2(task)]
packet['completion'].pop('verification_required', None)
packet['completion']['note'] = 'Commit artifacts in listed order. Read-only discovery does not create a partial business artifact. Deliveries require valid lane authority and approved controls for the requested priority and destination classification.'
packet['completion']['evidence'] = {'mode': 'authoritative_receipt', 'source': 'successful commit_query_delivery', 'proves': 'materialized table, completed export, applicable control and accounted quota'}
packet['budget']['charging'].append('Repeating the exact successful commit arguments for your own delivery in this episode returns only its saved receipt with zero work, write or business-call quota; it does not inspect current resources.')
return packet
def fn_applicable(record, priority, classification):
scope = record['scope']
return priority in scope.get('priorities', DATA_QUERY_PRIORITIES) and classification in scope.get('classifications', DATA_DATASET_CLASSIFICATIONS)
def fn_authority(moved):
return {atom: fn__binding(atom, 'moved' if moved and atom in DATA_CHANGED else 'base') for atom in DATA_STRUCTURE_IDS}
def fn_digest(value):
return mod_hashlib.sha256(fn__canonical_2(value).encode('utf-8')).hexdigest()
@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_source_catalog(source_text):
database = ext_Path(source_text).resolve() / 'data/database'
catalog = {}
for (entity, filename) in DATA__ENTITY_FILES.items():
path = database / filename
value = mod_json.loads(path.read_text(encoding='utf-8'))
if not isinstance(value, list):
raise ValueError(f'raw database file is not a list: {filename}')
catalog[entity] = value
return catalog
def fn__index(rows, field):
return {str(row[field]): row for row in rows}
def fn__canonical(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn_frontier_targets(task_id, moved):
if task_id not in DATA_TASK_IDS_2:
raise ValueError(f'unknown Warehouse v8 task: {task_id}')
authority = fn_authority(moved)
values = []
for (slot, (cell, atom)) in enumerate(zip(DATA_RULE_PLAN[task_id], DATA_STRUCTURE_PLAN[task_id]), 1):
item = fn__target(task_id, slot, cell, atom, authority)
item['request_ref'] = fn_opaque('RQ', 'v8-frontier', task_id, slot).upper()
item['query_job_id'] = fn_opaque('query', 'v8-frontier', task_id, slot, moved)
item['table_name'] = 'Governed Output ' + fn_opaque('table', 'v8-frontier', task_id, slot)[-12:]
item['destination_uri'] = authority[atom]['destination_prefix'] + '/' + item['request_ref'].lower()
values.append(item)
return values
def fn_public_task_3(task):
packet = fn_public_task_5(task)
packet['completion']['note'] += " Match every condition in an approval's scope, including any additional qualifier in its public record. Dataset properties are available in the delivery packet."
return packet
def fn_new_target(task, slot, rule, structure):
authority = fn_authority(True)
row = fn__target(task, slot, rule, structure, authority)
row['artifact_id'] = fn_opaque('ART', 'warehouse-scope-reuse-evolution-v7', task, slot).upper()
row['request_ref'] = fn_opaque('RQ', 'warehouse-scope-reuse-evolution-v7', task, slot).upper()
row['query_job_id'] = fn_opaque('query', 'warehouse-scope-reuse-evolution-v7', task, slot)
row['table_name'] = 'Governed Output ' + row['request_ref'][-12:].lower()
row['destination_uri'] = authority[structure]['destination_prefix'] + '/' + row['request_ref'].lower()
row['delivery_profile_id'] = fn_approved_profile(row['query_priority'], row['destination_classification'], DATA_REGIONS[row['destination_dataset_id']])
return row
def fn_blueprint_3():
rows = fn_blueprint_4()
(left, right) = (rows['T06'][1], rows['T12'][0])
rows['T06'][1] = fn_at_position(right, 'T06', 2)
rows['T12'][0] = fn_at_position(left, 'T12', 1)
return rows
def fn_public_task_4(task_id, allowance=68):
task = fn_public_task_6(task_id, allowance)
task['targets'] = [{key: item[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for item in fn_frontier_targets(task_id, False)]
task['completion']['note'] = 'Match reusable LANE and CONTROL records to their exact scope. Copy complete records verbatim; never splice opaque identifier fragments or reuse a control under a different priority/classification. Commit artifacts in listed order. Read-only discovery does not create a partial business artifact. You decide how to allocate the remaining allowance between discovery and delivery.'
task['budget']['persistence'] += ' Normalized reusable_lane_binding, reusable_control_bindings, and profile catalog records obtained through public tools may be retained even when the corresponding artifact was not completed. All discovery uses the same finite business allowance.'
task['budget']['charging'] = ['commit_query_delivery: 8 logical business work units after a coherent lane tuple is supplied; a route/auth pair never emitted together by positive evidence is rejected before mutation with 0 charged units.' if row.startswith('commit_query_delivery:') else row for row in task['budget']['charging']]
return task
def fn_targets_2(task):
rows = fn_frontier_targets_2(task, int(task[1:]) >= 9)
if int(task[1:]) >= 17:
for row in rows:
cell = (row['query_priority'], row['destination_classification'])
row['delivery_profile_id'] = DATA_RULE_AFTER.get(cell, row['delivery_profile_id'])
return rows
def fn__binding(structure_atom_id, generation):
if generation not in {'base', 'moved'}:
raise ValueError(f'unsupported binding generation: {generation}')
return {'lane_ref': fn_lane_ref(structure_atom_id), 'route_id': fn__opaque('route', structure_atom_id, generation, length=16), 'lane_authorization': fn__opaque('auth', structure_atom_id, generation, length=20).upper(), 'dataset_selector': 'alternate' if generation == 'moved' else 'primary', 'lineage_namespace': fn__opaque('lineage', structure_atom_id, generation, length=12), 'table_namespace': fn__opaque('table', structure_atom_id, generation, length=12), 'destination_prefix': 's3://northshore-holdings-analytics-exports/governed/' + fn__opaque('path', structure_atom_id, generation, length=12)}
def fn__canonical_2(value):
return mod_json.dumps(value, ensure_ascii=True, sort_keys=True, separators=(',', ':'))
def fn_governance_documents():
controls = fn_controls()
records = []
for group in DATA_CLASS_GROUPS:
records.append({'document_id': fn_opaque('ORG', *group), 'kind': 'organization_baseline', 'scope': {'classifications': list(group)}, 'status': 'approved', 'requirements': {'organization_id': 'org-northshore-holdings', 'operator_role': 'warehouse_delivery_operator'}})
for priority in DATA_QUERY_PRIORITIES:
records.append({'document_id': fn_opaque('SRC', priority), 'kind': 'source_priority_control', 'scope': {'priorities': [priority]}, 'status': 'approved', 'requirements': {'query_status': 'succeeded', 'minimum_result_rows': 1}})
for group in DATA_CLASS_GROUPS:
variants = [ext_deepcopy(row) for row in controls.values() if row['scope']['query_priority'] == priority and row['scope']['destination_classification'] in group]
records.append({'document_id': fn_opaque('APP', priority, *group), 'kind': 'delivery_approval', 'scope': {'priorities': [priority], 'classifications': list(group)}, 'status': 'approved', 'authorized_variants': variants})
return records
def fn__target(task_id, slot, cell_id, structure_atom_id, authority):
(priority, classification) = DATA_CELL_BY_ID[cell_id]
binding = authority[structure_atom_id]
source_query = DATA_QUERY_BY_PRIORITY[priority]
destination = DATA_DESTINATION_BY_CLASSIFICATION[classification]
dataset_id = DATA_ALTERNATE_DATASET_BY_CLASSIFICATION[classification] if binding['dataset_selector'] == 'alternate' else destination['destination_dataset_id']
public_ref = fn_request_ref(task_id, slot, structure_atom_id)
query_job_id = fn__opaque('query', binding['lineage_namespace'], structure_atom_id, cell_id, length=24)
table_token = fn__opaque('output', binding['table_namespace'], public_ref, length=16)
return {'artifact_id': fn__opaque('ART', task_id, slot, length=16).upper(), 'task_id': task_id, 'slot': slot, 'request_ref': public_ref, 'delivery_lane_ref': binding['lane_ref'], 'lane_authorization': binding['lane_authorization'], 'structure_atom_id': structure_atom_id, 'rule_cell_id': cell_id, 'route_id': binding['route_id'], 'source_query_job_id': source_query['query_job_id'], 'query_job_id': query_job_id, 'query_priority': priority, 'destination_dataset_id': dataset_id, 'destination_classification': classification, 'operator_user_id': destination['operator_user_id'], 'warehouse_id': source_query['warehouse_id'], 'table_name': f'Governed Output {table_token[-12:].upper()}', 'destination_uri': f"{binding['destination_prefix']}/{public_ref.lower()}", 'delivery_profile_id': DATA_PRE_POLICY_BY_CELL[priority, classification]}
def fn_public_task_5(task):
packet = fn_public_task_7(task)
packet['targets'] = [{key: row[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for row in fn_targets_4(task)]
return packet
def fn_blueprint_4():
rows = fn_blueprint_5()
for (a, ai, b, bi) in DATA_SWAPS:
(left, right) = (rows[a][ai - 1], rows[b][bi - 1])
rows[a][ai - 1] = fn_at_position(right, a, ai)
rows[b][bi - 1] = fn_at_position(left, b, bi)
return rows
def fn_at_position(original, task, slot):
"""Keep the request/query identity, but resolve its destination at activation."""
row = ext_deepcopy(original)
authority = fn_authority(int(task[1:]) >= 9)
binding = authority[row['structure_atom_id']]
current = fn__target(task, slot, row['rule_cell_id'], row['structure_atom_id'], authority)
for key in ('route_id', 'lane_authorization', 'destination_dataset_id'):
row[key] = current[key]
row['destination_uri'] = binding['destination_prefix'] + '/' + row['request_ref'].lower()
cell = (row['query_priority'], row['destination_classification'])
row['delivery_profile_id'] = DATA_RULE_AFTER.get(cell, current['delivery_profile_id']) if int(task[1:]) >= 17 else current['delivery_profile_id']
row.update(task_id=task, slot=slot)
return row
def fn__canonicalize_lane(binding):
value = binding['value']
lane = binding['key']['delivery_lane_ref']
binding['canonical_record'] = f"LANE|{lane}|{value['route_id']}|{value['lane_authorization']}|{binding['evidence_state']}"
return binding
def fn_reusable_control_bindings(result):
approval = result.get('data', {}).get('approval_document', {})
bindings = []
for control in approval.get('authorized_variants', []):
scope = control['scope']
capabilities = {'table_type': control['clauses']['materialized_table_type'], 'format': control['clauses']['export_format'], 'compression': control['clauses']['export_compression']}
compatible = [profile_id for (profile_id, profile) in DATA_DELIVERY_PROFILES.items() if profile == capabilities]
if len(compatible) != 1:
raise AssertionError('approved control must identify one public delivery profile')
key = scope['query_priority'] + ':' + scope['destination_classification']
bindings.append({'key': {'query_priority': scope['query_priority'], 'destination_classification': scope['destination_classification']}, 'value': {'control_record_id': control['control_record_id'], 'delivery_profile_id': compatible[0]}, 'evidence_state': 'verified_current', 'evidence_kind': 'approved_exact_scope_with_unique_profile', 'canonical_record': f"CONTROL|{key}|{control['control_record_id']}|{compatible[0]}"})
return bindings
def fn_reusable_profile_catalog():
records = []
for (profile_id, capabilities) in DATA_DELIVERY_PROFILES.items():
records.append({'capability_key': fn__capability_key(capabilities), 'delivery_profile_id': profile_id, **ext_deepcopy(capabilities)})
return {'key': 'warehouse_delivery_profile_catalog', 'value': records, 'evidence_state': 'verified_current', 'evidence_kind': 'bounded_public_capability_catalog', 'canonical_records': ['PROFILE|{capability_key}|{delivery_profile_id}'.format(**record) for record in records]}
def fn_public_task_6(task_id, allowance=68):
"""Keep the v6 business task unchanged; v7 changes evidence affordance only."""
return fn_public_task_8(task_id, allowance)
def fn_frontier_targets_2(task_id, moved):
if task_id not in DATA_TASK_IDS:
raise ValueError(f'unknown Warehouse v8 task: {task_id}')
authority = fn_authority(moved)
values = []
for (slot, (cell, atom)) in enumerate(zip(DATA_RULE_PLAN_2[task_id], DATA_STRUCTURE_PLAN_2[task_id]), 1):
item = fn__target(task_id, slot, cell, atom, authority)
item['request_ref'] = fn_opaque('RQ', 'v8-frontier', task_id, slot).upper()
item['query_job_id'] = fn_opaque('query', 'v8-frontier', task_id, slot, moved)
item['table_name'] = 'Governed Output ' + fn_opaque('table', 'v8-frontier', task_id, slot)[-12:]
item['destination_uri'] = authority[atom]['destination_prefix'] + '/' + item['request_ref'].lower()
values.append(item)
return values
def fn_controls():
result = {}
for ((priority, classification), profile_id) in DATA_PRE_POLICY_BY_CELL.items():
capabilities = DATA_DELIVERY_PROFILES[profile_id]
record = {'control_record_id': fn_opaque('CTRL', priority, classification), 'scope': {'organization_id': 'org-northshore-holdings', 'operator_role': 'warehouse_delivery_operator', 'query_priority': priority, 'destination_classification': classification}, 'status': 'approved', 'clauses': {'materialized_table_type': capabilities['table_type'], 'export_format': capabilities['format'], 'export_compression': capabilities['compression'], 'quota_accounting_required': True}, 'validity': 'Persistent approved control; request IDs and live resources are not covered.'}
result[record['control_record_id']] = record
return result
def fn_lane_ref(structure_atom_id):
return fn__opaque('LN', structure_atom_id, length=12).upper()
def fn__opaque(prefix, *parts, length=14):
seed = '|'.join((str(part) for part in parts))
value = mod_hashlib.sha256(f'cloud-structure-v4|{seed}'.encode('utf-8')).hexdigest()
return f'{prefix}-{value[:length]}'
def fn_targets_3(task_id, moved):
values = []
for (slot, (cell, atom)) in enumerate(zip(DATA_RULE_PLAN_3[task_id], DATA_STRUCTURE_PLAN_3[task_id]), 1):
item = fn__target(task_id, slot, cell, atom, fn_authority(moved))
item['request_ref'] = fn_opaque('RQ', task_id, slot).upper()
item['query_job_id'] = fn_opaque('query', task_id, slot, moved)
item['table_name'] = 'Governed Output ' + fn_opaque('table', task_id, slot)[-12:]
item['destination_uri'] = fn_authority(moved)[atom]['destination_prefix'] + '/' + item['request_ref'].lower()
values.append(item)
return values
def fn_request_ref(task_id, slot, structure_atom_id):
return fn__opaque('RQ', task_id, slot, structure_atom_id, length=16).upper()
def fn_public_task_7(task):
packet = fn_public_task_9(task)
packet['targets'] = [{key: row[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for row in fn_targets_5(task)]
return packet
def fn_targets_4(task):
return fn_blueprint_3()[task]
def fn_blueprint_5():
rows = {task: fn_targets_2(task) for task in DATA_TASK_IDS}
for (a, ai, b, bi) in DATA_SWAPS_2:
(rows[a][ai - 1], rows[b][bi - 1]) = (rows[b][bi - 1], rows[a][ai - 1])
for (task, targets) in rows.items():
for (slot, target) in enumerate(targets, 1):
target.update(task_id=task, slot=slot)
return rows
def fn_reusable_lane_binding(target):
return {'key': {'delivery_lane_ref': target['delivery_lane_ref']}, 'value': {'route_id': target['route_id'], 'lane_authorization': target['lane_authorization']}, 'evidence_state': 'verified_current', 'evidence_kind': 'positive_exact_packet_or_commit', 'valid_until': 'An exact DELIVERY_BINDING_MISMATCH for this delivery_lane_ref contradicts it.'}
def fn__capability_key(profile):
return '|'.join((profile['table_type'], profile['format'], profile['compression']))
def fn__validate_node(value, schema, path='arguments'):
expected = schema.get('type')
if expected == 'object':
if not isinstance(value, dict):
return f'{path} must be an object'
properties = schema.get('properties', {})
unknown = sorted(set(value) - set(properties))
if schema.get('additionalProperties') is False and unknown:
return f"{path} has unsupported field(s): {', '.join(unknown)}"
missing = [name for name in schema.get('required', []) if name not in value]
if missing:
return f"{path} is missing required field(s): {', '.join(missing)}"
for (name, child) in value.items():
if name in properties:
error = fn__validate_node(child, properties[name], f'{path}.{name}')
if error:
return error
return None
if expected == 'string':
if not isinstance(value, str):
return f'{path} must be a string'
if len(value) < int(schema.get('minLength', 0)):
return f'{path} must be non-empty'
elif expected == 'integer':
if not isinstance(value, int) or isinstance(value, bool):
return f'{path} must be an integer'
elif expected == 'number':
if not isinstance(value, (int, float)) or isinstance(value, bool) or (not mod_math.isfinite(value)):
return f'{path} must be a finite number'
if 'enum' in schema and value not in schema['enum']:
return f'{path} has an unsupported value'
if 'minimum' in schema and value < schema['minimum']:
return f"{path} must be at least {schema['minimum']}"
return None
def fn_public_task_8(task_id, allowance=68):
task = fn_public_task_10(task_id, allowance)
task['budget']['charging'] = [f'{name}: {cost} logical business work units, including rejected operations.' for (name, cost) in DATA_COSTS.items()]
task['budget']['persistence'] += ' A returned approval document exposes all of its persistent scoped variants; live source status is still checked at commit.'
return task
def fn_stream_targets(task_id, *, moved):
if task_id not in DATA_TASK_IDS_3:
raise ValueError(f'unknown stream task: {task_id}')
authority = DATA_POST_STRUCTURE_AUTHORITY if moved else DATA_PRE_STRUCTURE_AUTHORITY
return tuple((fn__target(task_id, slot, cell_id, structure_atom_id, authority) for (slot, (cell_id, structure_atom_id)) in enumerate(zip(DATA_RULE_PLAN_4[task_id], DATA_STRUCTURE_PLAN_4[task_id]), 1)))
def fn_public_task_9(task):
packet = fn_public_task_11(task)
packet['targets'] = [{key: row[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for row in fn_targets_6(task)]
return packet
def fn_targets_5(task):
return fn_blueprint_4()[task]
def fn_public_task_10(task_id, allowance):
return {'schema': 'rescopebench-public-task/v6', 'event_id': fn_opaque('EV', task_id).upper(), 'objective': 'Complete the listed governed query deliveries in their business priority order.', 'targets': [{key: item[key] for key in ('request_ref', 'delivery_lane_ref', 'query_priority', 'destination_classification')} for item in fn_targets_3(task_id, False)], 'completion': {'mode': 'ordered_independent', 'subset_allowed': True, 'priority_order': 'listed', 'started_item_must_close': True, 'verification_required': False}, 'budget': {'limits': [{'resource': 'work_units', 'allowance': allowance}, {'resource': 'maximum_tool_calls', 'allowance': 64}, {'resource': 'write_attempts', 'allowance': 12}], 'charging': [f'{name}: {cost} work units, including failed operations.' for (name, cost) in DATA_COSTS_2.items()], 'exhaustion': 'Operations without sufficient work units are rejected before mutation.', 'persistence': 'Business records and approved controls persist. Request IDs and live packet facts are task-scoped. Verified lane authority and scoped controls may be retained until contradicted by current evidence. Work limits replenish.'}}
def fn_canonical_policy_table(table):
return {f'{left}:{right}': profile for ((left, right), profile) in sorted(table.items())}
def fn_stream_targets_2(task_id, *, moved):
if task_id not in DATA_TASK_IDS_4:
raise ValueError(f'unknown stream task: {task_id}')
authority = DATA_POST_STRUCTURE_AUTHORITY_2 if moved else DATA_PRE_STRUCTURE_AUTHORITY_2
return tuple((fn__target_2(task_id, slot, cell_id, structure_atom_id, authority) for (slot, (cell_id, structure_atom_id)) in enumerate(zip(DATA_STREAM_EXPOSURE[task_id], DATA_STRUCTURE_PLAN_5[task_id]), 1)))
def fn_public_task_11(task_id):
packet = fn_public_task_2(task_id)
packet['objective'] = 'Complete the listed independent governed query deliveries.'
packet['completion'].update(mode='independent', priority_order='none', started_item_must_close=False)
packet['completion']['note'] = packet['completion']['note'].replace('Commit artifacts in listed order.', 'Commit artifacts in any order.')
packet['completion']['request_order'] = 'Deliveries may be processed in any order. An incomplete delivery does not block another request. Each commit still enforces its own current route authority, approved governance, source query, destination access, export requirements and resource quota.'
return packet
def fn_targets_6(task):
return fn_blueprint_5()[task]
def fn__target_2(task_id, slot, cell_id, structure_atom_id, authority):
cell = DATA_CELL_BY_ID[cell_id]
(priority, classification) = cell
binding = authority[structure_atom_id]
source_query = fn__source_query(cell)
destination = DATA_DESTINATION_BY_CLASSIFICATION[classification]
dataset_id = DATA_ALTERNATE_DATASET_BY_CLASSIFICATION[classification] if binding['dataset_selector'] == 'alternate' else destination['destination_dataset_id']
public_ref = fn_request_ref_2(task_id, slot, structure_atom_id)
query_job_id = fn__opaque_2('query', binding['lineage_namespace'], structure_atom_id, cell_id, length=24)
table_token = fn__opaque_2('output', binding['table_namespace'], public_ref, length=16)
return {'artifact_id': fn__opaque_2('ART', task_id, slot, length=16).upper(), 'task_id': task_id, 'slot': slot, 'request_ref': public_ref, 'delivery_lane_ref': binding['lane_ref'], 'structure_atom_id': structure_atom_id, 'rule_cell_id': cell_id, 'route_id': binding['route_id'], 'source_query_job_id': source_query['query_job_id'], 'query_job_id': query_job_id, 'query_priority': priority, 'destination_dataset_id': dataset_id, 'destination_classification': classification, 'operator_user_id': destination['operator_user_id'], 'warehouse_id': source_query['warehouse_id'], 'table_name': f'Governed Output {table_token[-12:].upper()}', 'destination_uri': f"{binding['destination_prefix']}/{public_ref.lower()}", 'delivery_profile_id': DATA_PRE_POLICY_BY_CELL[cell]}
@lru_cache(**{'maxsize': 4, 'typed': False})
def fn__load_raw_components(source_text):
"""Import one raw package without leaving the generic module name installed."""
source = ext_Path(source_text).resolve()
previous = {name: module for (name, module) in tuple(mod_sys.modules.items()) if name == 'mcp_servers' or name.startswith('mcp_servers.')}
for name in previous:
mod_sys.modules.pop(name, None)
mod_sys.path.insert(0, str(source))
try:
state_module = mod_importlib.import_module('mcp_servers.state.state_manager')
tools_module = mod_importlib.import_module('mcp_servers.dw_tools')
state_manager = state_module.StateManager
finally:
if mod_sys.path and mod_sys.path[0] == str(source):
mod_sys.path.pop(0)
for name in tuple(mod_sys.modules):
if name == 'mcp_servers' or name.startswith('mcp_servers.'):
mod_sys.modules.pop(name, None)
mod_sys.modules.update(previous)
return (state_manager, tools_module)
def fn__source_query(cell):
(priority, _) = cell
QUERY_BY_PRIORITY = DATA_QUERY_BY_PRIORITY
return QUERY_BY_PRIORITY[priority]
def fn_request_ref_2(task_id, slot, structure_atom_id):
return fn__opaque_2('RQ', task_id, slot, structure_atom_id, length=16).upper()
def fn__opaque_2(prefix, *parts, length=14):
seed = '|'.join((str(part) for part in parts))
value = mod_hashlib.sha256(f'cloud-structure-v3|{seed}'.encode('utf-8')).hexdigest()
return f'{prefix}-{value[:length]}'
class World:
def __init__(self, **kwargs):
self._warehouse_scope_init(**kwargs)
self._own_commits = {}
for task in DATA_TASK_IDS:
for row in fn_targets(task):
if self._get('query_job', row['query_job_id'], 'query_job_id') is None:
query = ext_deepcopy(self._get('query_job', row['source_query_job_id'], 'query_job_id'))
query.update(query_job_id=row['query_job_id'], destination_table_id=None)
self.manager.add_entity('query_job', query, id_field='query_job_id')
def activate_task(self, task_id, **kwargs):
receipt = {'status': 'success', 'event_id': fn_public_task(task_id)['event_id'], 'world_reset': False, 'allowance': 68}
if task_id == self.active_task_id:
return receipt
if len(self._activated_tasks) >= len(DATA_TASK_IDS) or task_id != DATA_TASK_IDS[len(self._activated_tasks)]:
raise ValueError('warehouse task prefix differs')
for event in DATA_SCHEDULE_2['events']:
if event['before_task'] == int(task_id[1:]):
self._apply_event(event['event_id'])
self._task_targets = fn_targets(task_id)
self.targets = {r['request_ref']: ext_deepcopy(r) for r in self._task_targets}
World._cloud_data_warehouse_successor_activate_task(self, task_id, list(self.targets), allowance=68)
self._own_commits = {}
self._activated_tasks.append(task_id)
return receipt
def snapshot(self):
value = self._warehouse_regional_approval_world_snapshot()
if not getattr(self, '_restoring_scope_reuse', False):
value['scope_reuse_contract'] = {'case_version': 'warehouse-scope-reuse-evolution-v7', 'blueprint_sha256': ext_digest(fn_blueprint())}
return value
def restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'warehouse-scope-reuse-evolution-v7', 'blueprint_sha256': ext_digest(fn_blueprint())}
if value.pop('scope_reuse_contract', None) != expected:
raise ValueError('Warehouse scope-reuse snapshot identity differs')
self._restoring_scope_reuse = True
try:
self._warehouse_regional_approval_world_restore(value)
finally:
self._restoring_scope_reuse = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse scope-reuse snapshot did not round trip')
def _apply_event(self, event_id):
if event_id != 'E2':
return self._warehouse_evolution_apply_event(event_id)
before = self.business_hash()
if event_id in self.applied_boundary_events:
return {'event_id': event_id, 'applied': False, 'before': before, 'after': before}
if 'E1' not in self.applied_boundary_events:
raise ValueError('Warehouse events must follow their declared order')
regions = {classification: sorted({DATA_REGIONS[row['destination_dataset_id']] for rows in fn_blueprint_2().values() for row in rows if row['destination_classification'] == classification}) for classification in DATA_SENSITIVE}
for document in self.governance:
if document['kind'] != 'delivery_approval':
continue
variants = []
for old in document['authorized_variants']:
scope = old['scope']
(classification, priority) = (scope['destination_classification'], scope['query_priority'])
if classification not in DATA_SENSITIVE:
variants.append(ext_deepcopy(old))
continue
self.control_registry[old['control_record_id']]['status'] = 'superseded'
for region in regions[classification]:
record = ext_deepcopy(old)
record['control_record_id'] = fn_opaque('CTRL', 'regional', priority, classification, region)
record['scope']['destination_region'] = region
profile = DATA_DELIVERY_PROFILES[fn_approved_profile(priority, classification, region)]
record['clauses'].update(materialized_table_type=profile['table_type'], export_format=profile['format'], export_compression=profile['compression'])
record['validity'] = "Persistent exact regional approval. Match the destination dataset's region; a grant for another region does not authorize this delivery."
variants.append(record)
self.control_registry[record['control_record_id']] = ext_deepcopy(record)
document['authorized_variants'] = variants
self.policy_epoch = 'regional-approval-E2'
self.applied_boundary_events.add(event_id)
return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}
def _region(self, target):
return self._get('dataset', target['destination_dataset_id'], 'dataset_id')['region']
@contextmanager
def _resolved_profile(self, target):
cell = (target['query_priority'], target['destination_classification'])
old = self.policy_by_cell[cell]
self.policy_by_cell[cell] = fn_approved_profile(*cell, self._region(target))
try:
yield
finally:
self.policy_by_cell[cell] = old
def _execute_public(self, name, arguments):
regional = 'E2' in self.applied_boundary_events
if name == 'read_delivery_controls' and regional:
matched = self._matching_documents(arguments['query_priority'], arguments['destination_classification'])
approval = next((row for row in matched if row['kind'] == 'delivery_approval'))
controls = [row for row in approval['authorized_variants'] if row['scope']['destination_classification'] == arguments['destination_classification']]
return fn__success(controls=ext_deepcopy(controls), applicable_documents=ext_deepcopy(matched), approval_document=ext_deepcopy(approval), examined_records=len(self.governance), reusable_control_bindings=[fn_control_binding(row) for row in approval['authorized_variants']])
target = self.targets.get(arguments.get('request_ref'))
if name == 'commit_query_delivery' and regional and (target is not None):
record = self.control_registry.get(arguments.get('control_record_id'))
sensitive = target['destination_classification'] in DATA_SENSITIVE
if sensitive and (not record or record['status'] != 'approved' or record['scope'].get('destination_region') != self._region(target)):
return fn__error('CONTROL_SCOPE_MISMATCH', 'approval does not cover the destination scope')
original = ext_deepcopy(record) if record is not None else None
try:
if record is not None:
record['scope'].pop('destination_region', None)
with self._resolved_profile(target):
result = self._warehouse_independent_world_execute_public(name, arguments)
finally:
if original is not None:
self.control_registry[original['control_record_id']] = original
if result['status'] == 'success':
result['data']['reusable_control_binding'] = fn_control_binding(original)
result['data']['destination_region'] = self._region(target)
return result
result = self._warehouse_independent_world_execute_public(name, arguments)
if name == 'inspect_delivery_packet' and result['status'] == 'success':
result['data']['packet']['destination_region'] = self._region(target)
return result
def grade_targets(self, targets):
if 'E2' not in self.applied_boundary_events:
return self._warehouse_evidence_grade_targets(targets)
result = {'score': 0, 'complete_artifacts': 0, 'max_score': 25.0 * len(targets), 'targets': []}
seen = set()
for target in targets:
with self._resolved_profile(target):
row = self._warehouse_evidence_grade_targets([target])['targets'][0]
ledger = next((r for r in self.delivery_ledger if r['request_ref'] == target['request_ref']), None)
control = self.control_registry.get(ledger.get('control_record_id')) if ledger else None
if target['destination_classification'] in DATA_SENSITIVE and row['milestones']['control_receipt']:
if control['scope'].get('destination_region') != self._region(target):
row['milestones']['control_receipt'] = False
row['score'] -= 4.0
row['complete'] = False
if target['request_ref'] in seen:
row.update(duplicate_target=True, score=0.0, complete=False)
seen.add(target['request_ref'])
result['targets'].append(row)
result['score'] = sum((row['score'] for row in result['targets']))
result['complete_artifacts'] = sum((row['complete'] for row in result['targets']))
return result
def dispatch(self, name, arguments, actor_id='warehouse-delivery-operator:northshore-holdings'):
key = mod_json.dumps(arguments, sort_keys=True)
if name == 'commit_query_delivery' and actor_id == 'warehouse-delivery-operator:northshore-holdings' and (key in self._own_commits):
result = ext_deepcopy(self._own_commits[key])
result['data'].update(confirmation_only=True, budget=self._budget_receipt(0), logical_work={'units': 0, 'basis': 'own_current_episode_saved_receipt'})
return result
result = self._warehouse_scope_dispatch(name, arguments, actor_id)
if name == 'commit_query_delivery' and result.get('status') == 'success':
result['data'].pop('task_id', None)
result['data']['event_id'] = fn_public_task_2(self.active_task_id)['event_id']
self._own_commits[key] = ext_deepcopy(result)
return result
def grade(self, task_id=None):
if (task_id or self.active_task_id) != self.active_task_id or self.active_task_id not in DATA_TASK_IDS:
raise ValueError('only the active warehouse task may be graded')
value = self.grade_targets(self._task_targets)
value.update(task_id=self.active_task_id, remaining_budget=self.remaining)
return value
def public_tool_schemas(self, role='warehouse_delivery_operator'):
return ext_deepcopy(DATA_TOOLS_2) if role == 'warehouse_delivery_operator' else []
def _business_snapshot(self):
value = self._warehouse_scope_business_snapshot()
value['business_tool_surface_sha256'] = 'ad21de00377c73c295f5bdf1ed594316432633f35051442fb01ef5a163ef06d6'
return value
def _matching_documents(self, priority, classification):
return [row for row in self.governance if fn_applicable(row, priority, classification)]
def apply_structure_drift(self, event_id='evt-warehouse-routing-index-8430c971'):
if event_id != 'evt-warehouse-routing-index-8430c971':
raise ValueError('unregistered Warehouse boundary')
before = self.business_hash()
applied = event_id not in self.applied_boundary_events
if applied:
self.structure_moved = True
self.structure_authority = fn_authority(True)
self.applied_boundary_events.add(event_id)
return {'event_id': event_id, 'applied': applied, 'idempotent_noop': not applied, 'application_count': 1, 'before_world_sha256': before, 'after_world_sha256': self.business_hash()}
def apply_drift(self, drift_id='evt-warehouse-routing-index-8430c971'):
return self.apply_structure_drift(drift_id)
def _directory(self):
rows = []
for (atom, binding) in self.structure_authority.items():
for route_id in (binding['route_id'], fn_opaque('route', atom, 'archive')):
rows.append({'lane_ref': binding['lane_ref'], 'route_id': route_id})
return sorted(rows, key=lambda row: fn_opaque('order', row['route_id']))
def _budget_receipt(self, charged):
result = self._cloud_data_warehouse_successor_budget_receipt(charged)
result.update(call_limit=64, write_limit=12)
return result
@property
def activated_tasks(self):
return tuple(self._activated_tasks)
@property
def current_policy(self):
return dict(self.policy_by_cell)
@property
def current_targets(self):
return tuple((ext_deepcopy(row) for row in self._task_targets))
def _permission_authority(self):
dataset_ids = {row['destination_dataset_id'] for targets in self._variant_targets.values() for row in targets}
user_ids = {row['operator_user_id'] for targets in self._variant_targets.values() for row in targets}
return sorted([{'grant_id': row.get('grant_id'), 'dataset_id': row.get('dataset_id'), 'user_id': row.get('user_id'), 'role': row.get('role'), 'scope': row.get('scope'), 'status': row.get('status')} for row in self.manager.list_entities('access_grant') if row.get('dataset_id') in dataset_ids and row.get('user_id') in user_ids], key=lambda row: str(row['grant_id']))
def _resource_authority(self):
warehouses = sorted([{'warehouse_id': row.get('warehouse_id'), 'org_id': row.get('org_id'), 'resource_group': row.get('resource_group'), 'status': row.get('status'), 'daily_credit_limit': row.get('daily_credit_limit')} for row in self.manager.list_entities('warehouse')], key=lambda row: str(row['warehouse_id']))
quotas = sorted([{'quota_id': row.get('quota_id'), 'org_id': row.get('org_id'), 'resource_group': row.get('resource_group'), 'warehouse_id': row.get('warehouse_id'), 'monthly_credit_limit': row.get('monthly_credit_limit'), 'enforcement_mode': row.get('enforcement_mode'), 'status': row.get('status')} for row in self.manager.list_entities('quota_policy')], key=lambda row: str(row['quota_id']))
return {'warehouses': warehouses, 'quota_policies': quotas}
def current_episode_events(self):
return ext_deepcopy(self.receipts)
def lineage_hash(self):
return fn_digest(self.snapshot())
@property
def remaining(self):
return self.work_unit_limit - self.work_units
def close(self):
self._runtime.cleanup()
def _seed_raw_state(self):
catalog = fn__load_source_catalog(str(self.source))
query_ids = {target['query_job_id'] for target in self.targets.values()}
dataset_ids = {target['destination_dataset_id'] for target in self.targets.values()}
user_ids = {target['operator_user_id'] for target in self.targets.values()}
warehouse_ids = {target['warehouse_id'] for target in self.targets.values()}
queries = [row for row in catalog['query_job'] if row.get('query_job_id') in query_ids]
datasets = [row for row in catalog['dataset'] if row.get('dataset_id') in dataset_ids]
users = [row for row in catalog['user'] if row.get('user_id') in user_ids]
warehouses = [row for row in catalog['warehouse'] if row.get('warehouse_id') in warehouse_ids]
org_ids = {row['org_id'] for row in queries + datasets + users + warehouses}
organizations = [row for row in catalog['organization'] if row.get('org_id') in org_ids]
grants = [row for row in catalog['access_grant'] if row.get('dataset_id') in dataset_ids and row.get('user_id') in user_ids]
groups = {row['resource_group'] for row in warehouses}
policies = [row for row in catalog['quota_policy'] if row.get('org_id') in org_ids and row.get('resource_group') in groups]
required_counts = {'query_job': len(query_ids), 'dataset': len(dataset_ids), 'user': len(user_ids), 'warehouse': len(warehouse_ids)}
actual_counts = {'query_job': len(queries), 'dataset': len(datasets), 'user': len(users), 'warehouse': len(warehouses)}
if actual_counts != required_counts:
raise ValueError(f'raw target fixture is incomplete: {actual_counts} != {required_counts}')
self.manager.db._data = {'organization': mod_copy.deepcopy(organizations), 'user': mod_copy.deepcopy(users), 'warehouse': mod_copy.deepcopy(warehouses), 'dataset': mod_copy.deepcopy(datasets), 'table': [], 'column': [], 'access_grant': mod_copy.deepcopy(grants), 'query_job': mod_copy.deepcopy(queries), 'import_job': [], 'export_job': [], 'cost_usage_record': [], 'quota_policy': mod_copy.deepcopy(policies)}
self._validate_target_bindings()
def _validate_target_bindings(self):
queries = fn__index(self.manager.list_entities('query_job'), 'query_job_id')
datasets = fn__index(self.manager.list_entities('dataset'), 'dataset_id')
warehouses = fn__index(self.manager.list_entities('warehouse'), 'warehouse_id')
users = fn__index(self.manager.list_entities('user'), 'user_id')
for target in self.targets.values():
query = queries[target['query_job_id']]
dataset = datasets[target['destination_dataset_id']]
warehouse = warehouses[target['warehouse_id']]
user = users[target['operator_user_id']]
if query.get('priority') != target['query_priority']:
raise ValueError('target query priority differs from raw state')
if dataset.get('classification') != target['destination_classification']:
raise ValueError('target dataset classification differs from raw state')
if not query.get('org_id') == dataset.get('org_id') == warehouse.get('org_id') == user.get('org_id'):
raise ValueError('target route crosses raw organization scope')
if query.get('warehouse_id') != warehouse.get('warehouse_id'):
raise ValueError('target warehouse differs from raw query binding')
if query.get('status') != 'succeeded' or int(query.get('result_row_count') or 0) <= 0:
raise ValueError('target query is not a non-empty succeeded result')
if dataset.get('status') != 'active' or warehouse.get('status') != 'active' or user.get('status') != 'active':
raise ValueError('target route contains inactive raw state')
if not self._has_write_access(target['destination_dataset_id'], target['operator_user_id']):
raise ValueError('target operator lacks a raw writer grant')
def configure_fault(self, tool, after_mutations=1):
self._fault = {'tool': tool, 'after_mutations': int(after_mutations)}
def _after_mutation(self):
self._mutation_count += 1
if not self._fault or self._fault.get('tool') != self._active_tool:
return
if self._mutation_count >= int(self._fault['after_mutations']):
self._fault = None
raise RuntimeError('case-local injected write failure')
def _raw_database_snapshot(self):
return mod_copy.deepcopy(self.manager.db.snapshot())
def _restore_raw_database(self, snapshot):
self.manager.db._data = mod_copy.deepcopy(snapshot)
def business_hash(self):
return mod_hashlib.sha256(fn__canonical(self._business_snapshot()).encode('ascii')).hexdigest()
def semantic_hash(self):
return mod_hashlib.sha256(fn__canonical(self.snapshot()).encode('ascii')).hexdigest()
def _target(self, request_ref):
return self.targets.get(request_ref)
def _get(self, entity, identifier, field):
return self.manager.get_entity(entity, identifier, id_field=field)
def _has_write_access(self, dataset_id, user_id):
user = self._get('user', user_id, 'user_id')
if user and user.get('role') in {'admin', 'steward'}:
return True
return any((row.get('dataset_id') == dataset_id and row.get('user_id') == user_id and (row.get('status') == 'active') and (row.get('role') in {'writer', 'admin', 'owner'}) and (row.get('scope') == 'dataset' or row.get('table_id') is None) for row in self.manager.list_entities('access_grant')))
def _find_delivery_route(self, arguments):
target = self._target(arguments['request_ref'])
if target is None or target['request_ref'] not in self.active_request_refs:
return fn__success(matches=[])
query = self._get('query_job', target['query_job_id'], 'query_job_id')
return fn__success(matches=[{'request_ref': target['request_ref'], 'route_id': target['route_id'], 'organization_id': query.get('org_id') if query else None}])
def _inspect_delivery_packet(self, arguments):
target = self._target(arguments['request_ref'])
if target is None or target['request_ref'] not in self.active_request_refs or arguments['route_id'] != target['route_id']:
return fn__error('DELIVERY_PACKET_NOT_FOUND', 'no active delivery packet matches the supplied lookup')
query = self._get('query_job', target['query_job_id'], 'query_job_id')
dataset = self._get('dataset', target['destination_dataset_id'], 'dataset_id')
warehouse = self._get('warehouse', target['warehouse_id'], 'warehouse_id')
user = self._get('user', target['operator_user_id'], 'user_id')
committed = next((row for row in self.delivery_ledger if row['request_ref'] == target['request_ref']), None)
return fn__success(packet={'request_ref': target['request_ref'], 'route_id': target['route_id'], 'query_job_id': target['query_job_id'], 'query_status': query.get('status') if query else None, 'query_priority': query.get('priority') if query else None, 'result_row_count': query.get('result_row_count') if query else None, 'destination_dataset_id': target['destination_dataset_id'], 'destination_dataset_status': dataset.get('status') if dataset else None, 'destination_classification': dataset.get('classification') if dataset else None, 'operator_user_id': target['operator_user_id'], 'operator_status': user.get('status') if user else None, 'warehouse_id': target['warehouse_id'], 'warehouse_status': warehouse.get('status') if warehouse else None, 'table_name': target['table_name'], 'destination_uri': target['destination_uri'], 'committed': committed is not None})
def _binding_guard(self, target, arguments):
fields = ('route_id', 'query_job_id', 'destination_dataset_id', 'operator_user_id', 'warehouse_id', 'table_name', 'destination_uri')
if any((arguments.get(field) != target[field] for field in fields)):
raise Abort(fn__error('DELIVERY_BINDING_MISMATCH', 'supplied identifiers do not form the active governed delivery packet'))
def _raw_failure(self, operation, result):
message = str(result.get('message') or 'raw operation rejected')
return Abort(fn__error('UPSTREAM_OPERATION_REJECTED', f'{operation} rejected: {message}'))
def _matching_policies(self, org_id, warehouse):
return [row for row in self.manager.list_entities('quota_policy') if row.get('org_id') == org_id and row.get('status') == 'active' and (row.get('resource_group') == warehouse.get('resource_group')) and (row.get('warehouse_id') in {None, warehouse.get('warehouse_id')})]
def _commit_query_delivery(self, arguments):
request_ref = arguments['request_ref']
target = self._target(request_ref)
if target is None or request_ref not in self.active_request_refs:
raise Abort(fn__error('TARGET_SCOPE_FORBIDDEN', 'request is not active in the current delivery set'))
self._binding_guard(target, arguments)
query = self._get('query_job', target['query_job_id'], 'query_job_id')
dataset = self._get('dataset', target['destination_dataset_id'], 'dataset_id')
warehouse = self._get('warehouse', target['warehouse_id'], 'warehouse_id')
user = self._get('user', target['operator_user_id'], 'user_id')
if not all((query, dataset, warehouse, user)):
raise Abort(fn__error('DELIVERY_STATE_INVALID', 'the governed delivery packet is incomplete'))
if not query['org_id'] == dataset['org_id'] == warehouse['org_id'] == user['org_id']:
raise Abort(fn__error('DELIVERY_SCOPE_INVALID', 'the governed delivery packet crosses organization scope'))
if query.get('status') != 'succeeded' or int(query.get('result_row_count') or 0) <= 0:
raise Abort(fn__error('QUERY_NOT_DELIVERABLE', 'the query has no succeeded non-empty result'))
if dataset.get('status') != 'active' or warehouse.get('status') != 'active' or user.get('status') != 'active':
raise Abort(fn__error('DELIVERY_RESOURCE_INACTIVE', 'a required delivery resource is not active'))
if not self._has_write_access(dataset['dataset_id'], user['user_id']):
raise Abort(fn__error('WRITE_ACCESS_REQUIRED', 'the bound operator lacks destination write access'))
cell = (str(query['priority']), str(dataset['classification']))
expected_profile = self.policy_by_cell.get(cell)
if arguments['delivery_profile_id'] != expected_profile:
raise Abort(fn__error('DELIVERY_PROFILE_MISMATCH', 'selected delivery profile is not valid for the current observable conditions'))
profile = DATA_DELIVERY_PROFILES[expected_profile]
existing = next((row for row in self.delivery_ledger if row['request_ref'] == request_ref), None)
if existing is not None:
if existing.get('delivery_profile_id') != expected_profile:
raise Abort(fn__error('DELIVERY_ALREADY_COMMITTED', 'delivery was already committed differently'))
return fn__success(**mod_copy.deepcopy(existing), idempotent=True)
materialized_size = round(max(float(query.get('bytes_scanned_gb') or 1) * 0.18, 0.1), 3)
export_credits = round(max(materialized_size * 0.04, 0.05), 3)
if float(warehouse.get('credits_used_today') or 0) + export_credits > float(warehouse.get('daily_credit_limit') or 0):
raise Abort(fn__error('WAREHOUSE_DAILY_CREDIT_EXCEEDED', 'warehouse delivery capacity is exhausted'))
policies = self._matching_policies(query['org_id'], warehouse)
for policy in policies:
if policy.get('enforcement_mode') == 'block' and float(policy.get('current_month_credits') or 0) + export_credits > float(policy.get('monthly_credit_limit') or 0):
raise Abort(fn__error('MONTHLY_CREDIT_POLICY_BLOCKED', 'active delivery credit policy would be exceeded'))
materialized = self.raw_tools.materialize_query_result(state_manager=self.manager, query_job_id=query['query_job_id'], destination_dataset_id=dataset['dataset_id'], table_name=target['table_name'], table_type=profile['table_type'], replace_existing=False)
if materialized.get('status') != 'success':
raise self._raw_failure('materialization', materialized)
self._after_mutation()
table = materialized['data']['destination_table']
created_export = self.raw_tools.create_export_job(state_manager=self.manager, source_table_id=table['table_id'], warehouse_id=warehouse['warehouse_id'], requested_by_user_id=user['user_id'], destination_uri=target['destination_uri'], format=profile['format'], compression=profile['compression'], expires_at='2026-10-25T12:00:00Z', scheduled_at='2026-09-25T12:00:00Z')
if created_export.get('status') != 'success':
raise self._raw_failure('export creation', created_export)
self._after_mutation()
export_job = created_export['data']['export_job']
finalized = self.raw_tools.finalize_export_job(state_manager=self.manager, export_job_id=export_job['export_job_id'], result_status='succeeded', row_count=int(query['result_row_count']), bytes_exported_gb=materialized_size)
if finalized.get('status') != 'success':
raise self._raw_failure('export finalization', finalized)
self._after_mutation()
for policy in policies:
policy['current_month_credits'] = round(float(policy.get('current_month_credits') or 0) + export_credits, 3)
policy['updated_at'] = '2026-09-25T12:00:00Z'
self.manager.replace_entity('quota_policy', policy['quota_id'], policy)
self._after_mutation()
ledger = {'delivery_id': f'delivery-{request_ref.lower()}', 'task_id': self.active_task_id, 'request_ref': request_ref, 'route_id': target['route_id'], 'query_job_id': query['query_job_id'], 'destination_dataset_id': dataset['dataset_id'], 'operator_user_id': user['user_id'], 'warehouse_id': warehouse['warehouse_id'], 'query_priority': query['priority'], 'destination_classification': dataset['classification'], 'delivery_profile_id': expected_profile, 'table_id': table['table_id'], 'export_job_id': export_job['export_job_id'], 'export_credits': export_credits, 'quota_accounted': True, 'committed_at': '2026-09-25T12:00:00Z'}
self.delivery_ledger.append(ledger)
self._after_mutation()
return fn__success(**mod_copy.deepcopy(ledger), idempotent=False)
def _execute(self, name, arguments):
if name == 'find_delivery_route':
return self._find_delivery_route(arguments)
if name == 'inspect_delivery_packet':
return self._inspect_delivery_packet(arguments)
if name == 'commit_query_delivery':
return self._commit_query_delivery(arguments)
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
def apply_policy_drift(self, event_id):
if event_id in self.applied_boundary_events:
return {'status': 'success', 'event_id': event_id, 'idempotent': True, 'changed': []}
changed = []
for cell in sorted(DATA_CHANGED_CELLS):
before = self.policy_by_cell[cell]
after = DATA_POST_POLICY_BY_CELL[cell]
self.policy_by_cell[cell] = after
changed.append({'cell': ':'.join(cell), 'before': before, 'after': after})
self.policy_epoch = 'post'
self.applied_boundary_events.add(event_id)
return {'status': 'success', 'event_id': event_id, 'idempotent': False, 'changed': changed}
def _warehouse_scope_init(self, *, allowance=68, source_root=CASE_DIR / 'raw'):
self._warehouse_scope_init_2(allowance=allowance, source_root=source_root)
variants = {(task_id, moved): fn_frontier_targets(task_id, moved) for task_id in DATA_TASK_IDS_2 for moved in (False, True)}
for rows in variants.values():
for item in rows:
if self._get('query_job', item['query_job_id'], 'query_job_id') is not None:
continue
query = ext_deepcopy(self._get('query_job', item['source_query_job_id'], 'query_job_id'))
if query is None:
raise ValueError('Warehouse v8 query template is absent')
query.update(query_job_id=item['query_job_id'], destination_table_id=None)
self.manager.add_entity('query_job', query, id_field='query_job_id')
self._variant_targets = {key: tuple((ext_deepcopy(item) for item in rows)) for (key, rows) in variants.items()}
self.targets = {f'{task_id}:{int(moved)}:{index}': ext_deepcopy(target) for ((task_id, moved), rows) in variants.items() for (index, target) in enumerate(rows, 1)}
self._validate_target_bindings()
self.targets = {}
def _cloud_data_warehouse_successor_activate_task(self, task_id, request_refs, allowance=50):
requested = {str(value) for value in request_refs}
unknown = requested - set(self.targets)
if unknown:
raise ValueError(f'unknown active target reference(s): {sorted(unknown)}')
self.active_task_id = str(task_id)
self.active_request_refs = requested
self.work_unit_limit = int(allowance)
self.work_units = 0
self.calls = 0
self.writes = 0
self.receipts = []
return {'status': 'success', 'task_id': self.active_task_id, 'active_target_count': len(requested), 'allowance': self.work_unit_limit}
def _warehouse_regional_approval_world_snapshot(self):
value = self._warehouse_document_opportunity_world_snapshot()
if not getattr(self, '_restoring_regional', False):
value['regional_approval_contract'] = {'case_version': 'warehouse-regional-approval-evolution-v6', 'blueprint_sha256': ext_digest(fn_blueprint_2())}
return value
def _warehouse_regional_approval_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'warehouse-regional-approval-evolution-v6', 'blueprint_sha256': ext_digest(fn_blueprint_2())}
if value.pop('regional_approval_contract', None) != expected:
raise ValueError('Warehouse regional approval snapshot identity differs')
self._restoring_regional = True
try:
self._warehouse_document_opportunity_world_restore(value)
finally:
self._restoring_regional = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse regional approval snapshot did not round trip')
def _warehouse_evolution_apply_event(self, event_id):
if event_id not in {'E1', 'E2'}:
raise ValueError('unregistered warehouse event')
before = self.business_hash()
if event_id in self.applied_boundary_events:
return {'event_id': event_id, 'applied': False, 'before': before, 'after': before}
if event_id == 'E1':
self.structure_moved = True
self.structure_authority = fn_authority(True)
else:
if 'E1' not in self.applied_boundary_events:
raise ValueError('warehouse events must follow their declared order')
for (cell, profile_id) in DATA_RULE_AFTER.items():
control = next((c for c in self.control_registry.values() if (c['scope']['query_priority'], c['scope']['destination_classification']) == cell))
profile = DATA_DELIVERY_PROFILES[profile_id]
control['clauses'].update(materialized_table_type=profile['table_type'], export_format=profile['format'], export_compression=profile['compression'])
self.policy_by_cell[cell] = profile_id
for document in self.governance:
for (index, variant) in enumerate(document.get('authorized_variants', [])):
if variant['control_record_id'] == control['control_record_id']:
document['authorized_variants'][index] = ext_deepcopy(control)
self.policy_epoch = 'evolution-E2'
self.applied_boundary_events.add(event_id)
return {'event_id': event_id, 'applied': True, 'before': before, 'after': self.business_hash()}
def _warehouse_independent_world_execute_public(self, name, arguments):
target = self.targets.get(arguments.get('request_ref'))
if name != 'commit_query_delivery' or target is None:
return self._warehouse_scope_execute_public(name, arguments)
original = self._task_targets
self._task_targets = [target] + [row for row in original if row is not target and row != target]
try:
return self._warehouse_scope_execute_public(name, arguments)
finally:
self._task_targets = original
def _warehouse_evidence_grade_targets(self, rows):
result = self._cloud_data_warehouse_successor_grade_targets(rows)
for (item, row) in zip(rows, result['targets']):
ledger = next((entry for entry in self.delivery_ledger if entry['request_ref'] == item['request_ref']), None)
control = self.control_registry.get(ledger.get('control_record_id')) if ledger else None
valid = bool(control and control['status'] == 'approved' and (control['scope']['query_priority'] == item['query_priority']) and (control['scope']['destination_classification'] == item['destination_classification']))
if row['milestones']['control_receipt'] and (not valid):
row['milestones']['control_receipt'] = False
row['score'] -= 4.0
row['complete'] = False
result['score'] = sum((row['score'] for row in result['targets']))
result['complete_artifacts'] = sum((row['complete'] for row in result['targets']))
return result
def _warehouse_scope_dispatch(self, name, arguments, actor_id='warehouse-delivery-operator:northshore-holdings'):
if name == 'commit_query_delivery' and isinstance(arguments, dict):
route = arguments.get('route_id')
authorization = arguments.get('lane_authorization')
if isinstance(route, str) and isinstance(authorization, str) and ((route, authorization) not in DATA_KNOWN_LANE_TUPLES):
result = fn__error('LANE_BINDING_TUPLE_INCONSISTENT', 'route_id and lane_authorization were not emitted together by positive evidence')
result['data']['budget'] = self._budget_receipt(0)
result['data']['recovery'] = 'Copy both fields verbatim from the same exact reusable_lane_binding.'
return result
return self._warehouse_scope_dispatch_2(name, arguments, actor_id)
def _warehouse_scope_business_snapshot(self):
value = self._warehouse_evidence_business_snapshot()
value['governance_documents'] = ext_deepcopy(self.governance)
value['business_tool_surface_sha256'] = 'e097c1a72aed2e241dde85b64b5b4e5fd0287805c69a402cfd43a4cbea870499'
return value
def _cloud_data_warehouse_successor_budget_receipt(self, charged):
return {'charged': charged, 'remaining': self.remaining, 'work_units_used': self.work_units, 'work_unit_limit': self.work_unit_limit, 'calls_used': self.calls, 'call_limit': 12, 'writes_used': self.writes, 'write_limit': 5}
def _warehouse_scope_init_2(self, *, allowance=68, source_root=CASE_DIR / 'raw'):
self.governance = fn_governance_documents()
self._warehouse_evidence_init(allowance=allowance, source_root=source_root)
def _warehouse_document_opportunity_world_snapshot(self):
value = self._warehouse_prefix_opportunity_world_snapshot()
if not getattr(self, '_restoring_document_opportunity', False):
value['document_opportunity_contract'] = {'case_version': 'warehouse-document-opportunity-evolution-v5', 'blueprint_sha256': ext_digest(fn_blueprint_3())}
return value
def _warehouse_document_opportunity_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'warehouse-document-opportunity-evolution-v5', 'blueprint_sha256': ext_digest(fn_blueprint_3())}
if value.pop('document_opportunity_contract', None) != expected:
raise ValueError('Warehouse document-opportunity snapshot identity differs')
self._restoring_document_opportunity = True
try:
self._warehouse_prefix_opportunity_world_restore(value)
finally:
self._restoring_document_opportunity = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse document-opportunity snapshot did not round trip')
def _warehouse_scope_execute_public(self, name, arguments):
result = self._warehouse_scope_execute_public_2(name, arguments)
if result.get('status') != 'success':
return result
data = result['data']
if name in {'inspect_delivery_packet', 'commit_query_delivery'}:
lane = data.get('reusable_lane_binding')
if lane is not None:
data['reusable_lane_binding'] = fn__canonicalize_lane(lane)
if name == 'read_delivery_controls':
data['reusable_control_bindings'] = fn_reusable_control_bindings(result)
elif name == 'list_delivery_profiles':
data['reusable_profile_catalog'] = fn_reusable_profile_catalog()
elif name == 'commit_query_delivery':
target = self.targets.get(arguments.get('request_ref'))
if target is not None:
key = target['query_priority'] + ':' + target['destination_classification']
data['reusable_control_binding'] = {'key': {'query_priority': target['query_priority'], 'destination_classification': target['destination_classification']}, 'value': {'control_record_id': arguments['control_record_id'], 'delivery_profile_id': arguments['delivery_profile_id']}, 'evidence_state': 'verified_current', 'evidence_kind': 'successful_exact_commit', 'canonical_record': f"CONTROL|{key}|{arguments['control_record_id']}|{arguments['delivery_profile_id']}"}
return result
def _cloud_data_warehouse_successor_grade_targets(self, targets):
rows = []
seen: set[str] = set()
for target in targets:
request_ref = str(target['request_ref'])
duplicate = request_ref in seen
seen.add(request_ref)
ledger = next((row for row in self.delivery_ledger if row['request_ref'] == request_ref), None)
query = self._get('query_job', target['query_job_id'], 'query_job_id')
table = self._get('table', ledger['table_id'], 'table_id') if ledger else None
export = self._get('export_job', ledger['export_job_id'], 'export_job_id') if ledger else None
columns = [row for row in self.manager.list_entities('column') if ledger and row.get('table_id') == ledger['table_id']]
expected_profile_id = self.policy_by_cell[target['query_priority'], target['destination_classification']]
profile = DATA_DELIVERY_PROFILES[expected_profile_id]
milestones = {'materialized_result': bool(ledger and table and (table.get('dataset_id') == target['destination_dataset_id']) and (table.get('table_type') == profile['table_type']) and (table.get('row_count') == query.get('result_row_count')) and (len(columns) == 3)), 'query_lineage': bool(ledger and query and (query.get('destination_table_id') == ledger.get('table_id'))), 'completed_export': bool(ledger and export and (export.get('status') == 'succeeded') and (export.get('source_table_id') == ledger.get('table_id')) and (export.get('destination_uri') == target['destination_uri']) and (export.get('format') == profile['format']) and (export.get('compression') == profile['compression']) and (export.get('row_count') == query.get('result_row_count'))), 'control_receipt': bool(ledger and ledger.get('delivery_profile_id') == expected_profile_id and (ledger.get('quota_accounted') is True) and (float(ledger.get('export_credits') or 0) > 0))}
points = {'materialized_result': 8.0, 'query_lineage': 5.0, 'completed_export': 8.0, 'control_receipt': 4.0}
score = 0.0 if duplicate else sum((points[name] for (name, passed) in milestones.items() if passed))
rows.append({'request_ref': request_ref, 'duplicate_target': duplicate, 'milestones': milestones, 'score': score, 'complete': score == 25.0})
total = round(sum((row['score'] for row in rows)), 2)
return {'score': total, 'complete_artifacts': sum((row['complete'] for row in rows)), 'max_score': 25.0 * len(rows), 'targets': rows}
def _warehouse_scope_dispatch_2(self, name, arguments, actor_id='warehouse-delivery-operator:northshore-holdings'):
desired = DATA_COSTS.get(name)
if desired is not None and name == 'read_delivery_controls' and (self.active_task_id is not None) and (self.remaining < desired):
result = fn__error('WORK_BUDGET_EXHAUSTED', 'remaining work units cannot fund this operation')
result['data']['budget'] = self._budget_receipt(0)
return result
count_before = self.calls
result = self._warehouse_evidence_dispatch(name, arguments, actor_id)
if self.calls == count_before:
return result
extra = DATA_COSTS[name] - DATA_COSTS_2[name]
self.work_units += extra
result['data']['budget'] = self._budget_receipt(DATA_COSTS[name])
basis = {'find_delivery_route': 'scan_16_candidate_binding_records', 'inspect_delivery_packet': 'six_exact_primary_key_business_record_checks', 'read_delivery_controls': 'evaluate_all_potentially_applicable_governance_documents', 'list_delivery_profiles': 'four_capability_records', 'commit_query_delivery': 'reserved_atomic_materialize_export_accounting_transaction'}[name]
ledger = {'units': DATA_COSTS[name], 'basis': basis, 'python_internal_list_scans_and_serialization_are_not_charged': True}
if name == 'read_delivery_controls':
ledger['examined_records'] = len(self.governance)
self.receipts[-1].update(charged=DATA_COSTS[name], logical_work=ext_deepcopy(ledger))
result['data']['logical_work'] = ledger
return result
def _warehouse_evidence_business_snapshot(self):
value = self._natural_cloud_data_warehouse_successor_business_snapshot()
value['control_registry'] = ext_deepcopy(getattr(self, 'control_registry', fn_controls()))
value['business_tool_surface_sha256'] = 'debd083bd85e97049dd352b10b07b9b5da8ca9ff27778264e9f45063e9c77ad1'
return value
def _warehouse_evidence_init(self, *, allowance, source_root=CASE_DIR / 'raw'):
self._natural_cloud_data_warehouse_successor_init(source_root=source_root, budget=allowance)
self.control_registry = fn_controls()
self._variant_targets = {(task_id, moved): fn_targets_3(task_id, moved) for task_id in DATA_TASK_IDS_2 for moved in (False, True)}
for rows in self._variant_targets.values():
for item in rows:
query = ext_deepcopy(self._get('query_job', item['source_query_job_id'], 'query_job_id'))
query.update(query_job_id=item['query_job_id'], destination_table_id=None)
self.manager.add_entity('query_job', query, id_field='query_job_id')
self.targets = {}
self.structure_authority = fn_authority(False)
self._activated_tasks = []
self._task_targets = []
self.initial_budget = allowance
self.work_unit_limit = allowance
def _warehouse_prefix_opportunity_world_snapshot(self):
value = self._warehouse_tail_coverage_world_snapshot()
if not getattr(self, '_restoring_prefix_opportunity', False):
value['prefix_opportunity_contract'] = {'case_version': 'warehouse-prefix-opportunity-evolution-v4', 'blueprint_sha256': ext_digest(fn_blueprint_4())}
return value
def _warehouse_prefix_opportunity_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'warehouse-prefix-opportunity-evolution-v4', 'blueprint_sha256': ext_digest(fn_blueprint_4())}
if value.pop('prefix_opportunity_contract', None) != expected:
raise ValueError('Warehouse prefix-opportunity snapshot version differs')
self._restoring_prefix_opportunity = True
try:
self._warehouse_tail_coverage_world_restore(value)
finally:
self._restoring_prefix_opportunity = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse prefix-opportunity snapshot did not round trip')
def _warehouse_scope_execute_public_2(self, name, arguments):
result = self._warehouse_scope_execute_public_3(name, arguments)
target = self.targets.get(arguments.get('request_ref'))
if target is None:
return result
if name == 'inspect_delivery_packet' and result.get('status') == 'success':
result['data']['reusable_lane_binding'] = fn_reusable_lane_binding(target)
elif name == 'commit_query_delivery':
if result.get('status') == 'success':
result['data']['reusable_lane_binding'] = fn_reusable_lane_binding(target)
elif result.get('error_code') == 'DELIVERY_BINDING_MISMATCH':
result['data']['binding_conflict'] = {'key': {'delivery_lane_ref': target['delivery_lane_ref']}, 'attempted': {'route_id': arguments['route_id'], 'lane_authorization': arguments['lane_authorization']}, 'evidence_state': 'stale', 'replacement_disclosed': False, 'recovery': 'Refresh only this exact active request from positive packet evidence.'}
return result
def _warehouse_evidence_dispatch(self, name, arguments, actor_id='warehouse-delivery-operator:northshore-holdings'):
if self.active_task_id is None:
return fn__error('TASK_NOT_ACTIVE', 'activate a task before dispatch')
if name not in DATA_TOOL_MAP:
return fn__error('TOOL_NOT_ALLOWED', 'tool is not in the learner allowlist')
if actor_id != 'warehouse-delivery-operator:northshore-holdings':
return fn__error('ACTOR_NOT_AUTHORIZED', 'actor is not an authorized warehouse delivery operator')
invalid = fn__validate_node(arguments, DATA_TOOL_MAP[name]['parameters'])
if invalid:
return fn__error('INVALID_ARGUMENTS', invalid)
if self.calls >= 64 or (name == 'commit_query_delivery' and self.writes >= 12):
return fn__error('CALL_LIMIT_EXHAUSTED', 'task operation guard is exhausted')
cost = DATA_COSTS_2[name]
if cost > self.remaining:
result = fn__error('WORK_BUDGET_EXHAUSTED', 'remaining work units cannot fund this operation')
result['data']['budget'] = self._budget_receipt(0)
return result
before = self.business_hash()
database = self._raw_database_snapshot()
ledger = ext_deepcopy(self.delivery_ledger)
(self._active_tool, self._mutation_count) = (name, 0)
try:
result = self._execute_public(name, ext_deepcopy(arguments))
if result['status'] != 'success':
raise Abort(result)
except Abort as error:
self._restore_raw_database(database)
self.delivery_ledger = ledger
result = error.result
except Exception:
self._restore_raw_database(database)
self.delivery_ledger = ledger
raise
finally:
(self._active_tool, self._mutation_count) = (None, 0)
self.calls += 1
self.writes += int(name == 'commit_query_delivery')
self.work_units += cost
result.setdefault('data', {})['budget'] = self._budget_receipt(cost)
if result['data'].get('task_id') in DATA_TASK_IDS_2:
task_id = result['data'].pop('task_id')
result['data']['event_id'] = fn_opaque('EV', task_id).upper()
self.receipts.append({'index': len(self.receipts) + 1, 'task_id': self.active_task_id, 'tool': name, 'arguments': ext_deepcopy(arguments), 'status': result['status'], 'error_code': result.get('error_code'), 'charged': cost, 'before_business_hash': before, 'after_business_hash': self.business_hash()})
return ext_deepcopy(result)
def _natural_cloud_data_warehouse_successor_business_snapshot(self):
value = self._structural_cloud_data_warehouse_successor_business_snapshot()
value['structure_authority'] = ext_deepcopy(self.structure_authority)
value['business_tool_surface_sha256'] = 'bf695e60b3b72bc51e2e546788aae608ee8ff0d3993a046ae4c7dbbbd4558a93'
return value
def _natural_cloud_data_warehouse_successor_init(self, source_root=None, source=None, budget=25):
resolved = ext_Path(source_root or source or CASE_DIR / 'raw').resolve()
self._structural_cloud_data_warehouse_successor_init(resolved, budget=budget)
variants = {(task_id, moved): fn_stream_targets(task_id, moved=moved) for task_id in DATA_TASK_IDS_3 for moved in (False, True)}
for targets in variants.values():
for target in targets:
if self._get('query_job', target['query_job_id'], 'query_job_id') is not None:
continue
source_query = self._get('query_job', target['source_query_job_id'], 'query_job_id')
if source_query is None:
raise ValueError('structure successor query template is absent')
query = ext_deepcopy(source_query)
query['query_job_id'] = target['query_job_id']
query['destination_table_id'] = None
self.manager.add_entity('query_job', query, id_field='query_job_id')
self._variant_targets = {key: tuple((ext_deepcopy(row) for row in rows)) for (key, rows) in variants.items()}
self.targets = {f'{task_id}:{int(moved)}:{index}': ext_deepcopy(target) for ((task_id, moved), targets) in variants.items() for (index, target) in enumerate(targets, 1)}
self._validate_target_bindings()
self.structure_moved = False
self.structure_authority = ext_deepcopy(DATA_PRE_STRUCTURE_AUTHORITY)
self._activated_tasks = []
self._task_targets = []
self.work_unit_limit = budget
def _warehouse_tail_coverage_world_snapshot(self):
value = self._warehouse_independent_world_snapshot()
if not getattr(self, '_restoring_tail_coverage', False):
value['tail_coverage_contract'] = {'case_version': 'warehouse-tail-coverage-evolution-v3', 'blueprint_sha256': ext_digest(fn_blueprint_5())}
return value
def _warehouse_tail_coverage_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
expected = {'case_version': 'warehouse-tail-coverage-evolution-v3', 'blueprint_sha256': ext_digest(fn_blueprint_5())}
if value.pop('tail_coverage_contract', None) != expected:
raise ValueError('Warehouse tail-coverage snapshot version differs')
self._restoring_tail_coverage = True
try:
self._warehouse_independent_world_restore(value)
finally:
self._restoring_tail_coverage = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse tail-coverage snapshot did not round trip')
def _warehouse_scope_execute_public_3(self, name, arguments):
if name == 'read_delivery_controls':
matched = self._matching_documents(arguments['query_priority'], arguments['destination_classification'])
approval = next((row for row in matched if row['kind'] == 'delivery_approval'))
control = next((row for row in approval['authorized_variants'] if row['scope']['destination_classification'] == arguments['destination_classification']))
return fn__success(control=ext_deepcopy(control), applicable_documents=ext_deepcopy(matched), approval_document=ext_deepcopy(approval), examined_records=len(self.governance))
if name == 'commit_query_delivery':
target = self.targets.get(arguments['request_ref'])
if target is not None:
matched = self._matching_documents(target['query_priority'], target['destination_classification'])
if len(matched) != 3 or any((row['status'] != 'approved' for row in matched)):
return fn__error('GOVERNANCE_AUTHORITY_UNAVAILABLE', 'applicable governance authority is not approved')
org = next((row for row in matched if row['kind'] == 'organization_baseline'))
source = next((row for row in matched if row['kind'] == 'source_priority_control'))
approval = next((row for row in matched if row['kind'] == 'delivery_approval'))
query = self._get('query_job', target['query_job_id'], 'query_job_id')
if query.get('org_id') != org['requirements']['organization_id'] or org['requirements']['operator_role'] != 'warehouse_delivery_operator':
return fn__error('GOVERNANCE_ORGANIZATION_MISMATCH', 'organization baseline does not authorize this operator scope')
if query.get('status') != source['requirements']['query_status'] or query.get('result_row_count', 0) < source['requirements']['minimum_result_rows']:
return fn__error('GOVERNANCE_SOURCE_MISMATCH', 'source does not satisfy the applicable priority control')
if arguments['control_record_id'] not in {row['control_record_id'] for row in approval['authorized_variants']}:
return fn__error('CONTROL_SCOPE_MISMATCH', 'control reference is outside the applicable approval document')
return self._warehouse_evidence_execute_public(name, arguments)
def _structural_cloud_data_warehouse_successor_business_snapshot(self):
value = self._cloud_data_warehouse_successor_business_snapshot()
value.update({'structure_authority': ext_deepcopy(self.structure_authority), 'rule_authority': fn_canonical_policy_table(self.policy_by_cell), 'permission_authority': self._permission_authority(), 'resource_authority': self._resource_authority(), 'business_tool_surface_sha256': fn_digest(DATA_PROVIDER_TOOLS)})
return value
def _structural_cloud_data_warehouse_successor_init(self, source_root=None, source=None, budget=50):
resolved = ext_Path(source_root or source or CASE_DIR / 'raw').resolve()
variants = {(task_id, moved): fn_stream_targets_2(task_id, moved=moved) for task_id in DATA_TASK_IDS_4 for moved in (False, True)}
bootstrap = []
for ((task_id, moved), targets) in variants.items():
for target in targets:
row = ext_deepcopy(target)
row['request_ref'] = f"{target['request_ref']}:{task_id}:{int(moved)}"
row['query_job_id'] = target['source_query_job_id']
bootstrap.append(row)
self._cloud_data_warehouse_successor_init(resolved, bootstrap, budget=budget)
for targets in variants.values():
for target in targets:
if self._get('query_job', target['query_job_id'], 'query_job_id') is not None:
continue
source_query = self._get('query_job', target['source_query_job_id'], 'query_job_id')
if source_query is None:
raise ValueError('structure successor query template is absent')
query = ext_deepcopy(source_query)
query['query_job_id'] = target['query_job_id']
query['destination_table_id'] = None
self.manager.add_entity('query_job', query, id_field='query_job_id')
self._variant_targets = {key: tuple((ext_deepcopy(row) for row in rows)) for (key, rows) in variants.items()}
self.targets = {f'{task_id}:{int(moved)}:{index}': ext_deepcopy(target) for ((task_id, moved), targets) in variants.items() for (index, target) in enumerate(targets, 1)}
self._validate_target_bindings()
self.structure_moved = False
self.structure_authority = ext_deepcopy(DATA_PRE_STRUCTURE_AUTHORITY_2)
self.policy_epoch = 'fixed'
self.policy_by_cell = dict(DATA_PRE_POLICY_BY_CELL)
self._activated_tasks: list[str] = []
self._task_targets: list[dict[str, ext_Any]] = []
def _warehouse_independent_world_snapshot(self):
value = self._warehouse_evolution_snapshot()
if not getattr(self, '_restoring_independent', False):
value['independent_delivery_contract'] = 'warehouse-independent-deliveries-evolution-v2'
return value
def _warehouse_independent_world_restore(self, snapshot):
value = ext_deepcopy(snapshot)
if value.pop('independent_delivery_contract', None) != 'warehouse-independent-deliveries-evolution-v2':
raise ValueError('Warehouse independent snapshot version differs')
self._restoring_independent = True
try:
self._warehouse_evolution_restore(value)
finally:
self._restoring_independent = False
if self.snapshot() != snapshot:
raise ValueError('Warehouse independent snapshot did not round trip')
def _warehouse_evidence_execute_public(self, name, arguments):
if name == 'list_delivery_profiles':
return fn__success(profiles=[{'delivery_profile_id': key, **ext_deepcopy(value)} for (key, value) in DATA_DELIVERY_PROFILES.items()])
if name == 'read_delivery_controls':
candidates = [record for record in self.control_registry.values() if all((record['scope'][key] == arguments[key] for key in arguments))]
return fn__success(control=ext_deepcopy(candidates[0]))
target = self.targets.get(arguments['request_ref'])
if target is None:
return fn__error('TARGET_SCOPE_FORBIDDEN', 'request is not in the active delivery set')
if name == 'find_delivery_route':
rows = self._directory()
return fn__success(candidates=[row for row in rows if row['lane_ref'] == target['delivery_lane_ref']], examined_records=len(rows))
if name == 'inspect_delivery_packet':
result = self._inspect_delivery_packet(arguments)
if result['status'] == 'success':
result['data']['packet'].update(delivery_lane_ref=target['delivery_lane_ref'], lane_authorization=target['lane_authorization'], stable_fields=['delivery_lane_ref', 'route_id', 'lane_authorization'], task_scoped_fields=['request_ref', 'query_job_id', 'table_name', 'destination_uri'])
return result
earlier = self._task_targets[:self._task_targets.index(target)]
if any((not row['complete'] for row in self.grade_targets(earlier)['targets'])):
return fn__error('PRIOR_TARGET_INCOMPLETE', 'complete earlier listed deliveries before this request')
if arguments['route_id'] != target['route_id'] or arguments['lane_authorization'] != target['lane_authorization']:
return fn__error('DELIVERY_BINDING_MISMATCH', 'route authority does not bind this active delivery')
control = self.control_registry.get(arguments['control_record_id'])
expected_scope = {'organization_id': 'org-northshore-holdings', 'operator_role': 'warehouse_delivery_operator', 'query_priority': target['query_priority'], 'destination_classification': target['destination_classification']}
if control is None or control['status'] != 'approved' or control['scope'] != expected_scope:
return fn__error('CONTROL_SCOPE_MISMATCH', 'control is absent, unapproved, or outside the delivery scope')
profile = DATA_DELIVERY_PROFILES[arguments['delivery_profile_id']]
clause = control['clauses']
if not (profile['table_type'] == clause['materialized_table_type'] and profile['format'] == clause['export_format'] and (profile['compression'] == clause['export_compression']) and (clause['quota_accounting_required'] is True)):
return fn__error('DELIVERY_PROFILE_MISMATCH', 'profile capabilities do not satisfy the approved control')
expanded = {key: target[key] for key in ('request_ref', 'route_id', 'query_job_id', 'destination_dataset_id', 'operator_user_id', 'warehouse_id', 'table_name', 'destination_uri')}
expanded['delivery_profile_id'] = arguments['delivery_profile_id']
result = self._commit_query_delivery(expanded)
if result['status'] == 'success':
ledger = next((row for row in self.delivery_ledger if row['request_ref'] == target['request_ref']))
ledger['control_record_id'] = control['control_record_id']
result['data']['control_record_id'] = control['control_record_id']
return result
def _cloud_data_warehouse_successor_business_snapshot(self):
return {'raw_database': self._raw_database_snapshot(), 'delivery_ledger': mod_copy.deepcopy(self.delivery_ledger), 'policy_epoch': self.policy_epoch, 'policy_by_cell': fn_canonical_policy_table(self.policy_by_cell), 'applied_boundary_events': sorted(self.applied_boundary_events)}
def _cloud_data_warehouse_successor_init(self, source, targets, budget=50):
self.source = ext_Path(source).resolve()
(state_manager, raw_tools) = fn__load_raw_components(str(self.source))
self.raw_tools = raw_tools
self.raw_tools.now_iso = lambda : '2026-09-25T12:00:00Z'
self._runtime = mod_tempfile.TemporaryDirectory(prefix='rescope-cloud-warehouse-v2-')
self.manager = state_manager(str(ext_Path(self._runtime.name) / 'data'))
self.targets = {str(target['request_ref']): mod_copy.deepcopy(target) for target in targets}
if len(self.targets) != len(targets):
raise ValueError('request references must be unique')
self._seed_raw_state()
self.policy_epoch = 'pre'
self.policy_by_cell = dict(DATA_PRE_POLICY_BY_CELL)
self.delivery_ledger: list[dict[str, ext_Any]] = []
self.applied_boundary_events: set[str] = set()
self.active_task_id: str | None = None
self.active_request_refs: set[str] = set()
self.initial_budget = int(budget)
self.work_unit_limit = int(budget)
self.work_units = 0
self.calls = 0
self.writes = 0
self.receipts: list[dict[str, ext_Any]] = []
self._fault: dict[str, ext_Any] | None = None
self._active_tool: str | None = None
self._mutation_count = 0
def _warehouse_evolution_snapshot(self):
value = World._cloud_data_warehouse_successor_snapshot(self)
value['evolution'] = {'case_version': 'warehouse-two-event-lifecycle-evolution-v1', 'schedule': ext_deepcopy(DATA_SCHEDULE_2), 'plan_sha256': ext_digest({'rules': DATA_RULE_PLAN_2, 'structures': DATA_STRUCTURE_PLAN_2}), 'activated_tasks': list(self._activated_tasks), 'task_targets': ext_deepcopy(self._task_targets), 'structure_moved': self.structure_moved, 'own_commits': ext_deepcopy(self._own_commits)}
return value
def _warehouse_evolution_restore(self, snapshot):
metadata = snapshot['evolution']
if metadata['case_version'] != 'warehouse-two-event-lifecycle-evolution-v1' or metadata['schedule'] != DATA_SCHEDULE_2 or metadata['plan_sha256'] != ext_digest({'rules': DATA_RULE_PLAN_2, 'structures': DATA_STRUCTURE_PLAN_2}):
raise ValueError('warehouse evolution contract differs')
active = metadata['activated_tasks']
if active != list(DATA_TASK_IDS[:len(active)]) or snapshot['active_task_id'] != (active[-1] if active else None):
raise ValueError('warehouse evolution prefix differs')
events = [e['event_id'] for e in DATA_SCHEDULE_2['events'] if e['before_task'] <= len(active)]
if snapshot['applied_boundary_events'] != events:
raise ValueError('warehouse evolution event ledger differs')
World._cloud_data_warehouse_successor_restore(self, snapshot)
self.control_registry = ext_deepcopy(snapshot['control_registry'])
self.governance = ext_deepcopy(snapshot['governance_documents'])
self.structure_authority = ext_deepcopy(snapshot['structure_authority'])
self.structure_moved = metadata['structure_moved']
self._activated_tasks = ext_deepcopy(active)
self._task_targets = ext_deepcopy(metadata['task_targets'])
self._own_commits = ext_deepcopy(metadata['own_commits'])
if self.snapshot() != snapshot:
raise ValueError('warehouse evolution did not round trip')
def _cloud_data_warehouse_successor_snapshot(self):
return {**self._business_snapshot(), 'targets': mod_copy.deepcopy(self.targets), 'active_task_id': self.active_task_id, 'active_request_refs': sorted(self.active_request_refs), 'initial_budget': self.initial_budget, 'work_unit_limit': self.work_unit_limit, 'work_units': self.work_units, 'remaining': self.remaining, 'calls': self.calls, 'writes': self.writes, 'receipts': mod_copy.deepcopy(self.receipts)}
def _cloud_data_warehouse_successor_restore(self, snapshot):
self._restore_raw_database(snapshot['raw_database'])
self.delivery_ledger = mod_copy.deepcopy(snapshot['delivery_ledger'])
self.policy_epoch = str(snapshot['policy_epoch'])
self.policy_by_cell = {tuple(key.split(':', 1)): value for (key, value) in snapshot['policy_by_cell'].items()}
self.applied_boundary_events = set(snapshot['applied_boundary_events'])
self.targets = mod_copy.deepcopy(snapshot['targets'])
self.active_task_id = snapshot['active_task_id']
self.active_request_refs = set(snapshot['active_request_refs'])
self.initial_budget = int(snapshot['initial_budget'])
self.work_unit_limit = int(snapshot['work_unit_limit'])
self.work_units = int(snapshot['work_units'])
self.calls = int(snapshot['calls'])
self.writes = int(snapshot['writes'])
self.receipts = mod_copy.deepcopy(snapshot['receipts'])
self._fault = None
self._active_tool = None
self._mutation_count = 0
class Abort(Exception):
def __init__(self, result):
Exception.__init__(self, result.get('message', 'operation rejected'))
self.result = result