File size: 5,626 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
// 최신 evaluated/analyzed에서도 멈추되 복구할 intent 하나만 믿지 않고 최초 epoch부터 모든 회차의 판정·분석·정산·ledger를 읽기 대사한다.
// 설명 문서: docs/specs/batch-step-continuation.md v0.18.0
const{hash,same,fail}=require('./batch-observation-proof-common');
const fields=['controller','history','meta','result'],body=value=>typeof value==='string'?JSON.parse(value):value;
function verify(db,parent,{throughCommitted=false}={}){
 const c=parent.checkpoint,events=Object.values(c.loopEvents||{}),latest=events.at(-1),trace=[];let prior,reconstruction;
 if(throughCommitted&&latest?.phase!=='committed')fail('MISSING_COMMITTED_PREFIX');
 function observed(event){const proof=require('./batch-loop-observation-proof').verify(db,c.runId,event.key);if(!proof.controllerTransitionVerified||!proof.controllerReconstruction)fail('MISSING_CONTROLLER_EVIDENCE');trace.push([event.key,proof.observationsHash]);return proof.controllerReconstruction;}
 function match(event,value){if(!event||fields.some(key=>!same(event[key],value[key])))fail('CONTROLLER_PREFIX');}
 for(let iteration=1;iteration<=latest.iteration;iteration++){
  const slice=events.filter(e=>e.iteration===iteration),phase=Object.fromEntries(slice.map(e=>[e.phase,e])),steps=phase.steps,s=steps?.controller;
  if(!steps||!s)fail('MISSING_ITERATION_BASELINE');
  if(prior){match(steps,{...prior,result:null});if(!same(steps.ledgerRun,prior.ledgerRun)||!same(steps.usageIds,prior.usageIds)||!same(steps.requestKeys,prior.requestKeys))fail('ITERATION_PREFIX');}
  else if(s.currentIteration!==0||s.cumulativeCost!==0||s.cumulativeTokens!==0||s.consecutiveFailures!==0||s.hasWarnedBudget||!same(s.metricHistory,{})||s.iterationResults.length||steps.history.length||steps.meta!==null
      ||s.startTime<Date.parse(parent.row.started_at)||s.startTime>Date.parse(steps.ledgerRun.started_at)||s.startTime>Date.parse(steps.recordedAt)||steps.ledgerRun.total_iterations!==0||steps.ledgerRun.total_cost!==0||steps.ledgerRun.total_tokens_used!==0||steps.ledgerRun.status!=='running')fail('INITIAL_CONTROLLER');
  for(const e of slice.filter(e=>!['steps','committed'].includes(e.phase)))if(!same(e.ledgerRun,steps.ledgerRun)||!same(e.ledgerIteration,steps.ledgerIteration))fail('PHASE_LEDGER_BASELINE');
  const intent=phase.evaluation_intent;if(!intent)fail('MISSING_EVALUATION');match(intent,{...steps,result:null});
  let value=observed(intent),target='evaluated';
  if(latest.key!==intent.key){
   match(phase.evaluated,value);
   if(!value.result.shouldTerminate&&latest.key!==phase.evaluated?.key){
    const analysis=phase.analysis_intent;match(analysis,value);value=observed(analysis);target='analyzed';
    if(latest.key!==analysis.key){
     match(phase.analyzed,value);if(latest.key!==phase.analyzed.key){const settlement=phase.settlement_intent;match(settlement,value);value=observed(settlement);target='settled';
     if(latest.key!==settlement.key)match(phase.settled,value);}
    }
   }else if(value.result.shouldTerminate&&latest.key!==phase.evaluated?.key)match(phase.settled,value);
  }
  if(iteration===latest.iteration&&!throughCommitted){
   reconstruction={version:1,phase:target,...Object.fromEntries(fields.map(key=>[key,structuredClone(value[key])])),decisionTime:value.decisionTime,sourceHash:latest.eventHash,observationsHash:value.observationsHash,prefixHash:hash({events:events.map(e=>e.eventHash),observations:trace})};break;
  }
  const committed=phase.committed;match(committed,value);
  const outputs={};for(const key of committed.entryKeys){const e=c.entries[key];if(e.iteration!==iteration)continue;const resolved=require('./batch-step-output').resolved(c,key,parent.memoryContinuations);if(resolved||e.status==='completed')outputs[e.stepId]=resolved?resolved.output:e.output;}
  const continued=require('./batch-step-output').continuedKeys(c,parent.memoryContinuations).some(key=>committed.entryKeys.includes(key)&&c.entries[key].iteration===iteration),actual=committed.ledgerIteration,completedAt=actual.completed_at;
  if(!Number.isFinite(Date.parse(completedAt))||Date.parse(completedAt)<Date.parse(phase.settled.recordedAt)||Date.parse(completedAt)>Date.parse(committed.recordedAt))fail('ITERATION_CLOSURE_TIME');
  const expectedIteration={...steps.ledgerIteration,status:value.result.goalMet&&!continued?'success':'failed',step_outputs:outputs,goal_evaluation_result:value.result.goalMet?1:0,cost:value.controller.cumulativeCost-s.cumulativeCost,tokens_used:value.controller.cumulativeTokens-s.cumulativeTokens,error_message:Object.values(outputs).find(v=>v?.error)?.error||null,completed_at:completedAt};
  if(!same({...actual,step_outputs:body(actual.step_outputs)},expectedIteration))fail('COMMITTED_ITERATION');
  const terminal=value.result.shouldTerminate?{status:value.result.goalMet?'completed':'circuit_broken',goal_met:value.result.goalMet?1:0,break_reason:value.result.breakReason||null,receipt_summary:value.result.receiptSummary||null,completed_at:completedAt}:{};
  if(!same(committed.ledgerRun,{...steps.ledgerRun,total_iterations:iteration,total_cost:value.controller.cumulativeCost,total_tokens_used:value.controller.cumulativeTokens,...terminal}))fail('COMMITTED_RUN');
  prior=committed;
  if(iteration===latest.iteration)reconstruction={version:1,phase:'committed',...Object.fromEntries(fields.map(key=>[key,structuredClone(value[key])])),decisionTime:value.decisionTime,sourceHash:latest.eventHash,observationsHash:value.observationsHash,prefixHash:hash({events:events.map(e=>e.eventHash),observations:trace})};
 }
 return reconstruction;
}
module.exports={verify};