"""Independent zero-DB verification of exact failed read retest, never report it as pass."""
from pathlib import Path
import json,hashlib,re
HERE=Path(__file__).resolve().parent;P=HERE.parent;RAW=Path('/tmp/cdx-ai-customer-weight-retest-20261011');OLD=Path('/tmp/cdx-ai-api-customer-read12-20261011')
def load(p):return json.loads(p.read_text())
def lines(p):return [json.loads(x) for x in p.read_text().splitlines()]
checks=0
def need(ok,label):
 global checks
 checks+=1
 if not ok:raise AssertionError(label)
pins=load(P/'source-frozen-sha.json')['files'];out={}
for lane in ['B','C']:
 p=RAW/f'private-{lane}-final';base=load(p/'budget-baseline.json');original=OLD/f'private-{lane}-final/sql-budget.jsonl';budget=(p/'sql-budget.jsonl').read_bytes();old=original.read_bytes()
 need(hashlib.sha256(old).hexdigest()==base['old_SQL_SHA'] and budget.startswith(old),'Unmodified old budget carried forward without reset')
 count=len(budget.splitlines());need(count<=600 and [x['n'] for x in lines(p/'sql-budget.jsonl')]==list(range(1,count+1)),'Cumulative600 all reads')
 need(load(p/'run-complete.json')['actual_HTTP']==1 and list(load(p/'cases.json'))==['WEIGHT_RETEST'],'Exactly one additional failed-path request')
 pre=load(p/'preflight-read.json');final=load(p/'persistence-final.json');need(pre['user_fullrows']==final['user_fullrows'] and pre['weight_fullrows']==final['weight_fullrows'] and pre['protection']==final['protection'] and final['unchanged'],'Whole original actor/weight/13/financial state preserved')
 need(load(p/'expected.json')=={'WEIGHT_RETEST':load(OLD/f'private-{lane}-final/expected.json')['WEIGHT']},'Original typed normal DTO oracle unchanged')
 r=load(p/'response-WEIGHT_RETEST.json');client=load(p/'client-WEIGHT_RETEST.json');need(r['raw_response_body']==client['body_raw'] and r['http_status']==client['http_status']==200,'Original response saved first and actual client bytes unchanged')
 body=json.loads(r['raw_response_body']);need(list(body)==['message','status','data','trace_id'] and body['status']==500 and body['data']==[] and type(body['trace_id']) is str and re.fullmatch('[0-9a-f]{13}',body['trace_id']) is not None,'Actual complete blocked response/type/order')
 events=lines(p/'business-native.jsonl');formal=[e for e in events if e['scenario']=='WEIGHT_RETEST'];errors=[e for e in formal if 'error' in e]
 need(errors and 'yoshop_user_weight_status' in (errors[-1]['queryString']+json.dumps(errors[-1].get('bind_plan',[]))).lower() and body['message']==errors[-1]['error']['message'],'Exact newly blocked original metadata dependency')
 actual=[e for e in events if e['layer']=='actual PDOStatement.execute'];need(all(e['operation'] in ['SELECT','metadata_SHOW','metadata_CALL'] for e in actual),'No actual DMLDDL')
 need(any('yoshop_staff' in (e['queryString']+json.dumps(e.get('bindValue',{}))).lower() for e in formal if e['layer']=='actual PDOStatement.execute'),'Authorized original staff metadata truly executed')
 included=load(p/'included-WEIGHT_RETEST.json')['files']
 for n,h in included.items():need(pins.get(n)==h,'Actualincluded source pin')
 src=load(p/'source-actual-fileset.json');need(src['actual_regular_files']==6168 and set(src['files'])==set(pins) and src['appledouble_magic_count']==0,'Actual complete source6168/magic0')
 for n,h in pins.items():need(src['files'][n]['sha256']==h,'Every actual frozen source byte')
 need(load(p/'cleanup.json')['tokens']=={'U1':'revoked'} and load(p/'worker-stopped.json')['port_closed'] is True,'New token/worker/port cleaned')
 need(len(load(p/'cache-cleanup.json')['own_cache_files_removed'])==2 and load(p/'cache-cleanup.json')['shared_cache_touched'] is False,'Only two exact new caches cleaned')
 need(not list(p.glob('observer-error-*.json')) and not list(p.glob('harness-error-*.json')),'No observer failure/body changes')
 out[lane]={'HTTP':1,'cumulative_HTTP':11,'new_SQL':count-base['old_SQL'],'cumulative_SQL':count,'new_original_native_SQL':len(actual),'formal_native_SQL':sum(e['layer']=='actual PDOStatement.execute' for e in formal),'actualincluded':len(included),'result':'TOOL_BLOCKED_USER_WEIGHT_STATUS_METADATA','normal_DTO_pass':False,'business_DB_pass':False,'blocked_sql':errors[-1]['queryString'],'blocked_bind':errors[-1].get('bind_plan'), 'DML':0,'DDL':0}
freeze=load(HERE/'pre-HTTP-freeze.json')
for n,h in freeze['files'].items():need(hashlib.sha256((HERE/n).read_bytes()).hexdigest()==h,'Before-HTTP retest helper freeze unchanged')
need(hashlib.sha256((P/'oracle_lib.py').read_bytes()).hexdigest()==freeze['original_parent_oracle_SHA'],'Original independent oracle unchanged')
print(json.dumps({'checks':checks,'lanes':out,'SQL':0,'HTTP':0,'no_further_token_or_HTTP_loop':True},ensure_ascii=False,indent=2))
