File size: 21,982 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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | // ๊ฐ์ ๋ฃจํ ์คํ/ํ์ฐจ/๋น์ฉ์ ๋ณต์ํ๋ฉฐ ์ด๋ฏธ ๋๋ธ child๋ goal ํ๊ฐ๋ฅผ ์ฌ์คํํ์ง ์๋๋ค.
// ์ค๋ช
๋ฌธ์: docs/specs/batch-step-continuation.md (v0.6.0, R67 ์งํ ์ค)
const {test,after}=require('node:test'),assert=require('node:assert/strict'),fs=require('fs'),os=require('os'),path=require('path'),{randomUUID}=require('crypto');
const home=fs.mkdtempSync(path.resolve('scratch/batch-loop-continue-')),oldHome=os.homedir;os.homedir=()=>home;
const ctx=require('../../src/context');ctx.currentCwd=home;require('../../src/config-manager').getKnowledgeConfig=()=>({devPreferenceAutoLearn:false,codeIntelEnabled:false,troubleshootAutoCapture:false});require('../../src/services/governance-client').cachedPolicy={enabled:false};require('../../src/skills-manager').generateClaudeRules=async()=>{};
const archive=require('../../src/wiki-run-archiver');archive.archiveWorkflowRun=async()=>{};archive.archiveBatchRun=async()=>({success:true});
const db=require('../../knowledge-db'),engine=require('../../src/workflow-manager'),batch=require('../../src/batch-manager'),execute=engine.executeNode;
after(async()=>{await engine.cleanupAll();await batch.cleanupAllActiveRuns();engine.executeNode=execute;os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));});
async function fixture({loseIteration=1,failPhase,failIteration=1,ready=false,failCompletion=false,failAfterCommit=false,continued=false}={}){
const project=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'loop child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},task={id:randomUUID(),project_id:project,name:'same loop',is_active:0,loop_config:JSON.stringify({goals:[{type:'file_exists',target:'READY'}],max_iterations:4,token_budget:1}),steps:[{id:'child',type:'workflow',config:{workflowId:workflow.id,timeoutMs:3000}},{id:'after',type:'transform',config:{script:'return {value: {{steps.child.runData.work.output.value}}};'}}]};
if(continued){task.steps.unshift({id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('optional loop failure')"}});task.loop_config=JSON.stringify({...JSON.parse(task.loop_config),consecutive_failure_threshold:1});}
if(ready)fs.writeFileSync(path.join(project,'READY'),'ready');
const childIndex=continued?1:0;db.saveWorkflow(project,workflow);await batch.saveScheduledTask(project,task);let calls=0;engine.executeNode=async run=>{calls++;require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.02,1,{id:'paid',costSource:'provider_reported',totalTokens:2});return{value:calls};};
const save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(failPhase&&Object.values(c.loopEvents||{}).at(-1)?.phase===failPhase&&Object.values(c.loopEvents||{}).at(-1)?.iteration===failIteration)throw Error('lost loop phase '+failPhase);if(!failPhase&&!failCompletion&&!failAfterCommit&&c.entries[loseIteration+':'+childIndex+':0']?.status==='completed')throw Error('lost loop child output');return save(c,...args);};
const complete=db.completeBatchRun;if(failCompletion)db.completeBatchRun=(id,status,error)=>{if(status==='success'){complete(id,'failed','injected completion publication failure');throw Error('injected completion publication failure');}return complete(id,status,error);};
const transaction=db.runInTransaction;let depth=0,injected=false;if(failAfterCommit)db.runInTransaction=(fn,options)=>{depth++;try{return transaction(()=>{const result=fn();if(depth===1&&!injected&&Object.values(db.getBatchCheckpoint(db.getBatchRuns(task.id)[0]?.run_id)?.loopEvents||{}).at(-1)?.phase==='committed'){injected=true;throw Error('outer loop transaction publication failure');}return result;},options);}finally{depth--;}};
let result;try{result=await batch.runTask(task);}finally{db.saveBatchCheckpoint=save;db.completeBatchRun=complete;db.runInTransaction=transaction;}assert.equal(result.success,false);return{project,workflow,task,calls,runId:db.getBatchRuns(task.id)[0].run_id};
}
async function prepare(f){const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.project),authorize:()=>true,approve:async()=>({approved:true})}),p=api.preview(f.runId,{owner});return api.commit(p.ticketId,{owner,confirmed:true});}
test('same loop iteration restores original controller/ledger and recovered child without duplicate cost or evaluation',async()=>{
const f=await fixture(),checkpoint=db.getBatchCheckpoint(f.runId),loop=db.getLoopRun('looprun-'+f.runId),iteration=db.getLoopIterations(loop.run_id)[0],usage=db.getRuntimeUsage(f.runId);
assert.equal(Object.values(checkpoint.loopEvents||{}).at(-1)?.phase,'steps');assert.equal(loop.status,'failed');fs.writeFileSync(path.join(f.project,'READY'),'done');engine.executeNode=async()=>{throw Error('original loop child replayed');};const prepared=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);
const final=db.getLoopRun(loop.run_id),rows=db.getLoopIterations(loop.run_id);assert.equal(final.status,'completed');assert.equal(final.started_at,loop.started_at);assert.equal(final.parent_run_id,f.runId);assert.equal(rows.length,1);assert.equal(rows[0].id,iteration.id);assert.equal(rows[0].started_at,iteration.started_at);assert.equal(rows[0].cost,.02);assert.equal(final.total_cost,.02);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);assert.deepEqual(db.getRuntimeUsage(f.runId),usage);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries['1:0:0'],checkpoint.entries['1:0:0']);assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,2);
});
test('a later interrupted iteration preserves earlier committed evaluations and starts only an intentional next iteration',async()=>{
const f=await fixture({loseIteration:2}),original=db.getLoopIterations('looprun-'+f.runId),checkpoint=db.getBatchCheckpoint(f.runId);assert.equal(f.calls,2);assert.equal(original.length,2);assert.equal(Object.values(checkpoint.loopEvents||{}).filter(e=>e.phase==='committed').length,1);
let calls=0;engine.executeNode=async run=>{calls++;fs.writeFileSync(path.join(f.project,'READY'),'done');require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.03,1,{id:'paid',costSource:'provider_reported',totalTokens:3});return{value:3};};const prepared=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:prepared.fingerprint});assert.equal(result.success,true,result.error);assert.equal(calls,1);const rows=db.getLoopIterations('looprun-'+f.runId);assert.equal(rows.length,3);assert.deepEqual(rows[0],original[0]);assert.equal(rows[1].started_at,original[1].started_at);rows.forEach((r,i)=>assert.ok(Math.abs(r.cost-[.02,.02,.03][i])<1e-9));assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.07);assert.equal(db.getWorkflowRuns(f.workflow.id).length,3);assert.equal(Object.values(db.getBatchCheckpoint(f.runId).loopEvents).filter(e=>e.phase==='evaluated').length,3);
});
test('goal evaluation result publication failure retains its intent and requires approval before consuming original observations',async()=>{
const f=await fixture({failPhase:'evaluated'}),checkpoint=db.getBatchCheckpoint(f.runId);assert.equal(Object.values(checkpoint.loopEvents||{}).at(-1)?.phase,'evaluation_intent');const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.project),authorize:()=>true,approve:async()=>({approved:true})});assert.equal(api.preview(f.runId,{owner}).reconstructedPhase,true);assert.equal(db.getBatchRun(f.runId).status,'failed');assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('restored continue failure still increments the original breaker and stops before a new iteration',async()=>{
const f=await fixture({continued:true}),p=await prepare(f);let calls=0;engine.executeNode=async()=>{calls++;throw Error('continued child replayed');};const result=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(result.success,false);assert.equal(calls,0);const row=db.getLoopRun('looprun-'+f.runId);assert.equal(row.status,'circuit_broken');assert.equal(row.break_reason,'CONSECUTIVE_FAILURES');assert.equal(row.total_iterations,1);assert.equal(row.total_cost,.02);assert.equal(Object.values(db.getBatchCheckpoint(f.runId).loopEvents).find(e=>e.phase==='evaluated').controller.consecutiveFailures,1);
});
test('loop ledger handoff failure rolls back the same batch and all original rows before effects',async()=>{
const f=await fixture(),p=await prepare(f),row=db.getBatchRun(f.runId),loop=db.getLoopRun('looprun-'+f.runId),iterations=db.getLoopIterations(loop.run_id),save=db.saveLoopIteration;db.saveLoopIteration=()=>{throw Error('loop claim disk failure');};
try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,false);}finally{db.saveLoopIteration=save;}
assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getLoopRun(loop.run_id),loop);assert.deepEqual(db.getLoopIterations(loop.run_id),iterations);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);fs.writeFileSync(path.join(f.project,'READY'),'done');engine.executeNode=async()=>{throw Error('replay after rollback');};assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);
});
test('loop rows changing during approval invalidate review and never publish a grant',async()=>{
const f=await fixture(),owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(f.project),authorize:()=>true,approve:async()=>{const row=db.getLoopRun('looprun-'+f.runId);db.saveLoopRun({...row,total_cost:99});return{approved:true};}}),p=api.preview(f.runId,{owner});await assert.rejects(api.commit(p.ticketId,{owner,confirmed:true}));assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);assert.equal(db.getBatchRun(f.runId).status,'failed');
});
test('elapsed wall time keeps the original start and cannot be reset by preparing a loop continuation',async()=>{
const f=await fixture(),clock=Date.now;Date.now=()=>clock()+4000000;try{await assert.rejects(prepare(f));}finally{Date.now=clock;}
assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('a fresh process resumes the verified dead loop owner with the same original rows and no child replay',async()=>{
const f=await fixture(),p=await prepare(f),original=db.getLoopRun('looprun-'+f.runId),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock'),target=owners.file(f.task.id),cp=require('child_process');owners.claimReview(f.task.id,locks.readLock(target),f.runId).release();
const dead=cp.spawnSync(process.execPath,['-e',"require('./src/db/store-write-lock').acquireStoreWriteLock(process.argv[1],{retainOnExit:true});",target],{encoding:'utf8',timeout:10000});assert.equal(dead.status,0,dead.stderr);assert.equal(locks.readLock(target).state,'dead');fs.writeFileSync(path.join(f.project,'READY'),'done');
const code="require('os').homedir=()=>process.argv[1];const ctx=require('./src/context');ctx.currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const engine=require('./src/workflow-manager');engine.executeNode=async()=>{throw Error('loop child replay')};const batch=require('./src/batch-manager');batch.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log('RESULT:'+JSON.stringify({success:r.success,error:r.error}));await engine.cleanupAll();await batch.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});";
const fresh=cp.spawnSync(process.execPath,['-e',code,home,f.project,f.runId,p.fingerprint],{encoding:'utf8',timeout:15000});assert.equal(fresh.status,0,fresh.stdout+fresh.stderr);db.reloadJson();assert.equal(db.getBatchRun(f.runId).status,'success');assert.equal(db.getLoopRun(original.run_id).started_at,original.started_at);assert.equal(db.getLoopRun(original.run_id).total_cost,.02);assert.equal(db.getLoopIterations(original.run_id).length,1);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('intentional later iterations keep the original approved settings checks after the restored prefix is consumed',async()=>{
const f=await fixture({loseIteration:2}),p=await prepare(f),config=require('../../src/config-manager'),get=config.getConfig;let calls=0;
engine.executeNode=async()=>{calls++;config.getConfig=()=>({...get(),locale:'changed in intentional third iteration'});return{value:3};};
try{const result=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(result.success,false);assert.match(result.error,/์ค์ .*๋ณ๊ฒฝ/);assert.equal(calls,1);const c=db.getBatchCheckpoint(f.runId);assert.equal(c.entries['3:0:0'].status,'completed');assert.equal(c.entries['3:1:0'],undefined);assert.equal(Object.values(c.loopEvents).filter(e=>e.phase==='evaluated').length,2);}finally{config.getConfig=get;}
});
// ์ ์ฅ๋ phase๋ง ์๋นํ๋ค. goal ๊ฒฐ๊ณผ๋ฅผ ์ธ๋ถ ํ์ฌ ์ํ๋ก ๋ค์ ๊ณ์ฐํ์ง ์๋๋ค.
test('a durable terminal evaluation finishes even when the original goal is no longer true, without goal or child replay',async()=>{
const f=await fixture({failPhase:'settled',ready:true}),c=db.getBatchCheckpoint(f.runId),saved=Object.values(c.loopEvents).at(-1);assert.equal(saved.phase,'evaluated');assert.equal(saved.result.goalMet,true);fs.unlinkSync(path.join(f.project,'READY'));
const Controller=require('../../src/loop-controller').LoopController,evaluate=Controller.prototype.evaluateTermination;Controller.prototype.evaluateTermination=async()=>{throw Error('saved goal replayed');};engine.executeNode=async()=>{throw Error('saved child replayed');};
try{const p=await prepare(f),r=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(r.success,true,r.error);}finally{Controller.prototype.evaluateTermination=evaluate;}
const events=Object.values(db.getBatchCheckpoint(f.runId).loopEvents);assert.equal(events.filter(e=>e.phase==='evaluated').length,1);assert.deepEqual(events.find(e=>e.phase==='evaluated'),saved);assert.equal(db.getLoopIterations('looprun-'+f.runId).length,1);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);
});
for(const [failPhase,phase]of [['analysis_intent','evaluated'],['settlement_intent','analyzed'],['committed','settled'],['steps','committed']])test('saved '+phase+' resumes its remaining phase and only the intentional next iteration',async()=>{
const f=await fixture({failPhase,failIteration:failPhase==='steps'?2:1}),original=db.getLoopIterations('looprun-'+f.runId),c=db.getBatchCheckpoint(f.runId),saved=Object.values(c.loopEvents).at(-1);assert.equal(saved.phase,phase);
const Controller=require('../../src/loop-controller').LoopController,evaluate=Controller.prototype.evaluateTermination;let evaluations=0,calls=0;Controller.prototype.evaluateTermination=function(...args){evaluations++;return evaluate.apply(this,args);};engine.executeNode=async()=>{calls++;fs.writeFileSync(path.join(f.project,'READY'),'ready');return{value:2};};
try{const p=await prepare(f),r=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(r.success,true,r.error);}finally{Controller.prototype.evaluateTermination=evaluate;}
assert.equal(calls,1);assert.equal(evaluations,1);const events=Object.values(db.getBatchCheckpoint(f.runId).loopEvents);assert.deepEqual(events.find(e=>e.key===saved.key),saved);assert.equal(events.filter(e=>e.phase==='evaluated').length,2);assert.equal(events.filter(e=>e.phase==='analyzed').length,1);assert.equal(events.find(e=>e.phase==='committed').history.length,1);const rows=db.getLoopIterations('looprun-'+f.runId);assert.equal(rows.length,2);assert.equal(rows[0].started_at,original[0].started_at);assert.equal(rows[0].cost,.02);assert.equal(rows[1].cost,0);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);
});
test('failed committed journal publication rolls back ledger finalization before failure records are written',async()=>{
const f=await fixture({failPhase:'committed',ready:true}),row=db.getLoopRun('looprun-'+f.runId),iteration=db.getLoopIterations(row.run_id)[0];assert.equal(Object.values(db.getBatchCheckpoint(f.runId).loopEvents).at(-1).phase,'settled');assert.equal(row.status,'failed');assert.equal(iteration.status,'failed');const p=await prepare(f);engine.executeNode=async()=>{throw Error('settled child replayed');};assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);assert.equal(db.getLoopRun(row.run_id).status,'completed');assert.equal(db.getLoopRun(row.run_id).total_cost,.02);
});
test('a terminal committed loop with failed batch publication restores only batch completion',async()=>{
const f=await fixture({ready:true,failCompletion:true}),c=db.getBatchCheckpoint(f.runId),saved=Object.values(c.loopEvents).at(-1),loop=db.getLoopRun('looprun-'+f.runId),iterations=db.getLoopIterations(loop.run_id);assert.equal(saved.phase,'committed');assert.equal(loop.status,'completed');
const Controller=require('../../src/loop-controller').LoopController,evaluate=Controller.prototype.evaluateTermination;Controller.prototype.evaluateTermination=async()=>{throw Error('terminal goal replayed');};engine.executeNode=async()=>{throw Error('terminal child replayed');};try{const p=await prepare(f);assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);}finally{Controller.prototype.evaluateTermination=evaluate;}
assert.deepEqual(db.getLoopRun(loop.run_id),loop);assert.deepEqual(db.getLoopIterations(loop.run_id),iterations);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.runId).loopEvents).at(-1),saved);assert.equal(db.getBatchRun(f.runId).status,'success');
});
test('an analysis intent without complete independent observations remains blocked and never reissues the model effect',async()=>{
const f=await fixture({failPhase:'analyzed'}),source=Object.values(db.getBatchCheckpoint(f.runId).loopEvents).at(-1),get=db.getBatchLoopObservations;assert.equal(source.phase,'analysis_intent');db.getBatchLoopObservations=(id,key)=>id===f.runId&&key===source.key?null:get(id,key);try{await assert.rejects(prepare(f));}finally{db.getBatchLoopObservations=get;}assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);
});
test('failure after nested committed save rolls back checkpoint memory and ledger together',async()=>{
const f=await fixture({ready:true,failAfterCommit:true}),c=db.getBatchCheckpoint(f.runId);assert.equal(Object.values(c.loopEvents).at(-1).phase,'settled');assert.equal(db.getLoopRun('looprun-'+f.runId).status,'failed');assert.equal(db.getLoopIterations('looprun-'+f.runId)[0].status,'failed');assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);
engine.executeNode=async()=>{throw Error('rolled back phase replayed');};const p=await prepare(f),result=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(result.success,true,result.error);assert.equal(db.getLoopRun('looprun-'+f.runId).status,'completed');assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);
});
test('a fresh process consumes analyzed history and starts only its new iteration',async()=>{
const f=await fixture({failPhase:'settlement_intent'}),p=await prepare(f),saved=Object.values(db.getBatchCheckpoint(f.runId).loopEvents).at(-1),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock'),target=owners.file(f.task.id),cp=require('child_process');assert.equal(saved.phase,'analyzed');owners.claimReview(f.task.id,locks.readLock(target),f.runId).release();fs.writeFileSync(path.join(f.project,'READY'),'ready');
const code="require('os').homedir=()=>process.argv[1];require('./src/context').currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const engine=require('./src/workflow-manager');engine.executeNode=async()=>({value:2});const batch=require('./src/batch-manager');batch.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log('RESULT:'+JSON.stringify({success:r.success,error:r.error}));await engine.cleanupAll();await batch.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});";
const result=cp.spawnSync(process.execPath,['-e',code,home,f.project,f.runId,p.fingerprint],{encoding:'utf8',timeout:15000});assert.equal(result.status,0,result.stdout+result.stderr);db.reloadJson();assert.equal(db.getBatchRun(f.runId).status,'success');assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);assert.equal(db.getLoopIterations('looprun-'+f.runId).length,2);assert.deepEqual(Object.values(db.getBatchCheckpoint(f.runId).loopEvents).find(e=>e.key===saved.key),saved);
});
test('review emits no HUD and the first resumed HUD uses the durable controller counters',async()=>{
const f=await fixture({failPhase:'settled',ready:true}),event=Object.values(db.getBatchCheckpoint(f.runId).loopEvents).at(-1),hud=require('../../src/services/loop-hud'),updates=[],listener=e=>{if(e.runId===f.runId)updates.push(e);};hud.on('update',listener);
try{const p=await prepare(f);assert.equal(updates.length,0);engine.executeNode=async()=>{throw Error('HUD fixture child replayed');};assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);assert.ok(updates.length);assert.equal(updates[0].iteration,event.controller.currentIteration);assert.equal(updates[0].cost,event.controller.cumulativeCost);}finally{hud.removeListener('update',listener);}
});
|