"""Authored finite deterministic top-k policy: descending score then ascending ID."""
import itertools,json,math,platform
import numpy as np
def select(rows,k):
 if type(k) is not int or not 0<=k<=len(rows) or len(rows)>8:raise ValueError('bounded integer k')
 if any(type(r) is not dict or set(r)!={'id','score'} or type(r['id']) is not str or not r['id'].isascii() or not 1<=len(r['id'])<=16 or type(r['score']) not in [int,float] for r in rows):raise ValueError('authored row schema')
 if len({r['id'] for r in rows})!=len(rows) or any(abs(r['score'])>1000000 or not math.isfinite(r['score']) for r in rows):raise ValueError('unique IDs and finite scores')
 if k==0:return []
 scores=np.array([r['score'] for r in rows],dtype=np.float64);indices=np.argpartition(-scores,k-1)[:k];threshold=min(float(scores[i]) for i in indices)
 strict=[r for r in rows if r['score']>threshold];ties=sorted((r for r in rows if r['score']==threshold),key=lambda r:r['id'])
 picked=strict+ties[:k-len(strict)];return sorted(picked,key=lambda r:(-r['score'],r['id']))
def demo():
 rows=[{'id':i,'score':s} for i,s in zip(['A','D','C','B','E'],[9,7,7,7,2],strict=True)]
 indices=np.argpartition(-np.array([r['score'] for r in rows]),2)[:3].tolist();naive=sorted([rows[i] for i in indices],key=lambda r:(-r['score'],r['id']))
 actual=select(rows,3);oracle=sorted(rows,key=lambda r:(-r['score'],r['id']))[:3]
 assert [r['id'] for r in actual]==['A','B','C'] and actual==oracle
 checks=0;naive_failures=0
 for perm in itertools.permutations(rows):
  p=list(perm)
  for k in range(6):assert select(p,k)==sorted(p,key=lambda r:(-r['score'],r['id']))[:k];checks+=1
  raw=np.argpartition(-np.array([r['score'] for r in p]),2)[:3];subset=sorted([p[int(i)] for i in raw],key=lambda r:(-r['score'],r['id']))
  naive_failures+=subset!=oracle
 assert checks==720 and naive_failures>0 and select([],0)==[]
 rejects=[]
 for label,a,k in [('negative',rows,-1),('too_large',rows,6),('boolean',rows,True),('nan',[{'id':'A','score':float('nan')}],1),('infinite',[{'id':'A','score':float('inf')}],1),('missing_id',[{'score':1}],1),('duplicate_id',[{'id':'A','score':1},{'id':'A','score':2}],1),('bigint_single',[{'id':'A','score':9007199254740995}],1),('bigint_pair',[{'id':'A','score':9007199254740995},{'id':'B','score':9007199254740994}],1),('huge_integer',[{'id':'A','score':10**1000}],1),('float_above_bound',[{'id':'A','score':1000000.0000000001}],1)]:
  try:select(a,k)
  except ValueError:rejects.append(label)
  else:raise AssertionError(label)
 boundary=[{'id':'A','score':1000000},{'id':'B','score':-1000000},{'id':'C','score':0.25}];boundary_result=select(boundary,2);assert [r['id'] for r in boundary_result]==['A','C']
 return {'score_contract':'plain int/float, finite, abs(score)<=1000000 before conversion; all allowed ints exactly representable in float64','boundary_input':boundary,'boundary_result':boundary_result,'v1_counterexamples_expected_ids':['A','A'],'runtime':platform.python_version(),'numpy':np.__version__,'input':rows,'k':3,'observed_argpartition_indices':indices,'sort_only_chosen':naive,'boundary_tie_aware':actual,'full_sort_oracle':oracle,'permutation_k_checks':checks,'naive_failures_among120':naive_failures,'rejected':rejects,'scope':'Authored bounded finite scores abs<=1000000/unique IDs/descending score ascending ID; argpartition tie output observed not universal. No speed or ranking-quality claims.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
