prophet-v2 / code /audit /06_refine_flagged.py
wchai's picture
v2 audited sample: 1,137 tasks, README with changes, audit and progress
341e402 verified
Raw History Blame Contribute Delete
17 kB
"""Re-verify the flagged runs from 05_exact_d1_and_cuts.py with JSON-escaped quotes (\\?") handled in
VERIF_DONE, VERIF_RUN, and JOB_JSON_RX, plus ZERO_LABEL in single-poll replies.
Runs in ~5 seconds on the subset of runs that had any flag in 05, updating verified_d1_cuts.json.
"""
import collections, glob, json, os, re, sys
from multiprocessing import Pool
import zstandard
V = '<ROOT>/'
sys.path.insert(0, V + 'data/scripts')
sys.path.insert(0, V + 'build_v2/scripts/v48')
import v48lib as L
SRC = '<RUNS>/release-20261202/'
OUT_V48 = V + 'build_v2/out_v49/'
SAMPLE_SET = {x.strip() for x in open(V + 'build_v2/sample_v49/ids.txt') if x.strip()}
FR = json.load(open(SRC + 'metadata/formal-results.json'))
RUN_META = {(r['task'], r['model_id']): r for r in FR['runs']}
TRACE_TRUTH = {}
for ln in open(V + 'audit/v2/out/runs_trace_truth.jsonl'):
if ln.strip():
d = json.loads(ln)
TRACE_TRUTH[(d['task'], d['model'])] = d
VID_RX = re.compile(r'verification_[0-9A-HJKMNP-TV-Z]{26}')
JOB_JSON_RX = re.compile(r'\\?"job\\?"\s*:\s*(\d+)\b')
VERIF_DONE = re.compile(r'\\?"(state|status)\\?"\s*:\s*\\?"(passed|failed|completed|terminated|error|errored|invalid|rejected)\\?"', re.I)
# Note: exclude shell-wrapper '"terminal_status":"completed"' and Promise.allSettled '"status":"fulfilled"'
SHELL_WRAP_DONE = re.compile(r'\\?"terminal_status\\?"\s*:\s*\\?"completed\\?"', re.I)
VERIF_RUN = re.compile(r'\\?"(state|status)\\?"\s*:\s*\\?"(running|queued|pending|in_progress|submitted)\\?"', re.I)
def records_with_vid(tx):
chunks = []
for line in re.split(r'\r?\n|\\n', tx):
if 'verification_' in line:
for sub in re.split(r'\}\s*\{', line):
vids = VID_RX.findall(sub)
if len(vids) == 1:
chunks.append((vids[0], sub))
elif len(vids) > 1:
for m in VID_RX.finditer(sub):
chunks.append((m.group(0), sub[max(0, m.start() - 900): m.end() + 250]))
return chunks
def records_with_job(tx):
chunks = []
for line in re.split(r'\r?\n|\\n', tx):
jids = JOB_JSON_RX.findall(line)
if len(jids) == 1:
chunks.append((jids[0], line))
elif len(jids) > 1:
for m in JOB_JSON_RX.finditer(line):
chunks.append((m.group(1), line[max(0, m.start() - 200): m.end() + 900]))
return chunks
def check_unit_for_node(j, N, U, ui, fam, node_tt):
n = N[j]
na = node_tt[j]
u = U[ui]
tx = u['text']
vals = L.node_values(n)
s_val = n.get('raw_score')
zero = (s_val is None or float(s_val) in (0.0, 100.0))
if na['d3_no_result']:
return 'LEAK_D3_NO_RESULT', f'node {j} has status=None ({na["fail_reason"][:60]})'
if u['t'] < n['t_submit']:
return 'LEAK_STILL_RUNNING', 'unit before t_submit'
if fam == 'C' and na['t_verif_done'] is not None and u['t'] < na['t_verif_done']:
return 'LEAK_STILL_RUNNING', f'unit {(na["t_verif_done"] - u["t"])/1000:.1f}s before C call_returned'
if fam != 'C':
nid = n['id']
recs = records_with_vid(tx)
my_recs = [seg for vid, seg in recs if vid == nid]
other_vids = {vid for vid, _ in recs if vid != nid}
if my_recs:
for seg in my_recs:
seg_clean = SHELL_WRAP_DONE.sub('', seg)
if VERIF_DONE.search(seg_clean) or any(L.shows_value(seg_clean, v) for v in vals):
if not VERIF_RUN.search(seg_clean):
return 'VALID_ID', 'id+done/score'
if any(VERIF_RUN.search(seg) for seg in my_recs):
return 'LEAK_STILL_RUNNING', f'{nid[-8:]} explicitly state=running in unit'
prev_asst = None
sibling_tool_units = []
for k in range(ui - 1, -1, -1):
if U[k]['kind'] == 'response':
continue
if U[k]['thread'] == u['thread']:
if U[k]['kind'] == 'assistant':
prev_asst = U[k]['text']
for m_k in range(k + 1, len(U)):
if U[m_k]['kind'] == 'response':
continue
if U[m_k]['thread'] == u['thread']:
if U[m_k]['kind'] in ('tool', 'user'):
sibling_tool_units.append((m_k, U[m_k]['text']))
else:
break
break
for sib_i, sib_tx in sibling_tool_units:
if nid in sib_tx and sib_i != ui:
for vid, seg in records_with_vid(sib_tx):
if vid == nid and VERIF_RUN.search(seg):
return 'LEAK_STILL_RUNNING', f'parallel poll: {nid[-8:]} is state=running in sibling unit {sib_i}'
if sib_i > ui:
return 'LEAK_OTHER_ID', f'parallel poll: {nid[-8:]} returned later in unit {sib_i}, not {ui}'
if other_vids and nid not in {v for v, _ in recs}:
return 'LEAK_OTHER_ID', f'unit carries other vid(s) {sorted(x[-6:] for x in other_vids)[:2]}, not {nid[-6:]}'
tx_clean = SHELL_WRAP_DONE.sub('', tx)
if prev_asst and nid in prev_asst:
polled = set(VID_RX.findall(prev_asst))
if len(polled) == 1:
if any(L.shows_value(tx_clean, v) for v in vals) or VERIF_DONE.search(tx_clean) or (zero and L.ZERO_LABEL.search(tx_clean)):
return 'VALID_SINGLE_POLL', 'single poll reply'
if VERIF_RUN.search(tx_clean):
return 'LEAK_STILL_RUNNING', 'single poll reply shows only running'
if '...[' in tx and 'chars truncated]...' in tx:
return 'TRUNCATED_16K', 'single poll reply middle-truncated by 16k cap'
return 'LEAK_EMPTY_POLL_REPLY', 'single poll reply has empty/non-verifier output'
earlier_same = [m_idx for m_idx in range(j)
if N[m_idx].get('raw_score') is not None and s_val is not None
and abs(float(N[m_idx]['raw_score']) - float(s_val)) < 0.005]
dt_since_sub_s = (u['t'] - n['t_submit']) / 1000.0
is_sidecar = ('You are a safety and security rater' in tx or 'You are a reminder observer' in tx)
if not is_sidecar and not earlier_same and not zero and dt_since_sub_s >= 5.0 and any(L.shows_value(tx_clean, v) for v in vals):
return 'VALID_WRAPPER', f'unique nonzero score in tool result +{dt_since_sub_s:.0f}s after submit'
if earlier_same:
return 'LEAK_REPEATED_SCORE', f'no id/poll; matches earlier submission {earlier_same} (+{dt_since_sub_s:.0f}s after submit)'
return 'LEAK_FALSE_MATCH', f'no id/poll; sidecar={is_sidecar}, zero={zero} (+{dt_since_sub_s:.0f}s after submit)'
else:
j_num = n['id'].replace('job_', '')
recs = records_with_job(tx)
my_recs = [seg for jid, seg in recs if jid == j_num]
other_jobs = {jid for jid, _ in recs if jid != j_num}
if my_recs:
for seg in my_recs:
seg_clean = SHELL_WRAP_DONE.sub('', seg)
if not VERIF_RUN.search(seg_clean) and (VERIF_DONE.search(seg_clean) or any(L.shows_value(seg_clean, v) for v in vals) or L.C_RESULT.search(seg_clean)):
return 'VALID_ID', 'job_id+done/score'
if any(VERIF_RUN.search(seg) for seg in my_recs):
return 'LEAK_STILL_RUNNING', f'job_{j_num} explicitly state=running in unit'
if other_jobs and j_num not in {jid for jid, _ in recs}:
return 'LEAK_OTHER_ID', f'unit carries other job(s) {sorted(other_jobs)[:3]}, not job_{j_num}'
prev_asst = None
for k in range(ui - 1, -1, -1):
if U[k]['kind'] == 'response':
continue
if U[k]['thread'] == u['thread'] and U[k]['kind'] == 'assistant':
prev_asst = U[k]['text']
break
tx_clean = SHELL_WRAP_DONE.sub('', tx)
if prev_asst:
polled_jobs = set(re.findall(r'sandboxctl\s+status\s+(\d+)\b', prev_asst))
sync_call = bool(re.search(r'sandboxctl\s+call\s+train\b', prev_asst))
if polled_jobs and j_num not in polled_jobs:
return 'LEAK_OTHER_ID', f'assistant polled job(s) {sorted(polled_jobs)}, not job_{j_num}'
if polled_jobs == {j_num} or (sync_call and not polled_jobs):
if any(L.shows_value(tx_clean, v) for v in vals) or VERIF_DONE.search(tx_clean) or L.C_RESULT.search(tx_clean) or (zero and L.ZERO_LABEL.search(tx_clean)):
return 'VALID_SINGLE_POLL', 'c_single_poll'
if VERIF_RUN.search(tx_clean):
return 'LEAK_STILL_RUNNING', 'c_single_poll shows running'
if '...[' in tx and 'chars truncated]...' in tx:
return 'TRUNCATED_16K', 'c_poll_reply middle-truncated by 16k cap'
return 'LEAK_EMPTY_POLL_REPLY', 'c_poll_reply has no verifier output'
earlier_same = [m_idx for m_idx in range(j)
if N[m_idx].get('raw_score') is not None and s_val is not None
and abs(float(N[m_idx]['raw_score']) - float(s_val)) < 0.005]
is_sidecar = ('You are a safety and security rater' in tx or 'You are a reminder observer' in tx)
if not is_sidecar and not zero and any(L.shows_value(tx_clean, v) for v in vals) and not earlier_same:
return 'VALID_WRAPPER', 'c_post_return_unique_score_in_tool'
if earlier_same:
return 'LEAK_REPEATED_SCORE', f'c_no_job_id; matches earlier submission {earlier_same}'
return 'LEAK_FALSE_MATCH', f'c_no_job_id_no_poll (zero={zero})'
def fast_load_run(task, model):
norm_d = os.path.join(V, 'audit/tmp/norm', task, model)
uj = os.path.join(norm_d, 'units.jsonl.zst')
if os.path.exists(uj) and os.path.exists(os.path.join(norm_d, 'nodes.json')):
fam = json.load(open(os.path.join(norm_d, 'meta.json')))['family']
N = json.load(open(os.path.join(norm_d, 'nodes.json')))
raw_u = zstandard.ZstdDecompressor().decompress(open(uj, 'rb').read(), max_output_size=1 << 31).decode()
U = [json.loads(l) for l in raw_u.splitlines() if l]
L.refine(N, U)
return fam, U, N
run = RUN_META[(task, model)]
fam, U, N, _, _ = L.load_run(run)
return fam, U, N
def process_run(rk):
task, model = rk
fam, U, N = fast_load_run(task, model)
tt = TRACE_TRUTH[(task, model)]
node_tt = {na['idx']: na for na in tt['nodes']}
D, VIS = {}, {}
for n in N:
if n['mode'] != 'train':
continue
i, _ = L.deliver_index(n, U, fam)
e = L.echo_index(n, U, fam)
w = L.window_index(n, U, fam)
if w is not None and (e is None or w < e):
e = w
if e is not None and (i is None or e < i):
VIS[n['idx']] = e
D[n['idx']] = None
else:
VIS[n['idx']] = i
D[n['idx']] = i
true_vis = {}
for n in N:
if n['mode'] != 'train':
continue
j = n['idx']
vj = VIS.get(j)
if vj is not None and U[vj]['kind'] not in ('assistant', 'response'):
st0, _ = check_unit_for_node(j, N, U, vj, fam, node_tt)
if st0.startswith('VALID_') or st0 == 'TRUNCATED_16K':
true_vis[j] = vj
continue
elif vj is not None:
s_val = n.get('raw_score')
earlier_same = [m_idx for m_idx in range(j)
if N[m_idx].get('raw_score') is not None and s_val is not None
and abs(float(N[m_idx]['raw_score']) - float(s_val)) < 0.005]
if not node_tt[j]['d3_no_result'] and not earlier_same:
true_vis[j] = vj
continue
tv = None
start_ui = (vj + 1) if vj is not None else 0
for ui in range(start_ui, len(U)):
if U[ui]['kind'] in ('assistant', 'response') or U[ui]['t'] < n['t_submit']:
continue
st, _ = check_unit_for_node(j, N, U, ui, fam, node_tt)
if st.startswith('VALID_') or st == 'TRUNCATED_16K':
tv = ui
break
true_vis[j] = tv
fin = [n for n in N if n['mode'] == 'final']
fin_pos = None
if fin and fam != 'C':
f = dict(fin[0]); f['mode'] = 'train_probe'
fin_pos, _ = L.deliver_index(f, U, fam)
by_t = collections.defaultdict(list)
for idx, i in D.items():
if i is not None:
by_t[U[i]['t']].append(idx)
out_rows = []
for T in sorted(by_t):
recv = sorted(by_t[T])
K = max(D[j] for j in recv)
if fin_pos is not None and K >= fin_pos:
continue
vis = [n for n in N if n['mode'] == 'train' and VIS.get(n['idx']) is not None and VIS[n['idx']] <= K]
vis_idx = {n['idx'] for n in vis}
tgt_nodes = [n for n in N if n['idx'] not in vis_idx]
if not tgt_nodes:
continue
r = max(recv)
tid = L.task_id(task, model, r)
bad_c, trunc_c = [], []
for j in recv:
st, det = check_unit_for_node(j, N, U, K, fam, node_tt)
if not st.startswith('VALID_') and D[j] != K:
st2, det2 = check_unit_for_node(j, N, U, D[j], fam, node_tt)
if st2.startswith('VALID_') or st2 == 'TRUNCATED_16K':
st, det = st2, det2
if st == 'TRUNCATED_16K':
trunc_c.append((j, st, det, true_vis.get(j)))
elif not st.startswith('VALID_'):
bad_c.append((j, st, det, true_vis.get(j)))
else:
u_dj = U[D[j]]['text']
s_val = N[j].get('raw_score')
vals = L.node_values(N[j])
zero = (s_val is None or float(s_val) in (0.0, 100.0))
if not zero and not any(L.shows_value(u_dj, v) for v in vals) and '...[' in u_dj:
trunc_c.append((j, 'SCORE_TRUNCATED_16K', 'id/state present, raw_score truncated out by 16k cap', D[j]))
bad_s = []
for n in vis:
j = n['idx']
tv = true_vis.get(j)
if tv is None or tv > K:
st_v, det_v = check_unit_for_node(j, N, U, VIS[j], fam, node_tt)
bad_s.append((j, st_v, det_v, tv, K))
out_rows.append((tid, bad_c, trunc_c, bad_s))
return out_rows
def main():
prev = json.load(open(V + 'audit/v49/out/verified_d1_cuts.json'))
# Map task_id back to (task, model) for all previously flagged tasks, plus any muse runs (to check SHELL_WRAP_DONE!)
idx = json.load(open(OUT_V48 + 'metadata/task_index.json'))
tid_to_rk = {r['task_id']: (r['fcs_task'], r['model']) for r in idx}
flagged_rks = set()
for tid, _ in prev['bad_cuts_full'] + prev['trunc_cuts_full'] + prev['d1_tasks_full']:
flagged_rks.add(tid_to_rk[tid])
for r in idx:
if 'muse' in r['model']:
flagged_rks.add((r['fcs_task'], r['model']))
print('Re-checking flagged + muse runs:', len(flagged_rks), flush=True)
with Pool(6) as pool:
all_res = list(pool.imap_unordered(process_run, sorted(flagged_rks)))
bad_cuts_full, trunc_cuts_full, d1_tasks_full = [], [], []
cut_cats = collections.Counter()
for rr in all_res:
for tid, bad_c, trunc_c, bad_s in rr:
for _, st, _, _ in bad_c:
cut_cats[st] += 1
if bad_c:
bad_cuts_full.append((tid, bad_c))
if trunc_c:
trunc_cuts_full.append((tid, trunc_c))
if bad_s:
d1_tasks_full.append((tid, bad_s))
bad_cuts_full.sort()
trunc_cuts_full.sort()
d1_tasks_full.sort()
print('=== FINAL ZERO-FP CUT & D1 RESULTS ===')
print('bad_cut_tasks (full / sample):', len(bad_cuts_full), '/', sum(1 for t, _ in bad_cuts_full if t in SAMPLE_SET))
print(' by category:', dict(cut_cats))
print(' sample bad_cuts:')
for t, bc in bad_cuts_full:
if t in SAMPLE_SET:
print(' ', t, bc)
print('trunc_16k_cut_tasks (full / sample):', len(trunc_cuts_full), '/', sum(1 for t, _ in trunc_cuts_full if t in SAMPLE_SET))
for x in trunc_cuts_full[:12]:
print(' trunc_cut:', x)
print('d1_tasks (full / sample):', len(d1_tasks_full), 'pairs=', sum(len(x[1]) for x in d1_tasks_full),
'/', sum(1 for t, _ in d1_tasks_full if t in SAMPLE_SET))
d1_cats = collections.Counter(x[1] for _, bl in d1_tasks_full for x in bl)
print(' d1 pair reasons:', dict(d1_cats))
json.dump({
'bad_cuts_full': bad_cuts_full,
'trunc_cuts_full': trunc_cuts_full,
'd1_tasks_full': d1_tasks_full,
}, open(V + 'audit/v49/out/verified_d1_cuts.json', 'w'), indent=1)
if __name__ == '__main__':
main()