Download src/services/batch-loop-resume.js from VanyaJ/bada-terminal: direct link, hf CLI and curl.
- Browser
- Download file 11.5 kB
-
https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/services/batch-loop-resume.js
- Command line
-
hf download hf://VanyaJ/bada-terminal/src/services/batch-loop-resume.js
-
curl -L -o batch-loop-resume.js https://huggingface.co/VanyaJ/bada-terminal/resolve/main/src/services/batch-loop-resume.js
11.5 kB
| // ์๋ ์คํจ ํ์ ์น์ธ ์์์ฆ์ ๋ณด์กดํ๋ค. ์ ์ฅ๋ phase๋ ์ ์ฒด ๊ด์ธก์ ๋์ฌํ ์น์ธ ๊ฒฐ๊ณผ๋ง ์ธ์ํ๋ฉฐ ํจ๊ณผ๋ฅผ ์ฌ์ ์กํ์ง ์๋๋ค. | |
| // ์ค๋ช ๋ฌธ์: docs/specs/batch-step-continuation.md (v0.20.0, R67 ์งํ ์ค) | |
| const {hash,hex}=require('./bong-browser-resolution'),same=require('../db/batch-recovery-record').same; | |
| const resumable=new Set(['steps','evaluated','analyzed','settled','committed']); | |
| const recoveredPhases={evaluation_intent:'evaluated',analysis_intent:'analyzed',settlement_intent:'settled'}; | |
| const fail=()=>{throw Object.assign(Error('BATCH_LOOP_CONTINUATION_BLOCKED'),{code:'BATCH_LOOP_CONTINUATION_BLOCKED',retryable:false});}; | |
| const rows=(db,id)=>structuredClone({run:db.getLoopRun(id),iterations:db.getLoopIterations(id)}); | |
| const output=value=>typeof value==='string'?JSON.parse(value):value; | |
| function inspect(db,parent,tree){ | |
| const c=parent.checkpoint;if(!c.definition.loop)return null; | |
| const events=Object.values(c.loopEvents||{}),source=events.at(-1),config=c.definition.loop,original=rows(db,'looprun-'+c.runId);let reconstruction; | |
| if(!source)return require('./batch-loop-first').inspect(db,parent,original); | |
| if(recoveredPhases[source?.phase]){try{reconstruction=require('./batch-loop-prefix-proof').verify(db,parent);}catch{fail();}} | |
| const event=reconstruction?{...source,...Object.fromEntries(['phase','controller','history','meta','result'].map(k=>[k,reconstruction[k]])),usageIds:(parent.usage.usage.entries||[]).map(e=>e.id),requestKeys:Object.keys(parent.usage.requests||{})}:source,s=event?.controller; | |
| const reconciled=require('./batch-loop-ghost').inspect(db,parent,original,source)||require('./batch-loop-phase-reconciliation').inspect(db,parent,original,source,event)||require('./batch-loop-reconciliation').inspect(db,parent,original,source),extended=!reconciled&&require('./batch-child-usage-extension').inspect(db,parent,original,event,tree),actual=reconciled?.rows||extended?.rows||original; | |
| if(!event||!resumable.has(event.phase)||config.worktree_isolation&&!c.workspaceOrigin||!actual.run||actual.run.parent_run_id!==c.runId||actual.run.run_id!==event.ledgerRun.run_id||actual.run.goal_id!==event.ledgerRun.goal_id | |
| ||actual.run.started_at!==event.ledgerRun.started_at||actual.iterations.length!==event.iteration||actual.run.total_iterations!==event.iteration)fail(); | |
| const terminal=event.result?.shouldTerminate===true; | |
| // ์ ์ฅ๋ ์ข ๋ฃ ๊ฒฐ๊ณผ์ ๊ฒ์์๋ ์ ์์ ์์ฐ์ ์ฃผ์ง ์๋๋ค. ๋น์ข ๋ฃ ์ฌ๊ฐ๋ ์ต์ด epoch/์์ฐ์ ์งํจ๋ค. | |
| // ์๋ ๋ถ์ ํจ๊ณผ๋ ๋๋ฌ๋ค. ๋ถ์ ๋ณต๊ตฌ ๋ค์๋ ์ ์ฐ๋ง ๋จผ์ ์ํํ๋ฉฐ ์ด๊ณผ ์ ์ ํจ๊ณผ ์์ด ์ข ๋ฃํ๋ค. | |
| // ์ผ๋ฐ analyzed ์คํจ๋ ์๊ฐ/๋น์ฉ guard๋ฅผ ์ ์ฐ๊น์ง ์ ์ํ๋ ค๋ฉด ์ ์ฒด ๋ ๋ฆฝ ๊ด์ธก์ ๋จผ์ ํต๊ณผํด์ผ ํ๋ค. | |
| if(event.phase==='analyzed'&&!reconstruction&&!reconciled){const proof=require('./batch-loop-prefix-proof').verify(db,parent);if(proof.phase!=='analyzed'||!['controller','history','meta','result'].every(k=>same(event[k],proof[k])))fail();} | |
| const settling=event?.phase==='analyzed'; | |
| if(Date.now()<s.startTime||!terminal&&(!settling&&(Date.now()-s.startTime>=(config.max_wall_time??3600)*1000||parent.usage.usage.costUsd>=(config.token_budget??5))||s.consecutiveFailures>=(config.consecutive_failure_threshold??3)||event.iteration>(config.max_iterations??10)))fail(); | |
| const first=events.find(e=>e.iteration===event.iteration&&e.phase==='steps'),last=actual.iterations.at(-1),prior=events.filter(e=>e.phase==='committed'&&e.iteration<event.iteration),cost=parent.usage.usage.costUsd,tokens=parent.usage.usage.totalTokens||0; | |
| if(!first||last.id!==first.ledgerIteration.id||last.started_at!==first.ledgerIteration.started_at||prior.length!==event.iteration-1||!same(actual.iterations.slice(0,-1),prior.map(e=>e.ledgerIteration)) | |
| ||actual.run.total_cost!==cost||actual.run.total_tokens_used!==tokens||Math.abs(last.cost-(cost-first.controller.cumulativeCost))>1e-9||last.tokens_used!==tokens-first.controller.cumulativeTokens)fail(); | |
| if(event.phase==='committed'){ | |
| if(!same(last,event.ledgerIteration))fail(); | |
| const expected=terminal?event.ledgerRun:{...event.ledgerRun,status:actual.run.status,goal_met:0,break_reason:actual.run.status==='aborted'?'CANCELLED':'EXECUTION_FAILED',completed_at:actual.run.completed_at}; | |
| if(!terminal&&!['failed','aborted'].includes(actual.run.status)||!same(actual.run,expected))fail(); | |
| }else{ | |
| const expectedRun={...first.ledgerRun,status:actual.run.status,total_iterations:event.iteration,total_cost:cost,total_tokens_used:tokens,goal_met:0,break_reason:actual.run.status==='aborted'?'CANCELLED':'EXECUTION_FAILED',completed_at:actual.run.completed_at}; | |
| if(!['failed','aborted'].includes(actual.run.status)||last.status!==actual.run.status||last.goal_evaluation_result!==0||actual.run.goal_met!==0||actual.run.break_reason!==(actual.run.status==='aborted'?'CANCELLED':'EXECUTION_FAILED') | |
| ||!same(actual.run,expectedRun)||!same(event.ledgerRun,first.ledgerRun)||!same(event.ledgerIteration,first.ledgerIteration)||first.ledgerRun.total_cost!==first.controller.cumulativeCost||first.ledgerRun.total_tokens_used!==first.controller.cumulativeTokens)fail(); | |
| if(event.phase!=='steps'){ | |
| // ์๋ฃ ์ถ๋ ฅ์ ํ์ฌ ์คํจ ledger์๋ ๋์กฐํ๋ค. phase hash๋ง์ผ๋ก ์คํ ๊ฒฐ๊ณผ๋ฅผ ์ธ์ฆํ์ง ์๋๋ค. | |
| const outputs={};for(const e of parent.entries.filter(e=>e.iteration===event.iteration)){const r=require('./batch-step-output').resolved(c,e.key,parent.memoryContinuations);if(r||e.status==='completed')outputs[e.stepId]=r?r.output:e.output;} | |
| if(!same(outputs,output(last.step_outputs)))fail(); | |
| } | |
| } | |
| // phase ์ดํ ์์ฅ์ ์จ์ ์์ฒญ/๋น์ฉ์ด ์์ผ๋ฉด ๊ฒฐ๊ณผ๊ฐ ์๋ค๊ณ ๊ฐ์ฃผํ์ง ์๋๋ค. | |
| if(event.phase!=='steps'&&(event.usageIds.length!==(parent.usage.usage.entries||[]).length||event.requestKeys.length!==Object.keys(parent.usage.requests||{}).length))fail(); | |
| return{eventKey:source.key,eventHash:source.eventHash,rowsHash:hash(original),originalRun:original.run,originalIterations:original.iterations,...(reconstruction?{reconstruction}:{}),...(reconciled?{reconciliation:reconciled.reconciliation}:{}),...(extended?{childUsageExtension:extended.extension}:{})}; | |
| } | |
| function claim(db,state){ | |
| if(!state.loopState)return;const d=state.loopState,first=require('./batch-loop-first'),event=first.source(state.checkpoint,d); | |
| if(hash(rows(db,d.originalRun.run_id))!==d.rowsHash||event.eventHash!==d.eventHash)fail(); | |
| if(first.isFirst(d)){const grant=Object.values(state.checkpoint.recoveries||{}).at(-1);if(d.originalIterations.length)db.removeBatchLoopGhost(state.checkpoint.runId,grant.id,g=>same(g.loopState,d)&&same(first.inspect(db,state.parent,rows(db,d.originalRun.run_id)),d));db.saveLoopRun(structuredClone(event.ledgerRun),{replaceReceipt:true});return;} | |
| if(d.reconciliation?.kind==='unstarted_iteration'){const grant=Object.values(state.checkpoint.recoveries||{}).at(-1);db.removeBatchLoopGhost(state.checkpoint.runId,grant.id,g=>same(g.loopState,d)&&same(require('./batch-loop-ghost').inspect(db,state.parent,rows(db,d.originalRun.run_id),event)?.reconciliation,d.reconciliation));} | |
| // ๋ถ๋ถ ๋ง๊ฐ receipt๋ ์ ํํ baseline์ผ๋ก ๋๋๋ฆฐ๋ค. ์๋ ๊ฐ์ ์น์ธ grant์ ๋ณด์กดํ๋ค. | |
| db.saveLoopRun(structuredClone(event.ledgerRun),{replaceReceipt:true});db.saveLoopIteration(structuredClone(event.ledgerIteration)); | |
| if(d.reconstruction){ | |
| // ์น์ธํ ๊ทผ๊ฑฐ์ ๊ฒฐ๊ณผ phase๋ฅผ ์์ ์ถ๊ฐํ๋ค. ์๋ intent/๊ด์ธก/์คํจ ํ์ grant์ ๊ทธ๋๋ก ๋จ๋๋ค. | |
| const next=structuredClone(state.checkpoint),usage=db.getRuntimeUsage(next.runId),key=String(next.revision+1),{eventHash:_,...source}=event; | |
| const body={...source,key,revision:next.revision+1,recordedAt:new Date().toISOString(),previousHash:event.eventHash,entryKeys:Object.keys(next.entries),entriesHash:hash(next.entries),usageIds:(usage.usage.entries||[]).map(e=>e.id),requestKeys:Object.keys(usage.requests||{}),usageHash:hash({entries:usage.usage.entries||[],requests:usage.requests||{}}),...Object.fromEntries(['phase','controller','history','meta','result'].map(k=>[k,structuredClone(d.reconstruction[k])]))}; | |
| next.loopEvents={...next.loopEvents,[key]:{...body,eventHash:hash(body)}};next.revision++; | |
| state.checkpoint=db.saveBatchCheckpoint(next,state.checkpoint.revision);const{reconstruction:__,...natural}=d;state.loopState={...natural,eventKey:key,eventHash:hash(body)}; | |
| } | |
| } | |
| function restore(db,run,state){ | |
| const first=require('./batch-loop-first'),initial=first.isFirst(state.loopState),event=first.source(state.checkpoint,state.loopState),actual=rows(db,event.ledgerRun.run_id); | |
| if(!same(actual.run,event.ledgerRun)||(initial?actual.iterations.length:!same(actual.iterations.at(-1),event.ledgerIteration)))fail(); | |
| const ledger=Object.create(require('./batch-loop-ledger').BatchLoopLedger.prototype); | |
| // evaluated/analyzed์ controller๋ ์ด๋ฏธ ์ด๋ฒ ํ์ฐจ๋ฅผ ์ ์ง๋ง ledger๋ ์์ง ์ง์ ํ์ฐจ๊น์ง ์ ์ฐํ๋ค. | |
| Object.assign(ledger,{db,owner:run,record:actual.run,iteration:actual.iterations.at(-1)||null,accountedCost:event.ledgerRun.total_cost,accountedTokens:event.ledgerRun.total_tokens_used});return{ledger,event:initial?{...event,history:[],meta:null}:event}; | |
| } | |
| function validate(c,g){ | |
| if(require('./batch-loop-first').isFirst(g.loopState))return require('./batch-loop-first').validate(c,g); | |
| const d=g.loopState,event=c.loopEvents?.[d?.eventKey],r=d?.reconstruction; | |
| if(!d||Object.keys(d).length!==(5+(r?1:0)+(d.reconciliation?1:0)+(d.childUsageExtension?1:0))||Object.keys(d).some(k=>!['eventKey','eventHash','rowsHash','originalRun','originalIterations','reconstruction','reconciliation','childUsageExtension'].includes(k))||!event||!(r?recoveredPhases[event.phase]===r.phase:resumable.has(event.phase))||event.eventHash!==d.eventHash||g.position.iteration!==event.iteration||!same(d.rowsHash,hash({run:d.originalRun,iterations:d.originalIterations}))||d.originalRun?.run_id!=='looprun-'+c.runId||!Array.isArray(d.originalIterations)||d.originalIterations.length!==event.iteration+(d.reconciliation?.kind==='unstarted_iteration'?1:0))fail(); | |
| if(d.childUsageExtension){if(event.phase!=='steps'||r||d.reconciliation)fail();require('./batch-child-usage-extension').validate(d.childUsageExtension,c,g);} | |
| if(d.reconciliation){if(r&&d.reconciliation.kind!=='partial_phase_closure')fail();require(d.reconciliation.kind==='unstarted_iteration'?'./batch-loop-ghost':d.reconciliation.kind==='partial_phase_closure'?'./batch-loop-phase-reconciliation':'./batch-loop-reconciliation').validate(d.reconciliation,event);if(r&&(!same(r.prefixHash,d.reconciliation.prefixHash)||!same(r.observationsHash,d.reconciliation.observationsHash)))fail();} | |
| if(r&&(r.version!==1||Object.keys(r).length!==10||Object.keys(r).some(k=>!['version','phase','controller','history','meta','result','decisionTime','sourceHash','observationsHash','prefixHash'].includes(k))||r.sourceHash!==event.eventHash||!hex(r.observationsHash)||!hex(r.prefixHash)||!Number.isSafeInteger(r.decisionTime)||r.decisionTime<event.controller.startTime||r.controller?.startTime!==event.controller.startTime||r.controller.currentIteration!==event.iteration||r.result?.iteration!==event.iteration||typeof r.result.shouldTerminate!=='boolean'||typeof r.result.goalMet!=='boolean'||!Array.isArray(r.history)))fail(); | |
| } | |
| module.exports={inspect,claim,restore,validate}; | |