File size: 7,772 Bytes
d739b1b | 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 | // ๊ณผ๊ฑฐ continue ์ถ๋ ฅ์ ์ถ์ ํ์ง ์๋๋ค. ์๋ ์์ฅ์ ๊ฐ๊ณผ ๊ทธ ๊ฐ์ ์๋นํ ์
๋ ฅ/๊ด์ธก์ ์ฝ๊ธฐ ๋์ฌํ๋ค.
// ์ค๋ช
๋ฌธ์: docs/specs/batch-memory-continue.md v1.0.0
const {hash}=require('./bong-browser-resolution'),format=require('../db/batch-checkpoint-record'),recovery=require('../db/batch-recovery-record'),continued=require('../db/batch-continued-record');
const fail=reason=>{throw Object.assign(Error('BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED: '+reason),{code:'BATCH_MEMORY_CONTINUE_VERIFICATION_FAILED',reason,retryable:false});};
const body=v=>typeof v==='string'?JSON.parse(v):v;
function verify(db,runId){return db.runInTransaction(()=>{
if(typeof runId!=='string'||!/^[-\w]{1,160}$/.test(runId))fail('RUN_ID');
const c=format.decode(db.getBatchCheckpoint(runId)),row=db.getBatchRun(runId),usage=db.getRuntimeUsage(runId);
if(!c||!row||!c.definition.loop||c.runId!==runId||row.task_id!==c.taskId||row.work_dir!==c.workDir||!['failed','aborted','paused'].includes(row.status)||usage?.version!==1||usage.runId!==runId||usage.parentRunId!==null)fail('IDENTITY');
const task=db.getBatchTasks(c.projectId).find(t=>t.id===c.taskId),definition=require('../utils/batch-definition');
if(!task||task.project_id!==c.projectId||definition.fingerprint(task)!==c.definitionHash)fail('DEFINITION_CHANGED');
const steps=format.stepsFor(task),entries=Object.values(c.entries),loop=db.getLoopRun('looprun-'+runId),rows=db.getLoopIterations('looprun-'+runId),records={},goalEvidence=[];
if(loop?.run_id!=='looprun-'+runId||loop.parent_run_id!==runId||!rows.length||rows.length>4096||rows.some((r,i)=>r.id!=='iter-looprun-'+runId+'-'+(i+1)||r.loop_run_id!==loop.run_id||r.iteration_number!==i+1))fail('LOOP_IDENTITY');
const u=usage.usage?.entries,requests=usage.requests;
if(!Array.isArray(u)||!requests||new Set(u.map(e=>e.id)).size!==u.length||u.some(e=>!['cli_reported','provider_reported','operator_reported','not_submitted'].includes(e.costSource)||!Number.isFinite(e.costUsd)||e.costUsd<0||e.totalTokens!==null&&e.totalTokens!==undefined&&(!Number.isSafeInteger(e.totalTokens)||e.totalTokens<0))||Object.values(requests).some(q=>!q||!['settled','not_submitted'].includes(q.state)||q.costKnown!==true))fail('UNKNOWN_USAGE');
if(!Number.isFinite(usage.usage.costUsd)||Math.abs(u.reduce((sum,e)=>sum+e.costUsd,0)-usage.usage.costUsd)>1e-9)fail('USAGE_TOTAL');
for(const e of entries){
if(e.status!=='failed'||steps[e.stepIndex].on_failure!=='continue'||continued.resolved(c,e.key)||recovery.resolved(c,e.key))continue;
if(continued.uncertain(e.error)||e.attempt!==0)fail('UNCERTAIN_FAILURE');
const source=rows[e.iteration-1],outputs=body(source?.step_outputs),output=outputs?.[e.stepId];
if(!output||Array.isArray(output)||Object.keys(output).length!==2||!Object.hasOwn(output,'error')||!Object.hasOwn(output,'_duration')||typeof output.error!=='string'||output.error.slice(0,2000)!==e.error.message||typeof output._duration!=='string'||!/^\d+\.\d{2}$/.test(output._duration)||!Number.isFinite(Number(output._duration)))fail('ORIGINAL_OUTPUT_MISSING');
format.json(output);
records[e.key]={entryKey:e.key,originalEntryHash:hash(e),output:structuredClone(output),outputHash:hash(output),durationSource:'original_consumed_output',source:{kind:'loop_iteration',id:source.id,hash:hash(source)},consumers:[]};
}
if(!Object.keys(records).length)fail('NO_MEMORY_OUTPUTS');
let revision=Object.keys(c.recoveries||{}).length+Object.keys(c.revocations||{}).length+Object.keys(c.continuations||{}).length+Object.keys(c.loopEvents||{}).length+Object.keys(c.loopPublications||{}).length+Number(!!c.loopOrigin),prior,iteration,outputs={};
for(const e of entries){
const resolution=recovery.resolved(c,e.key),published=e.status==='completed'?e:c.continuations?.[e.key],candidate=records[e.key],approved=continued.resolved(c,e.key);
if(prior?.status==='running')fail('RUNNING_PREFIX');format.sequence(prior,e,c.definition.loop);revision+=e.status==='running'?1:2;
if(prior?.status==='failed'){
const policy=steps[prior.stepIndex];
if(e.iteration===prior.iteration&&e.stepIndex===prior.stepIndex){if(policy.on_failure!=='retry'||e.attempt>(policy.retry_count||3)||continued.uncertain(prior.error)||continued.resolved(c,prior.key)||records[prior.key])fail('RETRY_POLICY');}
else if(!continued.resolved(c,prior.key)&&!records[prior.key])fail('FAILED_PREFIX');
}
if(e.iteration!==iteration){outputs={};iteration=e.iteration;}
const step=steps[e.stepIndex],escape=step.type==='cli'?v=>require('../utils/shell-helper').escapeShellArg(v,process.platform==='win32'):null,config=require('../batch-step-runners').interpolateConfig(step.config,outputs,escape);
if(e.inputsHash!==hash(outputs)||e.configHash!==hash(config))fail('CONSUMED_INPUTS');
if(prior&&prior.iteration===e.iteration&&records[prior.key]){
if(Date.parse(e.startedAt)<Date.parse(prior.completedAt))fail('CONSUMPTION_TIME');
records[prior.key].consumers.push({kind:'entry_inputs',key:e.key,entryHash:hash(e),inputsHash:e.inputsHash,configHash:e.configHash});
}
if(published){
const prefix=u.slice(0,published.usageIds.length),saved=Object.fromEntries(published.requestKeys.map(k=>[k,requests[k]])),invocations=Object.fromEntries(Object.entries(usage.workflowInvocations||{}).filter(([,d])=>d.kind==='batch'&&d.stepId===e.stepId&&d.stepIndex===e.stepIndex&&d.iteration===e.iteration));
if(hash(prefix.map(v=>v.id))!==hash(published.usageIds)||hash({entries:prefix,requests:saved})!==published.usageHash||hash(invocations)!==published.invocationsHash)fail('PUBLISHED_USAGE');outputs[e.stepId]=published.output;
}
if(resolution||approved||candidate)outputs[e.stepId]=(resolution||approved||candidate).output;
prior=resolution?{...e,status:'completed'}:e;
}
if(revision!==c.revision||(prior?.key||null)!==c.currentKey)fail('REVISION');
// ๋ง์ง๋ง ์คํจ ์ถ๋ ฅ์ ๋ค์ entry๊ฐ ์๋ค. ์ ์ฒด ์๋ ๋ชฉํ ๊ด์ธก์ด ๊ฐ์ ์
๋ ฅ์ ์๋นํ์ ๋๋ง ์ธ์ ํ๋ค.
for(const [key,record]of Object.entries(records))if(!record.consumers.length){
const entry=c.entries[key],event=Object.values(c.loopEvents||{}).find(e=>e.iteration===entry.iteration&&e.phase==='evaluation_intent');
if(!event||!event.entryKeys.includes(key)||Date.parse(event.recordedAt)<Date.parse(entry.completedAt))fail('MISSING_CONSUMER');
const inputs={};for(const k of event.entryKeys){const e=c.entries[k];if(e.iteration!==event.iteration)continue;const r=recovery.resolved(c,k)||continued.resolved(c,k)||records[k];if(r||e.status==='completed')inputs[e.stepId]=r?r.output:e.output;}
if(steps.some(s=>!Object.hasOwn(inputs,s.id)))fail('INCOMPLETE_GOAL_INPUTS');
const observations=require('../db/batch-loop-observation-record').decode(db,runId,event.key,db.getBatchLoopObservations(runId,event.key));if(!observations)fail('MISSING_OBSERVATIONS');
const parent={checkpoint:c,row,usage,task,steps,memoryContinuations:records},config=require('../config/loop-configuration').normalize(task.loop_config,{requireGoals:false}),proof=require('./batch-goal-observation-proof').verify(db,{parent,event,observations,outputs:inputs,config});
if(!proof.controllerTransitionVerified)fail('MISSING_CONTROLLER_EVIDENCE');
record.consumers.push({kind:'goal_observations',key:event.key,eventHash:event.eventHash,observationsHash:observations.hash,inputsHash:hash(inputs)});goalEvidence.push([event.key,observations.hash]);
}
return{version:1,runId,records,goalEvidenceCount:goalEvidence.length,knownCostUsd:usage.usage.costUsd,usageHash:hash(usage),fingerprint:hash([c,row,usage,loop,rows,records,goalEvidence]),candidateConsumptionVerified:true,canResume:false,ancestryCertified:false,controllerOutcomeCertified:false};
});}
module.exports={verify};
|