File size: 8,514 Bytes
0749819
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
"""Extend both Python arms without changing source rows or selecting by reward."""
from pathlib import Path
import os,sys,json,hashlib,fcntl,copy,argparse
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED
from dataclasses import replace
BASE=Path(__file__).resolve().parent;ROOT=BASE.parents[2]
os.environ.setdefault('CGD_ARTIFACTS',str(ROOT/'artifacts'))
sys.path.insert(0,str(BASE/'runtime'))
from code_search import data,harness,sft,vllm,colgrep
from code_search.harness.manifest import SamplingSpec
from code_search.sft.export import export_sft_trace
from code_search.colgrep import run as colgrep_run
from code_search.terminal.sandbox import Terminal

MODEL='deepseek-ai/DeepSeek-V4-Flash-0731'
def validate_messages(row):
 pending=set();seen=set()
 for m in row['messages']:
  if m['role']=='assistant':
   if pending:raise ValueError('Missing tool reply')
   calls=m.get('tool_calls') or []
   if len(calls)>5:raise ValueError('Tool call limit')
   for c in calls:
    cid=c['id'];a=json.loads(c['function']['arguments'])
    if not isinstance(a,dict) or not cid or cid in seen:raise ValueError('Malformed tool call')
    pending.add(cid);seen.add(cid)
  elif m['role']=='tool':
   if m.get('tool_call_id') not in pending:raise ValueError('Orphan tool reply')
   pending.remove(m['tool_call_id'])
 if pending:raise ValueError('Missing final tool reply')

def manifests(arm):
 student=json.loads((BASE/f'{arm}-student-protocol.json').read_text())
 common=dict(model_id=MODEL,parser_profile='deepseek_v4',search_tool=arm,max_turns=10,max_retries=6,remind_before_end=2,finish_turns=2,rescue_policy='force_then_harvest',sampling=SamplingSpec(temperature=.3,max_tokens=1024),colgrep=harness.ColgrepSpec(model='lightonai/LateOn-Code-edge',top_k=10,force_cpu=True,no_update=True))
 export=harness.build_structured_manifest(**common)
 assert export.system_prompt==student['system_prompt'] and list(export.tool_schema)==student['tools']
 teacher=harness.build_structured_manifest(**common,colgrep_only=arm=='colgrep',extra={'purpose':'python_unfiltered_count_topup','runtime':str(BASE/'runtime'),'thinking':False})
 return teacher,export

def rolling_results(fn, items, needed, workers):
 # Bound successful + in-flight rows by the remaining quota, avoiding overshoot.
 cursor=0; accepted=0; failures=0
 with ThreadPoolExecutor(max_workers=workers) as pool:
  active=set()
  while accepted<needed:
   while cursor<len(items) and len(active)<workers and accepted+len(active)<needed:
    active.add(pool.submit(fn,items[cursor]));cursor+=1
   if not active:break
   ready,active=wait(active,return_when=FIRST_COMPLETED)
   for future in ready:
    row,error=future.result()
    if error:failures+=1
    else:accepted+=1;failures=0
    yield row,error
    if failures>=8:raise RuntimeError('Eight consecutive generation failures; stopping')

