import subprocess,json,base64,urllib.request,urllib.error,socket,time,hashlib,datetime
s=json.loads(subprocess.check_output(['kubectl','-n','arbi-serve','get','secret','arbi-serve-auth','-o','json']))
token=base64.b64decode(s['data']['internal_token']).decode().strip()
pod=json.loads(subprocess.check_output(['kubectl','-n','arbi-serve','get','pod','arbi-engines-0','-o','json']))
assert all(c['ready'] and c['restartCount']==0 for c in pod['status']['containerStatuses'])
assert pod['spec']['containers'][0]['image'].endswith(':slim-3064ef2')
with socket.socket() as s: s.bind(('127.0.0.1',0)); port=s.getsockname()[1]
pf=subprocess.Popen(['kubectl','-n','arbi-serve','port-forward','--address=127.0.0.1','pod/arbi-engines-0',str(port)+':8001'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
base='http://127.0.0.1:'+str(port)
def post(path,body,timeout=90):
 r=urllib.request.Request(base+path,data=json.dumps(body).encode(),headers={'Authorization':'Bearer '+token,'Content-Type':'application/json','X-Request-ID':'issue4295-near-limit-259k'})
 return urllib.request.urlopen(r,timeout=timeout)
def prompt(n):
 rows=[]
 for i in range(n):
  digest=hashlib.sha256(('issue4295-near-limit-record-'+str(i)).encode()).hexdigest()[:16]
  rows.append(f'Record {i:06d}: reference {digest}; cargo count {(i*7919)%100003}; destination ordinary; status reviewed.\n')
 for frac,key,value in ((.05,'FIRST','copper anchor'),(.5,'MIDDLE','emerald meadow'),(.95,'LAST','cobalt bridge')):
  rows.insert(int(n*frac),f'IMPORTANT QUALIFICATION ENTRY: {key} secret value is {value}.\n')
 return 'Near-limit fixture 4295-B. Read this synthetic ledger. Remember the FIRST, MIDDLE and LAST secret values.\n'+''.join(rows)+'\nReply with only FIRST, MIDDLE and LAST secret values, in that order, separated by semicolons.'
def body(n):
 return {'model':'Qwen3.8-27B','messages':[{'role':'user','content':prompt(n)}],'chat_template_kwargs':{'enable_thinking':False}}
receipt={'started_at':datetime.datetime.now(datetime.timezone.utc).isoformat(),'pod':'arbi-engines-0','source_image':pod['spec']['containers'][0]['image'],'pod_uid':pod['metadata']['uid'],'target_prompt_tokens':259800,'max_output_tokens':96,'scope':'One synthetic HTTP request to existing production serving engine; no new GPU process/configuration change.'}
try:
 for _ in range(100):
  if pf.poll() is not None: raise RuntimeError('Port forward exited')
  try:
   with socket.create_connection(('127.0.0.1',port),timeout=.2): break
  except OSError: time.sleep(.1)
 else: raise RuntimeError('Port forward not ready')
 lo,hi=0,10000
 while lo<hi:
  mid=(lo+hi)//2
  with post('/tokenize',body(mid)) as f: d=json.load(f)
  count=d['count']
  if count<259800: lo=mid+1
  else: hi=mid
 req=body(lo)
 with post('/tokenize',req) as f: d=json.load(f)
 count=d['count']; cap=d['max_model_len']
 assert 259800<=count and count+96<=cap,(count,cap)
 receipt.update(prompt_tokens=count,max_model_len=cap,prompt_sha256=hashlib.sha256(req['messages'][0]['content'].encode()).hexdigest(),records=lo)
 print(json.dumps({'stage':'tokenized','prompt_tokens':count,'max_model_len':cap,'records':lo}),flush=True)
 req.update(max_tokens=96,temperature=0,stream=True,stream_options={'include_usage':True})
 started=time.monotonic(); output=[]; usage=None; first=None
 with post('/v1/chat/completions',req,timeout=1200) as f:
  receipt['http_status']=f.status
  for raw in f:
   if not raw.startswith(b'data:'): continue
   data=raw[5:].strip()
   if data==b'[DONE]': break
   d=json.loads(data)
   if d.get('usage'): usage=d['usage']
   for c in d.get('choices',[]):
    text=c.get('delta',{}).get('content') or ''
    if text:
     if first is None:
      first=time.monotonic()-started
      print(json.dumps({'stage':'first_content','seconds':round(first,3)}),flush=True)
     output.append(text)
 answer=''.join(output)
 expected=['copper anchor','emerald meadow','cobalt bridge']
 positions=[answer.lower().find(x) for x in expected]
 receipt.update(elapsed_seconds=round(time.monotonic()-started,3),first_content_seconds=first,usage=usage,synthetic_answer=answer,recall_pass=all(p>=0 for p in positions) and positions==sorted(positions),completed_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
 print(json.dumps({'stage':'completed',**receipt}),flush=True)
except Exception as e:
 receipt.update(error_type=type(e).__name__,completed_at=datetime.datetime.now(datetime.timezone.utc).isoformat())
 if isinstance(e,urllib.error.HTTPError): receipt['http_status']=e.code
 print(json.dumps({'stage':'failed',**receipt}),flush=True)
 raise
finally:
 pf.terminate();pf.wait(timeout=10)
 with open('/tmp/4295-near-limit-receipt.json','w') as f: json.dump(receipt,f,indent=2)
