"""Original groupby adjacent-run/global grouping and shared iterator witness."""
from itertools import groupby,product
from collections import Counter
import json

def validate(records):
 if type(records) is not list or len(records)>16 or any(type(r) is not tuple or len(r)!=2 or type(r[0]) is not str or not 1<=len(r[0])<=8 or type(r[1]) is not int or not 0<=r[1]<=1000 for r in records) or len({r[1] for r in records})!=len(records):raise ValueError('0..16 bounded stringkey/integeruniqueID records')

def analyze(records):
 validate(records);adjacent=[{'key':key,'ids':[r[1] for r in rows]} for key,rows in groupby(records,key=lambda r:r[0])]
 naive={r['key']:r['ids'] for r in adjacent};correct={key:[r[1] for r in rows] for key,rows in groupby(sorted(records,key=lambda r:r[0]),key=lambda r:r[0])}
 # Independent global append and direct run-length loop.
 ref={};runs=[]
 for key,ident in records:
  ref.setdefault(key,[]).append(ident)
  if not runs or runs[-1]['key']!=key:runs.append({'key':key,'ids':[]})
  runs[-1]['ids'].append(ident)
 assert adjacent==runs and correct==ref and Counter(v for values in correct.values() for v in values)==Counter(r[1] for r in records)
 return {'records':records,'adjacent_runs':adjacent,'naive_dict_overwrites_nonadjacent_key':naive,'sorted_samekey_materialized_global':correct,'independent_append_dict':ref}

def demo():
 main=analyze([('A',1),('B',2),('A',3)]);assert main['naive_dict_overwrites_nonadjacent_key']['A']==[3] and main['sorted_samekey_materialized_global']['A']==[1,3]
 g=groupby('AABB');first_key,first=next(g);second_key,second=next(g);old=list(first);current=list(second);assert (first_key,second_key,old,current)==('A','B',[],['B','B'])
 g=groupby('AABB');_,first=next(g);saved=list(first);_,second=next(g);assert saved==['A','A'] and list(second)==['B','B']
 wrong_sort=sorted(main['records'],key=lambda r:r[1]);assert len(analyze(wrong_sort)['adjacent_runs'])==3
 cases=0
 for n in range(7):
  for seq in product('AB',repeat=n):analyze([(key,i) for i,key in enumerate(seq)]);cases+=1
 assert cases==127 and analyze([])['adjacent_runs']==[]
 rejected=[]
 for bad in [[('A',True)],[('A',1),('B',1)],[(None,1)],[('A',i) for i in range(17)]]:
  try:analyze(bad)
  except ValueError:rejected.append(repr(bad))
  else:raise AssertionError('expected rejection')
 return {'nonadjacent_key_example':main,'shared_iterator_after_advancing_outer':{'first_key':first_key,'second_key':second_key,'uncached_old_group':old,'current_group':current},'materialize_before_advance_preserves_A':saved,'wrong_sort_by_ID_still_three_runs':True,'all127_binary_key_sequences_global_and_run_oracles':cases,'invalid_inputs_rejected':rejected,'scope':'actual Python3.12stdlib groupby with adjacent key contract; global sort/list materializesO(n), no Pandas/SQL engine/semantic merge/dedup/file deletion or stable group iterator after outer advance'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=True,indent=2))
