bada-terminal / test /wrapper /batch-loop-outbox.test.cjs
VanyaJ's picture
Release BADA Terminal v2.1.0 (Enterprise Ontology, NVIDIA auto-ontology, Release Preflight)
d739b1b verified
Raw History Blame Contribute Delete
15.4 kB
// ์‹ค์ œ ๋ฐฐ์น˜/์›์žฅ๊ณผ ์•Œ๋ฆผ ๋ฐ˜ํ™˜ ๊ฒฝ๊ณ„๋ฅผ ์—ฐ๊ฒฐํ•œ๋‹ค. OS๊ฐ€ ์•Œ๋ฆผ์„ ํ‘œ์‹œํ–ˆ๋‹ค๋Š” ์ฆ๊ฑฐ๋กœ ๋Œ€์ฒดํ•˜์ง€ ์•Š๋Š”๋‹ค.
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/batch-step-continuation.md (v0.7.0, R67 ์ง„ํ–‰ ์ค‘)
const {test,after}=require('node:test'),assert=require('node:assert/strict'),fs=require('fs'),path=require('path'),os=require('os'),{randomUUID}=require('crypto');
const home=fs.mkdtempSync(path.resolve('scratch/batch-outbox-')),oldHome=os.homedir;os.homedir=()=>home;
require('../../src/context').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()=>{};require('../../src/wiki-run-archiver').archiveBatchRun=async()=>({success:true});
const db=require('../../knowledge-db'),batch=require('../../src/batch-manager'),hud=require('../../src/services/loop-hud'),notifier=require('../../src/loop-notifier'),native=notifier.notifyLoopComplete,warning=notifier.notifyLoopWarning;
after(async()=>{await batch.cleanupAllActiveRuns();notifier.notifyLoopComplete=native;notifier.notifyLoopWarning=warning;os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));});
function task(){const project=fs.mkdtempSync(path.join(home,'case-')),item={id:randomUUID(),project_id:project,is_active:0,name:'durable publication',loop_config:JSON.stringify({goals:[{type:'file_exists',target:'READY'}],max_iterations:2,token_budget:1}),steps:[{id:'value',type:'transform',config:{script:'return {done:true};'}}]};fs.writeFileSync(path.join(project,'READY'),'ready');db.saveBatchTask(project,item);return item;}
async function prepare(item,id){const owner={},api=require('../../src/services/batch-continuation').create({owner,scope:require('../../src/services/mcp-project-scope').capture(item.project_id),authorize:()=>true,approve:async()=>({approved:true})}),review=api.preview(id,{owner});return api.commit(review.ticketId,{owner,confirmed:true});}
async function capture(item,action){const events={native:[],ipc:[],hud:[]};const snapshot=(kind,data)=>{const id=data.runId||data[0],c=db.getBatchCheckpoint(id),loop=db.getLoopRun('looprun-'+id);events[kind].push({data,phase:Object.values(c?.loopEvents||{}).at(-1)?.phase,status:loop?.status});};notifier.notifyLoopComplete=(...data)=>{snapshot('native',data);return{status:'submitted'};};const ipc=data=>snapshot('ipc',data),update=data=>{if(data.status==='completed'||data.status==='circuit_broken'||data.status==='failed'||data.status==='aborted')snapshot('hud',data);};batch.batchEvents.on('loop:complete',ipc);hud.on('update',update);try{return{result:await action(),events};}finally{notifier.notifyLoopComplete=native;batch.batchEvents.off('loop:complete',ipc);hud.off('update',update);}}
const runId=item=>db.getBatchRuns(item.id)[0].run_id;
test('native completion, terminal HUD and IPC are published only after committed ledger and each has a durable receipt',async()=>{
const item=task(),{result,events}=await capture(item,()=>batch.runTask(item));assert.equal(result.success,true,result.error);for(const kind of ['native','hud','ipc']){assert.equal(events[kind].length,1,kind);assert.equal(events[kind][0].phase,'committed');assert.equal(events[kind][0].status,'completed');}const c=db.getBatchCheckpoint(runId(item));assert.ok(c.loopPublications);assert.equal(Object.values(c.loopPublications).filter(e=>e.kind==='ready').length,1);assert.equal(Object.values(c.loopPublications).filter(e=>e.kind==='submitted').length,3);
});
for(const phase of ['evaluated','committed'])test(phase+' persistence failure never publishes goal completion and failed HUD/IPC follow failed ledger',async()=>{
const item=task(),save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(Object.values(c.loopEvents||{}).at(-1)?.phase===phase)throw Error('controlled goal persistence failure');return save(c,...args);};let captured;try{captured=await capture(item,()=>batch.runTask(item));}finally{db.saveBatchCheckpoint=save;}assert.equal(captured.result.success,false);assert.equal(captured.events.native.length,0);assert.equal(captured.events.hud.some(e=>e.data.status==='completed'),false);assert.equal(captured.events.ipc.some(e=>e.data.status==='completed'),false);assert.ok(captured.events.hud.length);assert.ok(captured.events.hud.every(e=>e.status==='failed'));assert.ok(captured.events.ipc.every(e=>e.status==='failed'));
});
test('resuming committed batch publication failure never duplicates native, terminal HUD or IPC',async()=>{
const item=task(),complete=db.completeBatchRun;let id;const {result,events}=await capture(item,async()=>{db.completeBatchRun=(run,status,error)=>{if(status==='success'){complete(run,'failed','controlled batch completion failure');throw Error('controlled batch completion failure');}return complete(run,status,error);};let first;try{first=await batch.runTask(item);}finally{db.completeBatchRun=complete;}assert.equal(first.success,false);id=runId(item);const p=await prepare(item,id);return batch.resumeBatchRun(id,{fingerprint:p.fingerprint});});assert.equal(result.success,true,result.error);for(const k of ['native','hud','ipc'])assert.equal(events[k].length,1,k);assert.equal(db.getLoopIterations('looprun-'+id).length,1);
});
for(const channel of ['hud','ipc','native'])for(const boundary of ['intent','submitted'])test(channel+' '+boundary+' storage failure preserves publication state and safe same-run continuation',async()=>{
const item=task(),save=db.saveBatchCheckpoint;let id;const {result,events}=await capture(item,async()=>{db.saveBatchCheckpoint=(c,...args)=>{const e=Object.values(c.loopPublications||{}).at(-1);if(e?.kind===boundary&&e.channel===channel)throw Error('controlled publication '+boundary+' failure');return save(c,...args);};let first;try{first=await batch.runTask(item);}finally{db.saveBatchCheckpoint=save;}assert.equal(first.success,false);id=runId(item);let p;if(channel==='native'&&boundary==='submitted'){
const handlers=new Map(),sender={isDestroyed:()=>false,mainFrame:{url:require('url').pathToFileURL(path.resolve('batch-scheduler.html')).href}},event={sender,senderFrame:sender.mainFrame};require('../../src/ipc/batch-continuation-ipc').register({handle:(name,handler)=>handlers.set(name,handler)},{currentCwd:item.project_id},{BrowserWindow:{fromWebContents:()=>({})},dialog:{showMessageBox:async(_parent,options)=>{assert.match(options.detail,/์•Œ๋ฆผ ์ œ์ถœ ๋ฏธํ™•์ธ: 1๊ฑด/);assert.match(options.detail,/ํ™•์ธ ๋น„์šฉ: \$0/);return{response:1};}}});const handler=handlers.get('batch:continue-run'),review=await handler(event,id,{action:'review'});assert.equal(review.success,true);assert.equal(review.review.loopPublications.uncertain,1);const accepted=await handler(event,id,{action:'accept',fingerprint:review.review.fingerprint});assert.equal(accepted.success,true);p=accepted.result;
}else p=await prepare(item,id);return batch.resumeBatchRun(id,{fingerprint:p.fingerprint});});assert.equal(result.success,true,result.error);assert.equal(events.native.length,1);assert.equal(events.hud.length,1);assert.equal(events.ipc.length,1);const summary=require('../../src/services/batch-loop-outbox').summary(db.getBatchCheckpoint(id));assert.equal(summary.uncertain,boundary==='submitted'?1:0);assert.equal(summary.pending,0);
});
test('outbox enqueue failure rolls back committed phase and ledger as one transaction',async()=>{
const item=task(),save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{const e=Object.values(c.loopPublications||{}).at(-1);if(e?.kind==='ready'&&e.data.source.kind==='committed')throw Error('controlled enqueue failure');return save(c,...args);};let first;try{first=await capture(item,()=>batch.runTask(item));}finally{db.saveBatchCheckpoint=save;}assert.equal(first.result.success,false);assert.equal(first.events.native.length,0);const id=runId(item);assert.equal(Object.values(db.getBatchCheckpoint(id).loopEvents).at(-1).phase,'settled');assert.equal(db.getLoopRun('looprun-'+id).status,'failed');const p=await prepare(item,id),last=await capture(item,()=>batch.resumeBatchRun(id,{fingerprint:p.fingerprint}));assert.equal(last.result.success,true,last.result.error);assert.equal(last.events.native.length,1);
});
test('a throwing IPC subscriber leaves explicit uncertainty without failing the completed work or skipping native submission',async()=>{
const item=task(),broken=()=>{throw Error('closed subscriber');};batch.batchEvents.on('loop:complete',broken);let captured;try{captured=await capture(item,()=>batch.runTask(item));}finally{batch.batchEvents.off('loop:complete',broken);}assert.equal(captured.result.success,true,captured.result.error);assert.equal(captured.events.native.length,1);const s=require('../../src/services/batch-loop-outbox').summary(db.getBatchCheckpoint(runId(item)));assert.equal(s.uncertain,1);assert.equal(s.pending,0);assert.equal(captured.result.loopPublications.uncertain,1);
});
test('a fresh process restores submitted committed HUD silently and does not submit any notification channel again',async()=>{
const item=task(),complete=db.completeBatchRun;const first=await capture(item,async()=>{db.completeBatchRun=(id,status,error)=>{if(status==='success'){complete(id,'failed','controlled completion failure');throw Error('controlled completion failure');}return complete(id,status,error);};try{return await batch.runTask(item);}finally{db.completeBatchRun=complete;}});assert.equal(first.result.success,false);const id=runId(item),p=await prepare(item,id),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock');owners.claimReview(item.id,locks.readLock(owners.file(item.id)),id).release();
const code="require('os').homedir=()=>process.argv[1];require('./src/context').currentCwd=process.argv[2];require('./src/services/governance-client').cachedPolicy={enabled:false};const n=require('./src/loop-notifier');let native=0,ipc=0,hud=0;n.notifyLoopComplete=()=>{native++;return{status:'submitted'}};const h=require('./src/services/loop-hud');h.on('update',e=>{if(e.status==='completed')hud++;});const b=require('./src/batch-manager');b.batchEvents.on('loop:complete',()=>ipc++);b.resumeBatchRun(process.argv[3],{fingerprint:process.argv[4]}).then(async r=>{console.log('RESULT:'+JSON.stringify({success:r.success,error:r.error,native,ipc,hud,snapshot:h.snapshot().find(e=>e.runId===process.argv[3])?.status}));await b.cleanupAllActiveRuns();process.exitCode=r.success?0:1;});";
const child=require('child_process').spawnSync(process.execPath,['-e',code,home,item.project_id,id,p.fingerprint],{encoding:'utf8',timeout:15000});assert.equal(child.status,0,child.stdout+child.stderr);const result=JSON.parse(child.stdout.split('\n').find(l=>l.startsWith('RESULT:')).slice(7));assert.deepEqual(result,{success:true,error:null,native:0,ipc:0,hud:0,snapshot:'completed'});db.reloadJson();assert.equal(db.getBatchRun(id).status,'success');
});
test('acknowledged publication cannot be changed or replaced even with a recomputed hash',async()=>{
const item=task();assert.equal((await capture(item,()=>batch.runTask(item))).result.success,true);const id=runId(item),c=db.getBatchCheckpoint(id),copy=structuredClone(c),key=Object.keys(copy.loopPublications).at(-1),e=copy.loopPublications[key];e.kind='intent';const {eventHash,...body}=e;e.eventHash=require('../../src/services/bong-browser-resolution').hash(body);copy.revision++;assert.throws(()=>db.saveBatchCheckpoint(copy,c.revision));assert.deepEqual(db.getBatchCheckpoint(id),c);
});
for(const failure of [false,true])test('budget warning follows durable evaluation and never escapes an uncommitted result: '+failure,async()=>{
const item=task(),engine=require('../../src/workflow-manager'),execute=engine.executeNode,wf={id:randomUUID(),name:'known usage',graph:{nodes:[{id:'paid',type:'input',config:{}}],edges:[]}};db.saveWorkflow(item.project_id,wf);item.steps=[{id:'paid',type:'workflow',config:{workflowId:wf.id}}];db.saveBatchTask(item.project_id,item);engine.executeNode=async run=>{require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.85,1,{id:'paid',costSource:'provider_reported',totalTokens:2});return{paid:true};};const save=db.saveBatchCheckpoint,warnings=[];notifier.notifyLoopWarning=(id)=>{warnings.push(Object.values(db.getBatchCheckpoint(id).loopEvents).at(-1).phase);return{status:'submitted'};};if(failure)db.saveBatchCheckpoint=(c,...args)=>{if(Object.values(c.loopEvents||{}).at(-1)?.phase==='evaluated')throw Error('warning evaluation save failure');return save(c,...args);};
try{const {result}=await capture(item,()=>batch.runTask(item));assert.equal(result.success,!failure,result.error);assert.deepEqual(warnings,failure?[]:['committed']);}finally{engine.executeNode=execute;db.saveBatchCheckpoint=save;notifier.notifyLoopWarning=warning;await engine.cleanupAll();}
});
test('pending earlier failure HUD and IPC are superseded by the later committed result rather than overwriting current completion',async()=>{
const item=task(),save=db.saveBatchCheckpoint;let id;const {result,events}=await capture(item,async()=>{db.saveBatchCheckpoint=(c,...args)=>{if(Object.values(c.loopEvents||{}).at(-1)?.phase==='committed')throw Error('controlled committed loss');const e=Object.values(c.loopPublications||{}).at(-1);if(e?.kind==='intent'&&e.channel==='hud')throw Error('controlled stopped HUD intent loss');return save(c,...args);};let first;try{first=await batch.runTask(item);}finally{db.saveBatchCheckpoint=save;}assert.equal(first.success,false);id=runId(item);const p=await prepare(item,id);return batch.resumeBatchRun(id,{fingerprint:p.fingerprint});});assert.equal(result.success,true,result.error);assert.equal(events.native.length,1);assert.equal(events.hud.length,1);assert.equal(events.hud[0].data.status,'completed');assert.equal(events.ipc.length,1);assert.equal(events.ipc[0].data.status,'completed');assert.equal(result.loopPublications.superseded,2);assert.equal(hud.snapshot().find(e=>e.runId===id).status,'completed');
});
test('one batch completion reaches each actual window once including an aliased scheduler and the workflow monitor',async()=>{
const ctx=require('../../src/context'),old={mainWindow:ctx.mainWindow,batchSchedulerWindow:ctx.batchSchedulerWindow,workflowMonitorWindow:ctx.workflowMonitorWindow},sent=[],window=id=>({isDestroyed:()=>false,webContents:{send:(channel,data)=>sent.push({id,channel,data})}}),shared=window('shared');ctx.mainWindow=shared;ctx.batchSchedulerWindow=shared;ctx.workflowMonitorWindow=window('monitor');
try{const item=task();assert.equal((await capture(item,()=>batch.runTask(item))).result.success,true);for(const id of ['shared','monitor'])assert.equal(sent.filter(e=>e.id===id&&e.channel==='loop:complete').length,1,id);ctx.mainWindow={isDestroyed:()=>false,webContents:{send:()=>{throw Error('closed IPC target');}}};const next=task(),last=await capture(next,()=>batch.runTask(next));assert.equal(last.result.success,true);assert.equal(last.result.loopPublications.uncertain,1);for(const id of ['shared','monitor'])assert.equal(sent.filter(e=>e.id===id&&e.channel==='loop:complete'&&e.data.runId===runId(next)).length,1,id);}finally{Object.assign(ctx,old);}
});