"""Deterministic fake-clock arithmetic, not an HTTP latency/cancellation test."""
import json
DEADLINE=2500;RESERVE=200;CAP=900;MIN_USEFUL=300;BACKOFF=150

def journey(setup,first,second):
 now=setup;steps=[['setup',setup,now]]
 cap=min(CAP,DEADLINE-now-RESERVE)
 assert first<=cap and cap>=MIN_USEFUL
 now+=first;steps.append(['first request',first,now])
 retry_cap=min(CAP,DEADLINE-now-BACKOFF-RESERVE)
 if retry_cap<MIN_USEFUL:
  decision='skip retry';now+=RESERVE;steps.append(['prepare failure response',RESERVE,now])
 else:
  decision='retry';now+=BACKOFF;steps.append(['backoff',BACKOFF,now])
  assert second<=retry_cap;now+=second;steps.append(['second request',second,now])
  now+=RESERVE;steps.append(['prepare success response',RESERVE,now])
 assert now<=DEADLINE
 return {'decision':decision,'retryCap':retry_cap,'steps':steps,'finishedAt':now,'slack':DEADLINE-now}
normal=journey(200,700,900);slow=journey(1200,900,0)
assert normal['finishedAt']==2150 and normal['slack']==350
assert slow['decision']=='skip retry' and slow['retryCap']==50 and slow['finishedAt']==2300
current=2;display=None;accepted=[]
for generation,result in [(2,'new search result'),(1,'old search result')]:
 if generation==current:display=result;accepted.append(generation)
assert display=='new search result' and accepted==[2]
report={'normal':normal,'slowSetup':slow,'staleResultGuard':{'acceptedGenerations':accepted,'display':display},'nestedMaximumCalls':3*3}
if __name__=='__main__':print(json.dumps(report,indent=2))
