"""CPU model repairs complete C functions; deterministic code handles integration.""" import os import hashlib import json from pathlib import Path import re import shutil import tempfile import time from .runtime import check from .syntax import functions,topology,context,c_tokens POLICY={'version':1,'model':'Qwen2.5-Coder-7B-Instruct Q4_K_M','gpu_layers':0,'threads':int(os.environ.get('COMPAILER_THREADS', '4')), 'context_tokens':8192,'seed':172,'temperature':0,'passes':1,'extra_retry_budget':3, 'output':'one_complete_C_function','preserve_passing_scenarios':True, 'accept_neutral_compiling_changes':True,'heldout_feedback':False} def canonical(text): return re.sub(r'/tmp/aicc-function-[^/]+/candidate\.c','candidate.c',text) def replace_function(source,name,raw): blocks=re.findall(r'```(?:c|C)?\s*\n(.*?)```',raw,re.S) if len(blocks)>1:raise ValueError('Expected one C block') code=(blocks[0] if blocks else raw).strip() emitted=functions(code) if len(emitted)!=1 or emitted[0]['name']!=name:raise ValueError('Expected only the assigned function') f=emitted[0] if code[:f['start']].strip() or code[f['end']:].strip():raise ValueError('Unexpected code outside function') original=functions(source);target=next(f for f in original if f['name']==name) tokens=lambda s:[t[0] for t in c_tokens(s)] if tokens(target['signature'])!=tokens(emitted[0]['signature']):raise ValueError('Function signature changed') revised=source[:target['start']]+code+source[target['end']:] after=functions(revised) if [f['name'] for f in after]!=[f['name'] for f in original]:raise ValueError('Function structure changed') for before,now in zip(original,after): if before['name']!=name and before['text']!=now['text']:raise ValueError('Another function changed') return revised def passing(report):return {i for i,t in enumerate(report['tests']) if t['passed']} def prompt_for(source,name,requirement,report,expanded=False,previous=None): fs=topology(source);by={f['name']:f for f in fs};target=by[name] decl,_,_=context(source,[name]);decl=re.sub(r'\n{3,}','\n\n',decl).strip() related=set(target['calls'])|{f['name'] for f in fs if name in f['calls']} interfaces='\n'.join(by[n]['signature']+';' for n in sorted(related)) helpers='' if expanded: helpers='\nRead-only dependency bodies:\n'+'\n\n'.join(by[n]['text'] for n in sorted(related))[:3000] failures=[{'input':t['input'][:350],'expected':t['expected'][:350], 'actual':t['stdout'][:350],'exit':t['returncode']} for t in report['tests'] if not t['passed']][:1] return ('Program behavior:\n'+requirement+'\nShared declarations:\n'+decl +'\nRelated function interfaces (do not implement these):\n'+interfaces+helpers +'\nAssigned function '+name+':\n```c\n'+target['text']+'\n```\n' +'Compiler diagnostics:\n'+canonical(report['diagnostics'][-1000:]) +'\nVisible integration failure (other functions may also be faulty):\n'+json.dumps(failures) +('\nPrevious replacement failed:\n'+json.dumps(previous)[-1800:] if previous else '') +'\nCorrect the assigned function according to the stated program behavior. Check its conditions, ' 'bounds, arithmetic, state updates and return value. Fix every actual fault in this function. ' 'If it is correct, reproduce it unchanged. Preserve the EXACT function signature and all interfaces. ' 'Return ONLY this one COMPLETE C function in a ```c block. No JSON, patches, explanations, ' 'includes, globals or other function definitions. Do not hardcode example answers.') class FunctionModel: def __init__(self,path): from llama_cpp import Llama self.llm=Llama(model_path=str(path),n_ctx=POLICY['context_tokens'],n_threads=POLICY['threads'], n_threads_batch=POLICY['threads'],n_batch=256,n_gpu_layers=0,seed=POLICY['seed'],verbose=False) def propose(self,prompt,target,number): self.llm.set_seed(POLICY['seed']+number) length=len(self.llm.tokenize(target.encode()));maximum=min(1600,max(256,2*length+96)) start=time.monotonic();print('MODEL_BEGIN',number,'prompt_chars',len(prompt),'max_output',maximum,flush=True) r=self.llm.create_chat_completion(messages=[{'role':'system','content': 'You correct one small C function. Output only its complete C definition with the original signature.'}, {'role':'user','content':prompt}],temperature=0,max_tokens=maximum) g={'raw':r['choices'][0]['message']['content'] or '', 'usage':r.get('usage'), 'finish_reason':r['choices'][0]['finish_reason'],'max_output_tokens':maximum, 'seconds':round(time.monotonic()-start,3)} print('MODEL_END',number,g['seconds'],g['usage'],flush=True);return g def ordered_names(source,baseline): fs=functions(source);names=[f['name'] for f in fs] if not baseline['compiled']: line=re.search(r'candidate.c:(\d+)',baseline['diagnostics']) if line: pos=sum(len(x) for x in source.splitlines(True)[:int(line[1])-1]) culprit=next((f['name'] for f in fs if f['start']<=pos