269 lines
18 KiB
Python
269 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
# SPDX-License-Identifier: GPL-3.0-only
|
|
"""Bounded design-fixture validation. Does not load or simulate an engine."""
|
|
from __future__ import annotations
|
|
import argparse
|
|
import copy
|
|
import json
|
|
from pathlib import Path
|
|
from jsonschema import Draft202012Validator, FormatChecker
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
class ContractError(ValueError):
|
|
pass
|
|
|
|
def require(condition, reason):
|
|
if not condition:
|
|
raise ContractError(reason)
|
|
|
|
def walk(value):
|
|
yield value
|
|
if isinstance(value, dict):
|
|
for item in value.values():
|
|
yield from walk(item)
|
|
elif isinstance(value, list):
|
|
for item in value:
|
|
yield from walk(item)
|
|
|
|
def semantic(document):
|
|
revision_names = {'stateRevision','projectionRevision','expectedRevision','previousRevision',
|
|
'newRevision','eventRevision','sequence','lastSequence','sinceRevision',
|
|
'snapshotRevision','currentRevision','correctionRevision'}
|
|
for node in walk(document):
|
|
if not isinstance(node, dict):
|
|
continue
|
|
for key, value in node.items():
|
|
if key in revision_names and value is not None:
|
|
require(isinstance(value, str) and 0 <= int(value) <= 2**64-1, 'uint64 overflow')
|
|
if {'minor','currency'} <= node.keys():
|
|
require(isinstance(node['minor'],str) and -(2**63) <= int(node['minor']) <= 2**63-1,
|
|
'money int64 overflow')
|
|
if {'min','max','step'} <= node.keys():
|
|
require(node['min'] <= node['max'] and node['step'] > 0, 'invalid numeric scale')
|
|
if {'id','total','breakdown','ownerManagerId','expectedRevision'} <= node.keys():
|
|
require(sum(int(v['amount']['minor']) for v in node['breakdown']) == int(node['total']['minor']),
|
|
'quote breakdown mismatch')
|
|
if node.get('kind') == 'match':
|
|
match(node)
|
|
if node.get('kind') == 'toto':
|
|
ids=[fixture['id'] for fixture in node['fixtures']]
|
|
require(len(ids)==11 and len(set(ids))==11,'coupon fixture identity mismatch')
|
|
for column in node['columns']:
|
|
picks=[pick['fixtureId'] for pick in column['picks']]
|
|
require(len(picks)==11 and len(set(picks))==11 and set(picks)==set(ids),
|
|
'coupon pick bound to wrong fixture')
|
|
if node.get('kind') == 'squad':
|
|
require(node['rosterSize']==len(node['players']),'squad roster size mismatch')
|
|
if node['onFieldCount'] is not None:
|
|
require(node['onFieldCount']==sum(p['role']=='starter' for p in node['players']),
|
|
'squad field count mismatch')
|
|
if node.get('kind') == 'manager_archive':
|
|
require(all(m['control']=='archived' for m in node['managers']),'active person in archive')
|
|
if node.get('kind') == 'session':
|
|
managers = node['managers']
|
|
require(all(m['control']=='human' and m['status']=='active' for m in managers),'inactive manager in active roster')
|
|
require(len({m['slot'] for m in managers})==len(managers),'duplicate active slot')
|
|
require(not {m['id'] for m in managers}.intersection(node['archivedManagerIds']),'archived identity reused')
|
|
require(len({m['id'] for m in managers}) == len(managers), 'duplicate manager identity')
|
|
humans = {m['id']:m for m in managers if m['control']=='human' and m['status']=='active'}
|
|
ownership = node['humanOwnership']
|
|
require(len({r['teamId'] for r in ownership})==len(ownership), 'duplicate team ownership')
|
|
require(len({r['managerId'] for r in ownership})==len(ownership), 'duplicate manager ownership')
|
|
for r in ownership:
|
|
require(r['controller']=='human' and r['managerId'] in humans, 'ownership lacks active human')
|
|
require(humans[r['managerId']]['teamId']==r['teamId'], 'wrong owned team')
|
|
if node['sessionState'] in ['desktop','live','postmatch']:
|
|
require(node['activeManagerId'] in humans, 'active manager missing')
|
|
if node.get('kind') == 'ownership_change':
|
|
require(node['archivedIdentity']['id']==node['managerId'] and
|
|
node['archivedIdentity']['control']=='archived', 'archived identity changed')
|
|
remaining = {r['managerId'] for r in node['humanOwnership']}
|
|
require(node['managerId'] not in remaining, 'resigned human retained control')
|
|
if not remaining:
|
|
require(node['sessionState']=='ended' and node['activeManagerId'] is None and
|
|
node['terminationReason']=='last_human_resigned', 'last human did not terminate')
|
|
else:
|
|
require(node['sessionState']=='desktop' and node['activeManagerId'] in remaining and
|
|
node['aiHandover'] and node['terminationReason'] is None, 'AI handover inconsistent')
|
|
if node.get('kind') == 'correction':
|
|
require(node['supersedesId'] != node['id'], 'correction cycle')
|
|
if node['replacementMatch']:
|
|
require(node['replacementMatch']['id']==node['targetId'], 'correction changed match identity')
|
|
if document.get('messageType')=='snapshot':
|
|
meta=document['meta']
|
|
for node in walk(document['data']):
|
|
if not isinstance(node,dict):
|
|
continue
|
|
if {'minor','currency','minorUnits'} <= node.keys():
|
|
require(node['currency']==meta['currency']['code'] and
|
|
node['minorUnits']==meta['currency']['minorUnits'], 'currency precision mismatch')
|
|
if {'snapshotRevision','nextCursor'} <= node.keys():
|
|
require(node['snapshotRevision']==meta['stateRevision'], 'page revision mismatch')
|
|
if {'total','ownerManagerId','expectedRevision'} <= node.keys():
|
|
require(node['expectedRevision']==meta['stateRevision'] and
|
|
node['ownerManagerId']==meta['scope']['managerId'] and
|
|
node['teamId']==meta['scope']['teamId'], 'quote owner or revision mismatch')
|
|
data=document['data']
|
|
if data['kind']=='desktop' and data['team']['kind']=='national':
|
|
require(data['accounts'] is None, 'national desk acquired club cash')
|
|
for key in ['training','camps','bank','stadium','toto']:
|
|
require(data['menuAvailability'][key]['status']=='unavailable', 'national engine menu not blocked')
|
|
if document.get('messageType')=='command' and document['kind']=='career.start':
|
|
payload=document['payload']
|
|
for manager in payload['managers']:
|
|
name=manager['name']
|
|
require(name==name.strip() and 1<=len(name)<=24 and not any(ord(c)<32 or 127<=ord(c)<=159 for c in name),'invalid manager name')
|
|
require(payload['setup']['players']==len(payload['managers']), 'start manager count mismatch')
|
|
require(len({m['id'] for m in payload['managers']})==len(payload['managers']), 'duplicate start manager')
|
|
require(len({m['teamId'] for m in payload['managers']})==len(payload['managers']), 'duplicate start team')
|
|
require(len({m['portraitGuiKey'] for m in payload['managers']})==len(payload['managers']), 'duplicate portrait')
|
|
|
|
def match(m):
|
|
sides={m['home']['id']:'home',m['away']['id']:'away'}
|
|
require(len(sides)==2,'same match sides')
|
|
ids=[e['id'] for e in m['events']]
|
|
seq=[int(e['sequence']) for e in m['events']]
|
|
require(len(set(ids))==len(ids),'duplicate event identity')
|
|
require(all(a<b for a,b in zip(seq,seq[1:])),'out-of-order sequence')
|
|
r=m['result']
|
|
if r['regulation'] is not None and r['final'] is not None:
|
|
for side in ['home','away']:
|
|
extra=r['extra'][side] if r['extra'] is not None else 0
|
|
require(r['regulation'][side]+extra==r['final'][side], 'phase score mismatch')
|
|
if r['extraTimePlayed'] is True:
|
|
require(r['regulation'] is not None and r['extra'] is not None,'known ET lacks phase score')
|
|
if r['extraTimePlayed'] is None:
|
|
require(r['extra'] is None,'unknown ET fabricated extra score')
|
|
known_rosters={}
|
|
for lineup in m['lineups']:
|
|
require(lineup['teamId'] in sides,'lineup on wrong team')
|
|
all_players=lineup['starters']+lineup['bench']
|
|
pids=[p['id'] for p in all_players]
|
|
require(len(set(pids))==len(pids),'duplicate lineup player')
|
|
require(lineup['rosterSize']==len(pids),'roster size mismatch')
|
|
if lineup['classificationKnown']:
|
|
require(lineup['onFieldCount']==len(lineup['starters']),'on-field count mismatch')
|
|
require(len(lineup['starters'])<=lineup['onFieldLimit'],'too many field players')
|
|
if m['rules']['rosterLimit'] is not None:
|
|
require(len(pids)<=m['rules']['rosterLimit'],'roster limit exceeded')
|
|
if lineup['coverage']['status']=='complete':
|
|
known_rosters[lineup['teamId']]=set(pids)
|
|
if m['mode']=='indoor':
|
|
# Explicitly the supplied source-aligned synthetic example, not a new simulation rule.
|
|
require(m['rules']['onFieldLimit']==6 and m['rules']['rosterLimit']==11,
|
|
'indoor example contradicts verified six/eleven context')
|
|
goals={'home':0,'away':0};kicks={'home':0,'away':0}
|
|
for e in m['events']:
|
|
require(e['teamId'] is None or e['teamId'] in sides,'event team outside match')
|
|
if e['actorPlayerId'] is not None and e['teamId'] in known_rosters:
|
|
require(e['actorPlayerId'] in known_rosters[e['teamId']],'actor outside recorded roster')
|
|
if e['kind'] in ['goal','own_goal']:
|
|
require(e['recipientTeamId'] in sides,'goal recipient unknown')
|
|
goals[sides[e['recipientTeamId']]]+=1
|
|
if e['kind']=='shootout_kick':
|
|
require(isinstance(e['scored'],bool),'shootout outcome missing')
|
|
if e['scored']:kicks[sides[e['teamId']]]+=1
|
|
missing=set(m['coverage']['missing'])
|
|
if r['status']=='completed' and r['final'] is not None and 'events' not in missing:
|
|
require(goals==r['final'],'event goals mismatch final score')
|
|
if r['shootout'] is not None and not missing.intersection({'events','shootout_order'}):
|
|
require(kicks==r['shootout'],'shootout tally mismatch')
|
|
if r['decision']=='shootout':
|
|
require(r['shootout'] is not None,'shootout score missing')
|
|
if r['winnerTeamId'] is not None:
|
|
winner='home' if r['shootout']['home']>r['shootout']['away'] else 'away'
|
|
require(r['shootout']['home']!=r['shootout']['away'] and
|
|
m[winner]['id']==r['winnerTeamId'],'wrong shootout winner')
|
|
|
|
def main():
|
|
parser=argparse.ArgumentParser();parser.add_argument('--out',type=Path)
|
|
args=parser.parse_args()
|
|
schema=json.loads((ROOT/'schemas/ui-contract.schema.json').read_text())
|
|
Draft202012Validator.check_schema(schema)
|
|
index=json.loads((ROOT/'examples/index.json').read_text())
|
|
results=[];fixtures={}
|
|
def check(name,fn):
|
|
try:fn();results.append({'check':name,'passed':True})
|
|
except Exception as exc:results.append({'check':name,'passed':False,'error':str(exc)})
|
|
def validate(doc,ref='#'):
|
|
chosen=schema if ref=='#' else {'$defs':schema['$defs'],'$ref':ref}
|
|
Draft202012Validator(chosen,format_checker=FormatChecker()).validate(doc)
|
|
semantic(doc)
|
|
for item in index['fixtures']:
|
|
doc=json.loads((ROOT/'examples'/item['file']).read_text());fixtures[item['file']]=doc
|
|
check('fixture:'+item['file'],lambda d=doc,r=item['schemaRef']:validate(d,r))
|
|
def negative(name,file,mutate,ref='#'):
|
|
doc=copy.deepcopy(fixtures[file]);mutate(doc)
|
|
def action():
|
|
try:validate(doc,ref)
|
|
except Exception:return
|
|
raise AssertionError('Invalid contract fixture was accepted')
|
|
check('reject:'+name,action)
|
|
negative('html-payload','desktop-club.json',lambda d:d['data'].update(html='<b>untrusted</b>'))
|
|
negative('invalid-date','desktop-club.json',lambda d:d['meta'].update(date='2027-02-30'))
|
|
negative('fractional-cent','desktop-club.json',lambda d:d['data']['accounts']['cash'].update(minor=1.5))
|
|
negative('money-overflow','desktop-club.json',lambda d:d['data']['accounts']['cash'].update(minor=str(2**63)))
|
|
negative('revision-overflow','desktop-club.json',lambda d:d['meta'].update(stateRevision=str(2**64)))
|
|
negative('currency-precision','desktop-club.json',lambda d:d['data']['accounts']['cash'].update(minorUnits=0))
|
|
negative('et-final-sum','match-extra-time.json',lambda d:d['data']['result']['final'].update(home=3))
|
|
negative('pso-added-to-goals','match-national-shootout.json',lambda d:d['data']['result']['final'].update(home=7))
|
|
negative('duplicate-event','match-extra-time.json',lambda d:d['data']['events'].append(copy.deepcopy(d['data']['events'][0])))
|
|
negative('reordered-pso','match-national-shootout.json',lambda d:d['data']['events'].reverse())
|
|
negative('indoor-eleven','match-indoor.json',lambda d:d['data']['rules'].update(onFieldLimit=11))
|
|
negative('roster-size','match-indoor.json',lambda d:d['data']['lineups'][0].update(rosterSize=11))
|
|
negative('foreign-actor','match-extra-time.json',lambda d:d['data']['events'][0].update(actorPlayerId='player:other-1'))
|
|
negative('duplicate-ownership','session-four-managers.json',lambda d:d['data']['humanOwnership'][1].update(teamId=d['data']['humanOwnership'][0]['teamId']))
|
|
negative('last-human-active','manager-last-human-game-end.json',lambda d:d['ownershipChange'].update(activeManagerId='manager:career-demo-1'))
|
|
negative('correction-id-change','almanac-correction.json',lambda d:d['replacementMatch'].update(id='match:different'),'#/$defs/Correction')
|
|
negative('correction-cycle','almanac-correction.json',lambda d:d.update(supersedesId=d['id']),'#/$defs/Correction')
|
|
negative('quote-sum','camps.json',lambda d:d['data']['camps'][0]['quote']['total'].update(minor='1'))
|
|
negative('page-revision','squad.json',lambda d:d['data']['page'].update(snapshotRevision='39'))
|
|
negative('quote-owner','camps.json',lambda d:d['data']['camps'][0]['quote'].update(ownerManagerId='manager:career-demo-2'))
|
|
negative('start-count','command-career-start.json',lambda d:d['payload']['setup'].update(players=3))
|
|
negative('coupon-wrong-fixture','toto.json',lambda d:d['data']['columns'][0]['picks'][0].update(fixtureId='fixture:other'))
|
|
def command_context(command, current, current_meta):
|
|
require(command['careerId']==current_meta['careerId'] and command['worldId']==current_meta['worldId'], 'wrong career/world')
|
|
require(command['expectedRevision']==current_meta['stateRevision'], 'stale command revision')
|
|
owner=command['owner']
|
|
require(owner['managerId']==current['activeManagerId'],'wrong active manager')
|
|
manager=next(m for m in current['managers'] if m['id']==owner['managerId'])
|
|
require(owner['teamId']==manager['teamId'],'wrong command team')
|
|
current=fixtures['session-four-managers.json']
|
|
check('command-owner-context',lambda:command_context(fixtures['command-resign.json'],current['data'],current['meta']))
|
|
def reject_context(field,value):
|
|
altered=copy.deepcopy(fixtures['command-resign.json'])
|
|
if field=='managerId':altered['owner'][field]=value
|
|
else:altered[field]=value
|
|
try:command_context(altered,current['data'],current['meta'])
|
|
except ContractError:return
|
|
raise AssertionError('stale or foreign command accepted by reference contract check')
|
|
check('reject:stale-command-context',lambda:reject_context('expectedRevision','39'))
|
|
check('reject:foreign-manager-context',lambda:reject_context('managerId','manager:career-demo-2'))
|
|
check('reject:foreign-world-context',lambda:reject_context('worldId','world:other'))
|
|
observed={d['data']['kind'] for d in fixtures.values() if d.get('messageType')=='snapshot'}
|
|
expected=set(json.loads((ROOT/'schemas/contract-index.json').read_text())['readKinds'])
|
|
check('all-read-model-kinds-have-fixtures',lambda:require(observed==expected,'missing read model sample'))
|
|
legacy=fixtures['match-legacy-unknown-phases.json']['data']
|
|
check('legacy-pso-does-not-invent-et',lambda:require(legacy['result']['extraTimePlayed'] is None and legacy['result']['regulation'] is None,'invented phase'))
|
|
pso=fixtures['match-national-shootout.json']['data']
|
|
check('shootout-excluded-from-match-goals',lambda:require(sum(1 for e in pso['events'] if e['kind']=='goal')==4 and sum(pso['result']['shootout'].values())==9,'PSO counted as match goals'))
|
|
match_et=fixtures['match-extra-time.json']['data']
|
|
appeared={p['id'] for p in match_et['lineups'][0]['starters']}|{e['actorPlayerId'] for e in match_et['events'] if e['kind']=='substitution' and e['teamId']==match_et['home']['id']}
|
|
check('appearance-union-starters-and-entered-bench',lambda:require(len(appeared)==12 and 'player:harbor-12' not in appeared,'bench counted without entry'))
|
|
check('zero-attendance-and-weather-remain-known',lambda:require(match_et['attendance']==0 and match_et['weather']['temperatureCelsius']==0 and 'attendance' not in match_et['coverage']['missing'],'known zero lost'))
|
|
menus=json.loads((ROOT/'menu-contracts.json').read_text())['menus']
|
|
check('all-menu-read-references-resolve',lambda:require(all(set(m['readModels'])<=expected for m in menus),'unknown menu read kind'))
|
|
report={'status':'design_fixture_qa_only','engineExecuted':False,'nativeUiTested':False,
|
|
'fixtureCount':len(index['fixtures']),'readKinds':len(expected),'menuCount':len(menus),
|
|
'passed':sum(x['passed'] for x in results),'failed':sum(not x['passed'] for x in results),'checks':results}
|
|
rendered=json.dumps(report,ensure_ascii=False,indent=2)+'\n'
|
|
if args.out:args.out.write_text(rendered)
|
|
print(json.dumps({k:v for k,v in report.items() if k!='checks'},ensure_ascii=False))
|
|
if report['failed']:
|
|
for result in results:
|
|
if not result['passed']:print(json.dumps(result,ensure_ascii=False))
|
|
return 1 if report['failed'] else 0
|
|
|
|
if __name__=='__main__':raise SystemExit(main())
|