275 lines
15 KiB
Python
275 lines
15 KiB
Python
"""Offline additive family-scoped private-bit allocation for proven flat11 scopes.
|
|
|
|
Never creates missing spell definitions. Every private bit must be unused in
|
|
all effective selected-family rows; existing fields/bits remain exact. A fresh merge
|
|
must revalidate this witness against its final inventory before publication.
|
|
"""
|
|
import copy
|
|
import warrior_cooldown_modifier as policy
|
|
|
|
TABLES = ('Spell', 'SpellName', 'SpellMisc', 'SpellEffect')
|
|
|
|
|
|
def _effective(native, overlays, table):
|
|
if type(native) is not list or len(native) > 500000 or type(overlays) is not list:
|
|
raise ValueError('complete bounded definition tables required')
|
|
rows = {}
|
|
for row in native:
|
|
if type(row) is not dict:
|
|
raise ValueError('typed native definition required')
|
|
rid = policy._integer(row.get('ID'), 0, 0x7fffffff, 'native definition identity')
|
|
if rid in rows:
|
|
raise ValueError('duplicate native definition')
|
|
rows[rid] = row
|
|
seen = set()
|
|
for overlay in overlays:
|
|
if type(overlay) is not dict:
|
|
raise ValueError('typed definition overlay required')
|
|
if overlay.get('table_name') != table:
|
|
continue
|
|
rid = policy._integer(overlay.get('id'), 0, 0x7fffffff, 'definition overlay identity')
|
|
if rid in seen:
|
|
raise ValueError('duplicate definition overlay')
|
|
seen.add(rid)
|
|
status = overlay.get('record_status', 'valid')
|
|
if status == 'removed':
|
|
rows.pop(rid, None)
|
|
elif status == 'valid':
|
|
record = overlay.get('record')
|
|
if type(record) is not dict or type(record.get('ID')) is not int or record['ID'] != rid:
|
|
raise ValueError('definition overlay record identity')
|
|
rows[rid] = record
|
|
else:
|
|
raise ValueError('nonvalid definition overlay')
|
|
return rows
|
|
|
|
|
|
def definition_closure(source_records, native_tables, overlays, spell_ids):
|
|
"""Presence/name/default-effect-slot closure; no new effect-semantic claim."""
|
|
if type(source_records) is not dict or set(native_tables) != set(TABLES):
|
|
raise ValueError('complete typed definition inventories required')
|
|
if type(spell_ids) is not list or len(set(spell_ids)) != len(spell_ids) or len(spell_ids) > 100000:
|
|
raise ValueError('unique bounded desired identities required')
|
|
for ident in spell_ids:
|
|
policy._integer(ident, 1, 0x7fffffff, 'desired source identity')
|
|
tables = {name: _effective(native_tables[name], overlays, name) for name in TABLES}
|
|
misc, effects = {}, {}
|
|
for row in tables['SpellMisc'].values():
|
|
if row.get('SpellID') in spell_ids:
|
|
policy._integer(row['SpellID'], 1, 0x7fffffff, 'native misc spell identity')
|
|
if policy._integer(row.get('DifficultyID'), 0, 0x7fffffff, 'native misc difficulty') == 0:
|
|
misc.setdefault(row['SpellID'], []).append(row)
|
|
for row in tables['SpellEffect'].values():
|
|
if row.get('SpellID') in spell_ids:
|
|
policy._integer(row['SpellID'], 1, 0x7fffffff, 'native effect spell identity')
|
|
if policy._integer(row.get('DifficultyID'), 0, 0x7fffffff, 'native effect difficulty') == 0:
|
|
effects.setdefault(row['SpellID'], []).append(row)
|
|
result = {}
|
|
for ident in sorted(spell_ids):
|
|
policy._integer(ident, 1, 0x7fffffff, 'desired source identity')
|
|
source = source_records.get(ident)
|
|
reasons = []
|
|
if type(source) is not dict or type(source.get('entry')) is not int or source['entry'] != ident:
|
|
reasons.append('missing-source-definition')
|
|
source = None
|
|
if ident not in tables['Spell']:
|
|
reasons.append('missing-native-Spell')
|
|
name = tables['SpellName'].get(ident)
|
|
if name is None:
|
|
reasons.append('missing-native-SpellName')
|
|
elif source is not None and (type(source.get('name')) is not str or type(name.get('Name_lang')) is not str or source['name'] != name['Name_lang']):
|
|
reasons.append('source-native-name-mismatch')
|
|
if len(misc.get(ident, [])) != 1:
|
|
reasons.append('missing-or-ambiguous-default-SpellMisc')
|
|
actual = {}
|
|
for effect in effects.get(ident, []):
|
|
index = policy._integer(effect.get('EffectIndex'), 0, 31, 'native effect slot')
|
|
if index in actual:
|
|
reasons.append('duplicate-default-effect-slot')
|
|
if not policy._integer(effect.get('Effect'), 0, 0xffff, 'native effect operation'):
|
|
reasons.append('inactive-native-effect-slot')
|
|
actual[index] = effect
|
|
expected = set()
|
|
if source is not None:
|
|
for i in range(3):
|
|
if policy._integer(source.get('effect' + str(i + 1)), 0, 255, 'source effect'):
|
|
expected.add(i)
|
|
if not expected or not expected <= actual.keys():
|
|
reasons.append('missing-source-enabled-effect-slots')
|
|
result[ident] = {'spell_id': ident, 'complete': not reasons, 'held_reasons': sorted(set(reasons)),
|
|
'rows': {'Spell': ident if ident in tables['Spell'] else None,
|
|
'SpellName': ident if name is not None else None,
|
|
'SpellMisc': [row['ID'] for row in misc.get(ident, [])],
|
|
'SpellEffect': [row['ID'] for row in effects.get(ident, [])]},
|
|
'source_enabled_effect_slots': sorted(expected),
|
|
'extra_native_effect_slots_preserved': sorted(actual.keys() - expected),
|
|
'scope': 'Existing parent/name/default effect-slot presence; no new effect or asset semantics asserted.'}
|
|
return result
|
|
|
|
|
|
def allocate(source, target, closure, bits, *, family=policy.FAMILY):
|
|
"""Add high unused bits only for exact complete source identity scopes."""
|
|
initial = policy.derive(source, target, bits, family=family)
|
|
if type(closure) is not dict:
|
|
raise ValueError('typed per-spell closure required')
|
|
by_spell = {row['SpellID']: row for row in target}
|
|
used = 0
|
|
for row in target:
|
|
for i, word in enumerate(row['SpellClassMask']):
|
|
used |= (word & 0xffffffff) << (32 * i)
|
|
free = [bit for bit in range(127, -1, -1) if not used & (1 << bit)]
|
|
changed = copy.deepcopy(target)
|
|
destinations = {row['SpellID']: row for row in changed}
|
|
allocated, held = [], []
|
|
for row in initial['held']:
|
|
# Do not pick an arbitrary alias for preexisting equivalent bits or
|
|
# reconstruct colliding aggregates. This allocation handles exact
|
|
# identity scopes which lack a safe original native bit.
|
|
if row['reason'] != 'no-exact-native-bit':
|
|
held.append(copy.deepcopy(row))
|
|
continue
|
|
incomplete = [ident for ident in row['spell_ids'] if ident not in closure or
|
|
type(closure[ident]) is not dict or closure[ident].get('complete') is not True or
|
|
type(closure[ident].get('spell_id')) is not int or closure[ident]['spell_id'] != ident]
|
|
if incomplete:
|
|
held.append(dict(row, reason='incomplete-parent-definition-closure', incomplete_spell_ids=incomplete))
|
|
continue
|
|
if not free:
|
|
held.append(dict(row, reason='no-unused-native-class-bit'))
|
|
continue
|
|
bit = free.pop(0)
|
|
for ident in row['spell_ids']:
|
|
record = destinations[ident]
|
|
word = (record['SpellClassMask'][bit // 32] & 0xffffffff) | (1 << (bit % 32))
|
|
record['SpellClassMask'][bit // 32] = word - (1 << 32) if word >= 1 << 31 else word
|
|
allocated.append({'source_bit': row['source_bit'], 'native_bit': bit,
|
|
'spell_ids': list(row['spell_ids']), 'globally_unused_in_baseline': True})
|
|
# The independent strict mapper must now see the claimed unique identity
|
|
# route. If allocation introduced an ambiguity, refuse the whole candidate.
|
|
final = policy.derive(source, changed, bits, family=family)
|
|
final_routes = {row['source_bit']: row for row in final['admitted']}
|
|
for allocation in allocated:
|
|
actual = final_routes.get(allocation['source_bit'])
|
|
if actual is None or actual['native_bit'] != allocation['native_bit'] or actual['spell_ids'] != allocation['spell_ids']:
|
|
raise ValueError('additive allocation does not yield unique exact runtime route')
|
|
allowed = {}
|
|
for allocation in allocated:
|
|
for ident in allocation['spell_ids']:
|
|
allowed[ident] = allowed.get(ident, 0) | (1 << allocation['native_bit'])
|
|
replacements = []
|
|
for record in changed:
|
|
before = by_spell[record['SpellID']]
|
|
if {k: v for k, v in record.items() if k != 'SpellClassMask'} != {k: v for k, v in before.items() if k != 'SpellClassMask'}:
|
|
raise ValueError('native nonmask fields changed')
|
|
old = sum((word & 0xffffffff) << (32 * i) for i, word in enumerate(before['SpellClassMask']))
|
|
new = sum((word & 0xffffffff) << (32 * i) for i, word in enumerate(record['SpellClassMask']))
|
|
if old & ~new or (old ^ new) != allowed.get(record['SpellID'], 0):
|
|
raise ValueError('native field preservation or allocation scope differs')
|
|
if old != new:
|
|
replacements.append({'table_name': 'SpellClassOptions', 'id': record['ID'],
|
|
'before': copy.deepcopy(before), 'record': copy.deepcopy(record)})
|
|
return {'policy': f'additive-unused-native-class{family}-flat11-bit-v1',
|
|
'baseline_source_inventory_sha256': policy._sha(source),
|
|
'baseline_native_inventory_sha256': policy._sha(target),
|
|
'baseline_unused_native_bits': [bit for bit in range(128) if not used & (1 << bit)],
|
|
'allocations': allocated, 'held_allocations': held, 'record_replacements': replacements,
|
|
'native_inventory': changed, 'mapping_profile': final,
|
|
'all_existing_native_fields_and_bits_preserved': True,
|
|
'new_parent_definitions_authored': False, 'installable_package': False,
|
|
'requires_final_composer_revalidation': True}
|
|
|
|
|
|
def validate_allocation(proposal, source, target, closure, bits, *, family=policy.FAMILY):
|
|
if type(proposal) is not dict or proposal != allocate(source, target, closure, bits, family=family):
|
|
raise ValueError('allocation differs from exact baseline or definition closure')
|
|
return proposal
|
|
|
|
|
|
def allocate_disjoint_groups(source, target, closure, groups, *, family=policy.FAMILY, membership_proofs=None):
|
|
"""Give each disjoint target identity group one globally unused family bit.
|
|
|
|
This is a group-membership witness, not an individual source-bit mapping.
|
|
No definitions or SCO rows are created; any invalid group or insufficient
|
|
free bits refuses the whole candidate. Group/member order is canonicalized.
|
|
"""
|
|
policy._integer(family, 1, 255, 'selected family')
|
|
old, native_masks = policy._inventories(source, target, family=family)
|
|
if type(closure) is not dict:
|
|
raise ValueError('typed per-spell closure required')
|
|
if type(groups) is not list or not 1 <= len(groups) <= 128:
|
|
raise ValueError('bounded nonempty disjoint groups required')
|
|
from spell_family_membership_proof import approved_membership
|
|
used_membership = {}
|
|
canonical, seen = [], set()
|
|
for group in groups:
|
|
if type(group) is not list or not 1 <= len(group) <= 100000:
|
|
raise ValueError('nonempty bounded spell identity group required')
|
|
for ident in group:
|
|
policy._integer(ident, 1, 0x7fffffff, 'group spell identity')
|
|
if ident in seen:
|
|
raise ValueError('overlapping or duplicate group identity')
|
|
seen.add(ident)
|
|
if ident not in old or old[ident][0] != family:
|
|
raise ValueError('group identity missing from selected source family')
|
|
if ident not in native_masks:
|
|
raise ValueError('group identity missing native class row')
|
|
proof = closure.get(ident)
|
|
if (type(proof) is not dict or proof.get('complete') is not True or
|
|
type(proof.get('spell_id')) is not int or proof['spell_id'] != ident):
|
|
if membership_proofs is None:
|
|
raise ValueError('incomplete parent definition closure')
|
|
used_membership[ident] = approved_membership(membership_proofs, ident, family, proof)
|
|
canonical.append(sorted(group))
|
|
canonical.sort()
|
|
used = 0
|
|
for mask in native_masks.values():
|
|
used |= mask
|
|
free = [bit for bit in range(127, -1, -1) if not used & (1 << bit)]
|
|
if len(free) < len(canonical):
|
|
raise ValueError('insufficient unused native class bits for all groups')
|
|
allocations = [dict(native_bit=bit, spell_ids=group)
|
|
for bit, group in zip(free, canonical)]
|
|
changed = copy.deepcopy(target)
|
|
by_spell = {row['SpellID']: row for row in changed}
|
|
allowed = {}
|
|
for allocation in allocations:
|
|
bit = allocation['native_bit']
|
|
for ident in allocation['spell_ids']:
|
|
allowed[ident] = 1 << bit
|
|
row = by_spell[ident]
|
|
word = (row['SpellClassMask'][bit // 32] & 0xffffffff) | (1 << (bit % 32))
|
|
row['SpellClassMask'][bit // 32] = word - (1 << 32) if word >= 1 << 31 else word
|
|
# Validate complete resulting membership, including non-group native rows.
|
|
# Do not call derive: source bits may overlap these disjoint target groups.
|
|
_, final_masks = policy._inventories(source, changed, family=family)
|
|
for allocation in allocations:
|
|
members = sorted(ident for ident, mask in final_masks.items()
|
|
if mask & (1 << allocation['native_bit']))
|
|
if members != allocation['spell_ids']:
|
|
raise ValueError('new group bit membership differs or has collateral')
|
|
replacements = []
|
|
for before, after in zip(target, changed):
|
|
ident = before['SpellID']
|
|
if ({k: v for k, v in before.items() if k != 'SpellClassMask'} !=
|
|
{k: v for k, v in after.items() if k != 'SpellClassMask'}):
|
|
raise ValueError('native nonmask fields changed')
|
|
old_mask, new_mask = native_masks[ident], final_masks[ident]
|
|
if old_mask & ~new_mask or old_mask ^ new_mask != allowed.get(ident, 0):
|
|
raise ValueError('native field preservation or group scope differs')
|
|
if old_mask != new_mask:
|
|
replacements.append(dict(table_name='SpellClassOptions', id=before['ID'],
|
|
before=copy.deepcopy(before), record=copy.deepcopy(after)))
|
|
result = dict(policy='additive-unused-native-disjoint-group-bit-v1', family=family,
|
|
baseline_source_inventory_sha256=policy._sha(source),
|
|
baseline_native_inventory_sha256=policy._sha(target),
|
|
baseline_closure_sha256=policy._sha(closure),
|
|
canonical_groups_sha256=policy._sha(canonical),
|
|
baseline_unused_native_bits=list(reversed(free)),
|
|
groups=allocations, record_replacements=replacements, native_inventory=changed,
|
|
all_existing_native_fields_and_bits_preserved=True,
|
|
new_parent_definitions_authored=False, installable_package=False,
|
|
requires_final_composer_revalidation=True)
|
|
if used_membership:
|
|
result["membership_proofs_used"] = used_membership
|
|
return result
|