def run_arm(arm,url,pilot=False,workers=48):
 prep=json.loads((BASE/'preparation.json').read_text()); target=prep['baseline'][arm]['additional_needed']
 state=BASE/arm;state.mkdir(exist_ok=True);lock=(state/'generation.lock').open('w');fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
 teacher_manifest,student_manifest=manifests(arm)
 manifestfile=state/'generation-manifest.json'
 if manifestfile.exists():assert json.loads(manifestfile.read_text())==teacher_manifest.to_dict()
 else:teacher_manifest.write(manifestfile)
 rawfile=state/'new-raw.jsonl';done={}
 if rawfile.exists():
  for line in rawfile.open():
   r=json.loads(line);assert r['instance_id'] not in done;done[r['instance_id']]=r
 candidates=[data.Instance.from_json(json.loads(l)) for l in (BASE/'tasks.jsonl').open()]
 assert hashlib.sha256((BASE/'tasks.jsonl').read_bytes()).hexdigest()==prep['candidate_tasks_sha256']
 pending=[r for r in candidates if r.instance_id not in done]
 llm=vllm.Client(model=MODEL,base_url=url,temperature=.3,max_tokens=1024,chat_template_kwargs={'enable_thinking':False},max_retries=4)
 vllm.assert_tool_calls(llm,list(teacher_manifest.tool_schema),system_prompt=teacher_manifest.system_prompt)
 colgrep_run._LOCAL_HF=os.environ.get('HF_HOME',colgrep_run._LOCAL_HF)
 def one(inst):
  try:
   outcome=harness.run_session(llm,instance_id=inst.instance_id,task=inst.problem_statement,repo=inst.checkout_dir,manifest=teacher_manifest)
   if outcome.end_reason in {'llm_error','context_overflow'}:raise RuntimeError(outcome.error or outcome.end_reason)
   row=export_sft_trace(outcome,manifest=teacher_manifest,gold={'files':sorted(inst.gold_files)})
   score=sft.score_instance(inst.instance_id,outcome.pred_spans,inst.gold,n_searches=outcome.n_searches,finished=outcome.finished)
   row.update({k:getattr(score,k) for k in ['file_recall','file_precision','file_f1','line_recall','found_all_files']})
   row.update(tools=list(teacher_manifest.tool_schema),repo=inst.repo,base_commit=inst.base_commit,language=inst.language,source=inst.source,events=outcome.events)
   validate_messages(row)
   try:weighted=sft.weight_record(row,inst.gold_files)
   except ValueError as exc:
    weighted=None;row["weighting_error"]=str(exc)
   # Match the historical Python release: only the system prompt/tool descriptions
   # are normalized to the exported student protocol, not assistant/tool content.
   # Raw/unfiltered ColGREP retains its strict teacher protocol, as in the source.
   student_messages=copy.deepcopy(row['messages']);student_messages[0]['content']=student_manifest.system_prompt
   if weighted:
    weighted['messages']=student_messages;weighted['tools']=list(student_manifest.tool_schema)
    assert len(weighted['turn_weights'])==sum(m['role']=='assistant' for m in row['messages'])
   row['_weighted']=weighted
   return row,None
  except Exception as e:return None,{'instance_id':inst.instance_id,'error':str(e)[:1500]}
 goal=min(target,4) if pilot else target
 errors=0
 with rawfile.open('a') as output,(state/'errors.jsonl').open('a') as err:
  for row,error in rolling_results(one,pending,max(0,goal-len(done)),min(workers,4) if pilot else workers):
   if error:err.write(json.dumps(error)+'\n');err.flush();errors+=1
   else:
    assert row['instance_id'] not in done
    output.write(json.dumps(row,ensure_ascii=False)+'\n');output.flush();done[row['instance_id']]=row
   status={'arm':arm,'new_unfiltered':len(done),'baseline_unfiltered':prep['baseline'][arm]['counts']['unfiltered'],'combined_unfiltered':len(done)+prep['baseline'][arm]['counts']['unfiltered'],'target':14500,'errors_this_run':errors,'pilot':pilot,'workers':workers}
   temporary=state/'progress.json.tmp';temporary.write_text(json.dumps(status,indent=2)+'\n');temporary.replace(state/'progress.json')
   print(json.dumps(status),flush=True)
 if len(done)<goal:raise RuntimeError(f'Candidate pool exhausted before {arm} target: {len(done)}/{goal}')
 if pilot:
  assert sum(r['n_searches']>0 for r in done.values())>=3,'Pilot search behavior failed'
  tool_errors=sum(bool(e['payload'].get('error')) for r in done.values() for e in r['events'] if e['kind']=='ToolCompleted')
  assert tool_errors<8,f'Pilot tool errors: {tool_errors}'
  if arm=='colgrep':assert any(r['retrieved_steps'] for r in done.values()),'Pilot produced no successful semantic retrieval'
 else:(state/'COMPLETE.json').write_text(json.dumps({'new_unfiltered':len(done),'combined_unfiltered':14500,'raw_sha256':hashlib.sha256(rawfile.read_bytes()).hexdigest()},indent=2)+'\n')
 llm._client.close();lock.close()

if __name__=='__main__':
 ap=argparse.ArgumentParser();ap.add_argument('--base-url',default='http://localhost:8001/v1');ap.add_argument('--preflight-only',action='store_true');ap.add_argument('--arm',choices=['grep','colgrep']);ap.add_argument('--workers',type=int,default=48);a=ap.parse_args()
 prep=json.loads((BASE/'preparation.json').read_text())
 for name,expected in prep['runtime_hashes'].items():assert hashlib.sha256((BASE/'runtime'/name).read_bytes()).hexdigest()==expected,name
 for arm in ['grep','colgrep']:
  teacher,student=manifests(arm);print(arm,'teacher prompt',teacher.prompt_hash,'student prompt',student.prompt_hash,flush=True)
 if a.preflight_only:raise SystemExit(0)
 vllm.assert_up(a.base_url)
 arms=[a.arm] if a.arm else ['grep','colgrep']
 for arm in arms:
  if not (BASE/arm/'progress.json').exists():run_arm(arm,a.base_url,pilot=True,workers=a.workers)
 with ThreadPoolExecutor(max_workers=len(arms)) as pool:
  list(pool.map(lambda arm:run_arm(arm,a.base_url,workers=a.workers),arms))
 print('Requested Python arms have 14,500 unfiltered trajectories',flush=True)