Files
mtusi2026lab6/scripts/recover_observations.py
T
2026-10-30 21:38:40 +03:00

58 lines
3.3 KiB
Python

"""Re-query persisted traces with bounded time range; preserve unsuccessful captures."""
from pathlib import Path
import json
import shutil
import time
import urllib.request
import urllib.parse
import sys
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
from observe_experiment import log_query,save
E=ROOT/'evidence'
def main():
archive=E/'initial_captures';archive.mkdir(exist_ok=True)
uploads=json.loads((E/'slo_uploads.json').read_text());requests=json.loads((E/'slo_requests.json').read_text())
intervals={}
for u in uploads:intervals[u['trace_id']]=(u['accepted_at']-60,u.get('ready_at',u['accepted_at']+180)+60)
for r in requests:
if r['trace_id']:intervals[r['trace_id']]=(r['time']-60,r['time']+r['seconds']+60)
outcomes=[]
for filename in ['signals_worker_2.json','signals_db_2.json']:
path=E/filename
if not (archive/filename).exists():shutil.copy2(path,archive/filename)
data=json.loads(path.read_text())
for tid,trace in list(data['traces'].items()):
if not trace.get('unavailable'):continue
a,b=intervals.get(tid,(time.time()-1800,time.time()))
url='http://localhost:3206/api/traces/'+tid+'?'+urllib.parse.urlencode({'start':int(a),'end':int(b)})
started=time.monotonic()
try:
with urllib.request.urlopen(url,timeout=60) as response:result=json.load(response)
data['traces'][tid]=result;status='retrieved'
except Exception as exc:status=type(exc).__name__
outcomes.append({'file':filename,'trace_id':tid,'status':status,'seconds':time.monotonic()-started,'start':a,'end':b})
if filename=='signals_db_2.json':
from audit_observability import spans
errors=[r for r in requests if r['phase']=='2_db_degraded' and r['status']==503 and r['trace_id']]
for row in errors[::max(1,len(errors)//10)]:
tid=row['trace_id'];a=row['time']-60;b=row['time']+row['seconds']+60
url='http://localhost:3206/api/traces/'+tid+'?'+urllib.parse.urlencode({'start':int(a),'end':int(b)})
started=time.monotonic()
try:
with urllib.request.urlopen(url,timeout=60) as response:result=json.load(response)
data['traces'][tid]=result;status='retrieved'
except Exception as exc:status=type(exc).__name__
outcomes.append({'file':filename,'trace_id':tid,'status':status,'seconds':time.monotonic()-started,'selection':'ordered diagnostic sample from real 503 requests'})
if status=='retrieved' and any(s['name']=='db.execute' and s.get('status',{}).get('code')=='STATUS_CODE_ERROR' for s in spans(result)):break
streams=[]
for tid,trace in data['traces'].items():
if not trace.get('unavailable'):
streams.extend(log_query('{service_name="messenger-api"} |= "'+tid+'"',limit=10)['data']['result'])
data['correlated_api_logs']={'status':'success','data':{'resultType':'streams','result':streams}}
data['recaptured_at']=time.time()
path.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
save('capture_recovery.json',outcomes)
print(json.dumps(outcomes,indent=2))
if __name__=='__main__':main()