File size: 6,760 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
// committed/์‹คํŒจ ๋งˆ๊ฐ๊ณผ ๋Œ€๊ธฐ ํ•ญ๋ชฉ์€ ํ•จ๊ป˜ ์ €์žฅํ•œ๋‹ค. ์™ธ๋ถ€ ์ œ์ถœ๊ณผ DB๋Š” ์›์žํ™”ํ•  ์ˆ˜ ์—†์–ด ์˜๋„๋ฅผ ๋จผ์ € ๊ธฐ๋กํ•œ๋‹ค.
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/batch-step-continuation.md (v0.12.0, R67 ์ง„ํ–‰ ์ค‘)
const {hash}=require('./bong-browser-resolution'),{same}=require('../db/batch-recovery-record'),format=require('../db/batch-loop-publication-record');
const rows=(db,c)=>({run:db.getLoopRun('looprun-'+c.runId),iterations:db.getLoopIterations('looprun-'+c.runId)});
function packet(c,event){const r=event.result,warning=event.phase==='evaluated';return{runId:c.runId,loopRunId:event.ledgerRun.run_id,iteration:event.iteration,cost:warning?event.controller.cumulativeCost:event.ledgerRun.total_cost,status:warning?'warning':r.shouldTerminate?r.goalMet?'completed':'circuit_broken':'running',reason:warning?'budget_warning':r.reason,breakReason:r.breakReason||null,goalMet:warning?false:r.goalMet,shouldTerminate:warning?false:r.shouldTerminate,receiptSummary:warning?null:r.receiptSummary||null};}
function summary(c){const result={pending:0,uncertain:0,submitted:0,unsupported:0,superseded:0,legacy:c?.publicationVersion!==1};for(const {ready,channels}of format.states(c||{}).values())for(const channel of ready.data.channels){const s=channels[channel]?.kind;if(!s)result.pending++;else if(s==='intent'||s==='uncertain')result.uncertain++;else result[s]++;}return result;}
function verify(db,c){for(const {ready}of format.states(c).values()){
 const {source,packet:p,channels}=ready.data;if(source.kind==='stopped'){
  const actual=rows(db,c),old=Object.values(c.recoveries||{}).map(g=>g.loopState&&({run:g.loopState.originalRun,iterations:g.loopState.originalIterations}));
  if(![actual,...old].some(v=>v&&hash(v)===source.rowsHash))throw Error('Unverified loop stop publication');
  const found=[actual,...old].find(v=>v&&hash(v)===source.rowsHash),r=found.run;
  if(!same(p,stopped(c,r))||!same(channels,['hud','ipc']))throw Error('Unverified loop stop payload');
 }else{
  const e=c.loopEvents[source.eventKey],expected=source.kind==='warning'?['warning']:e.result.shouldTerminate?['hud','ipc','native']:['hud'];
  if(!same(p,packet(c,e))||!same(channels,expected))throw Error('Unverified loop result publication');
 }
}}
function stopped(c,r){return{runId:c.runId,loopRunId:r.run_id,iteration:r.total_iterations,cost:r.total_cost,status:r.status,reason:r.status==='aborted'?'cancelled':'execution_failed',breakReason:r.break_reason||null,goalMet:false,shouldTerminate:true,receiptSummary:null};}
function create({db,run,checkpoint,controller,emit}){
 function ready(source,p,channels){const c=checkpoint.get();if(c.publicationVersion!==1)return;const data={source,packet:p,channels},publicationId=hash(data);if(format.states(c).has(publicationId))return;checkpoint.publication({kind:'ready',publicationId,channel:null,data});}
 function warnings(){const c=checkpoint.get(),evaluated=Object.values(c.loopEvents||{}).filter(e=>e.phase==='evaluated');for(let i=0;i<evaluated.length;i++){const e=evaluated[i];if(e.controller.hasWarnedBudget&&(i===0||!evaluated[i-1].controller.hasWarnedBudget))ready({kind:'warning',eventKey:e.key,eventHash:e.eventHash},packet(c,e),['warning']);}}
 function enqueue(kind){const c=checkpoint.get();if(c.publicationVersion!==1)return;
  if(kind==='committed'){const e=Object.values(c.loopEvents||{}).at(-1);if(e?.phase!=='committed')throw Error('Loop publication needs committed result');ready({kind,eventKey:e.key,eventHash:e.eventHash},packet(c,e),e.result.shouldTerminate?['hud','ipc','native']:['hud']);}
  else{const actual=rows(db,c);if(!['failed','aborted'].includes(actual.run?.status))throw Error('Loop publication needs stopped ledger');ready({kind:'stopped',rowsHash:hash(actual)},stopped(c,actual.run),['hud','ipc']);}
  warnings();
 }
 function flush(){const c=checkpoint.get();if(c.publicationVersion!==1){
  // ์ด์ „ ๊ธฐ๋ก์—๋Š” ์ œ์ถœ ๊ทผ๊ฑฐ๊ฐ€ ์—†๋‹ค. ์žฌ์ „์†กํ•˜์ง€ ์•Š๊ณ  ๊ฒ€์ฆ๋œ DB ์ƒํƒœ๋กœ ์ฝ๊ธฐ snapshot๋งŒ ๋ณต์›ํ•œ๋‹ค.
  const r=rows(db,c).run;if(r&&['completed','circuit_broken','failed','aborted'].includes(r.status))require('./loop-hud').publish(controller,r.status,r.break_reason,{iteration:r.total_iterations,cost:r.total_cost,silent:true});
  return summary(c);
 }verify(db,c);
  const packets=[...format.states(c).values()],latest=Object.fromEntries(['hud','ipc'].map(channel=>[channel,packets.filter(p=>p.ready.data.channels.includes(channel)).at(-1)?.ready.publicationId]));
  for(const {ready,channels}of packets)for(const channel of ready.data.channels){
   if(channels[channel])continue;const {publicationId}=ready,p=ready.data.packet;
   checkpoint.publication({kind:'intent',publicationId,channel,data:null});let outcome='submitted';
   if(['hud','ipc'].includes(channel)&&latest[channel]!==publicationId){checkpoint.publication({kind:'superseded',publicationId,channel,data:null});continue;}
   try{
    if(channel==='hud'){
     let failed=false;require('./loop-hud').publish(controller,p.status,p.breakReason,{publicationId,iteration:p.iteration,cost:p.cost,onFailure:()=>{failed=true;}});if(failed)outcome='uncertain';
    }
    else if(channel==='ipc'){const result=emit('loop:complete',{...p,publicationId});if(result?.status==='uncertain')outcome='uncertain';}
    else{const notifier=require('../loop-notifier'),r=channel==='native'?notifier.notifyLoopComplete(p.runId,p.goalMet,p.breakReason||p.reason,p.cost):notifier.notifyLoopWarning(p.runId,`๋ˆ„์  ๋น„์šฉ($${p.cost.toFixed(2)})์ด ์˜ˆ์‚ฐ์˜ 80%๋ฅผ ์ดˆ๊ณผํ–ˆ์Šต๋‹ˆ๋‹ค.`);outcome=['submitted','unsupported'].includes(r?.status)?r.status:'uncertain';}
   }catch{outcome='uncertain';run.logStream?.write('[Loop Outbox] ์ œ์ถœ ๊ฒฐ๊ณผ๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์—†์–ด ์ž๋™ ์žฌ์ „์†กํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.\n');}
   // ์ด ์“ฐ๊ธฐ๊ฐ€ ์‹คํŒจํ•˜๋ฉด intent๋งŒ ๋‚จ๋Š”๋‹ค. ์ด๋ฏธ ์ œ์ถœํ–ˆ์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋‹ค์‹œ ๋ณด๋‚ด์ง€ ์•Š๋Š”๋‹ค.
   checkpoint.publication({kind:outcome,publicationId,channel,data:null});
  }
  const result=summary(checkpoint.get());run.loopPublicationSummary=result;return result;
 }
 function initial(){const c=checkpoint.get(),e=Object.values(c.loopEvents||{}).at(-1),entry=[...format.states(c).values()].find(s=>s.ready.data.source.eventKey===e?.key&&s.ready.data.source.kind==='committed');
  if(e?.phase==='committed'&&e.result.shouldTerminate&&(entry?.channels.hud||c.publicationVersion!==1)){const p=entry?entry.ready.data.packet:packet(c,e);require('./loop-hud').publish(controller,p.status,p.breakReason,{publicationId:entry?.ready.publicationId,iteration:p.iteration,cost:p.cost,silent:true});}
  else require('./loop-hud').publish(controller,'running');
 }
 return{enqueue,flush,initial,summary:()=>summary(checkpoint.get())};
}
module.exports={create,summary,verify,packet};