bada-terminal / test /wrapper /batch-memory-continuation.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
20.9 kB
// ๊ฒฉ๋ฆฌ DB์— ๊ณผ๊ฑฐ ํ˜•์‹๋งŒ ์žฌํ˜„ํ•˜๊ณ  ์‹ค์ œ ์Šน์ธ/transaction/๊ฐ™์€ ์‹คํ–‰ ์žฌ๊ฐœ๋ฅผ ๊ฒ€์ฆํ•œ๋‹ค.
// ์„ค๋ช… ๋ฌธ์„œ: docs/specs/batch-memory-continue.md v1.0.0
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-memory-resume-')),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,{hash}=require('../../src/services/bong-browser-resolution');
after(async()=>{await engine.cleanupAll();await batch.cleanupAllActiveRuns();engine.executeNode=execute;os.homedir=oldHome;process.once('exit',()=>fs.rmSync(home,{recursive:true,force:true}));});
const legacy=runId=>require('../helpers/batch-memory-legacy-fixture.cjs')(db,home,runId);
async function fixture({last=false,failPhase,failIteration=1,nonterminal=false,breaker=3,paidFailure=false}={}){
const project=fs.mkdtempSync(path.join(home,'case-')),workflow={id:randomUUID(),name:'paid child',graph:{nodes:[{id:'work',type:'input',config:{}}],edges:[]}},optional={id:'optional',type:'transform',on_failure:'continue',config:{script:"throw Error('original continued error')"}},child={id:'child',type:'workflow',config:{workflowId:workflow.id,timeoutMs:3000,...(!last?{inputs:{duration:'{{steps.optional._duration}}',error:'{{steps.optional.error}}'}}:{})}},task={id:randomUUID(),project_id:project,name:'approve memory output',is_active:0,loop_config:JSON.stringify({goals:nonterminal?[{type:'file_exists',target:'READY'}]:[{type:'metric_threshold',metric_key:'optional._duration',operator:'>=',value:0}],max_iterations:4,token_budget:1,consecutive_failure_threshold:breaker}),steps:last?[child,optional]:[optional,child]};if(paidFailure){const quote=require('../../src/config/claude-execution-config').quoteShellArgument,source="const fixtureSession=require('crypto').randomUUID();console.log(JSON.stringify({type:'system',subtype:'init',session_id:fixtureSession}));console.log(JSON.stringify({uuid:require('crypto').randomUUID(),is_error:false,type:'result',subtype:'success',result:'public paid failure',total_cost_usd:.01,usage:{input_tokens:1,output_tokens:1},session_id:fixtureSession}));process.exitCode=9;",script=path.join(project,'fixture.cjs'),binary=path.join(project,process.platform==='win32'?'claude.cmd':'claude');fs.writeFileSync(script,source);fs.writeFileSync(binary,process.platform==='win32'?'@echo off\r\n'+quote(process.execPath)+' '+quote(script)+' %*\r\n':'#!'+process.execPath+'\n'+source,{mode:0o700});Object.assign(optional,{type:'pty_agent',config:{is_oneshot:true,cli_engine:quote(binary),prompt:'fixture',timeout:2}});}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:42};};const save=db.saveBatchCheckpoint;
db.saveBatchCheckpoint=(c,...args)=>{const phase=Object.values(c.loopEvents||{}).at(-1)?.phase;if(failPhase?phase===failPhase&&Object.values(c.loopEvents).at(-1).iteration===failIteration:last?phase==='evaluated':c.entries[failIteration+':1:0']?.status==='completed')throw Error('injected publication loss');return save(c,...args);};try{assert.equal((await batch.runTask(task)).success,false);}finally{db.saveBatchCheckpoint=save;}assert.equal(calls,failIteration);const runId=db.getBatchRuns(task.id)[0].run_id,{original,c}=legacy(runId);return{project,workflow,task,runId,original,c,key:failIteration+':'+(last?1:0)+':0'};
}
function service(f,overrides={}){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}),...overrides});return{owner,api};}
async function prepare(f){const{owner,api}=service(f),p=api.preview(f.runId,{owner});return api.commit(p.ticketId,{owner,confirmed:true});}
for(const last of[false,true])test('approved memory continue '+(last?'goal-consumed':'child-consumed')+' output resumes the same execution without rewriting its original failure',async()=>{
const f=await fixture({last}),before=db.getBatchCheckpoint(f.runId),u=db.getRuntimeUsage(f.runId),raw=db.getLoopIterations('looprun-'+f.runId),p=await prepare(f),prepared=db.getBatchCheckpoint(f.runId),g=Object.values(prepared.recoveries).at(-1);assert.deepEqual(prepared.entries,before.entries);assert.equal(prepared.continuations,undefined);assert.deepEqual(g.memoryContinuations[f.key].output,f.original.continuations[f.key].output);assert.deepEqual(g.loopState.originalIterations,raw);engine.executeNode=async()=>{throw Error('paid child replayed');};const result=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(result.success,true,result.error);assert.deepEqual(result.stepOutputs.optional,f.original.continuations[f.key].output);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries,before.entries);assert.equal(db.getBatchCheckpoint(f.runId).continuations,undefined);assert.deepEqual(db.getRuntimeUsage(f.runId),u);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);assert.equal(db.getLoopIterations('looprun-'+f.runId)[0].status,'failed');assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,2);
});
test('cancelling native preparation leaves raw candidates and entries without an approval or effects',async()=>{const f=await fixture(),before=db.getBatchCheckpoint(f.runId),raw=db.getLoopIterations('looprun-'+f.runId),{owner,api}=service(f,{approve:async()=>({approved:false})}),p=api.preview(f.runId,{owner});assert.deepEqual(p.memoryContinueStepIds,['optional']);await assert.rejects(api.commit(p.ticketId,{owner,confirmed:true}));assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.deepEqual(db.getLoopIterations('looprun-'+f.runId),raw);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);});
test('candidate mutation while approving invalidates the fingerprint before any grant',async()=>{const f=await fixture(),{owner,api}=service(f,{approve:async()=>{const row=db.getLoopIterations('looprun-'+f.runId)[0],outputs=JSON.parse(row.step_outputs);outputs.optional._duration='999.99';db.saveLoopIteration({...row,step_outputs:JSON.stringify(outputs)});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('grant storage failure rolls back the paused handoff and all original failure records',async()=>{const f=await fixture(),before=db.getBatchCheckpoint(f.runId),row=db.getBatchRun(f.runId),save=db.saveBatchCheckpoint;db.saveBatchCheckpoint=(c,...args)=>{if(c.recoveries)throw Error('grant disk failure');return save(c,...args);};try{await assert.rejects(prepare(f));}finally{db.saveBatchCheckpoint=save;}assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.deepEqual(db.getBatchRun(f.runId),row);assert.equal((await prepare(f)).status,'paused');});
test('loop writer failure restores raw rows and the same approved grant for retry without child replay',async()=>{const f=await fixture({last:true}),p=await prepare(f),before=db.getBatchCheckpoint(f.runId),row=db.getBatchRun(f.runId),raw=db.getLoopIterations('looprun-'+f.runId),save=db.saveLoopIteration;db.saveLoopIteration=()=>{throw Error('loop handoff disk failure');};try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,false);}finally{db.saveLoopIteration=save;}assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.deepEqual(db.getBatchRun(f.runId),row);assert.deepEqual(db.getLoopIterations('looprun-'+f.runId),raw);engine.executeNode=async()=>{throw Error('retry replayed child');};assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);});
test('the continued failure keeps its original breaker count and stops before another paid iteration',async()=>{const f=await fixture({nonterminal:true,breaker:1}),p=await prepare(f);let calls=0;engine.executeNode=async()=>{calls++;throw Error('paid work repeated');};const r=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(r.success,false);assert.equal(calls,0);const row=db.getLoopRun('looprun-'+f.runId);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('a later legacy candidate requires the complete independent earlier committed prefix',async()=>{const f=await fixture({nonterminal:true,failIteration:2}),get=db.getBatchLoopObservations,prior=Object.values(f.c.loopEvents).find(e=>e.iteration===1&&e.phase==='evaluation_intent');db.getBatchLoopObservations=(id,key)=>id===f.runId&&key===prior.key?null:get(id,key);try{await assert.rejects(prepare(f));}finally{db.getBatchLoopObservations=get;}assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);assert.equal(db.getWorkflowRuns(f.workflow.id).length,2);});
test('a later recovery preserves the original committed row and both consumed memory outputs',async()=>{const f=await fixture({nonterminal:true,failIteration:2}),prior=db.getLoopIterations('looprun-'+f.runId)[0],p=await prepare(f),g=Object.values(db.getBatchCheckpoint(f.runId).recoveries)[0];assert.equal(Object.keys(g.memoryContinuations).length,2);fs.writeFileSync(path.join(f.project,'READY'),'ready');engine.executeNode=async()=>{throw Error('earlier or current child replayed');};const r=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(r.success,true,r.error);assert.deepEqual(db.getLoopIterations('looprun-'+f.runId)[0],prior);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.04);assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,3);});
test('a second recovery after new continued work preserves the first approval hash and original candidate source',async()=>{const f=await fixture({nonterminal:true,failPhase:'settlement_intent'}),p=await prepare(f),first=structuredClone(Object.values(db.getBatchCheckpoint(f.runId).recoveries)[0]),save=db.saveBatchCheckpoint;let calls=0;engine.executeNode=async run=>{calls++;require('../../src/services/usage-request').begin(run,'cli','paid');engine.addRunUsage(run.runId,.03,1,{id:'paid',costSource:'provider_reported',totalTokens:3});return{value:43};};db.saveBatchCheckpoint=(c,...args)=>{if(c.entries['2:1:0']?.status==='completed')throw Error('second child publication lost');return save(c,...args);};try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,false);}finally{db.saveBatchCheckpoint=save;}assert.equal(calls,1);fs.writeFileSync(path.join(f.project,'READY'),'ready');const second=await prepare(f);engine.executeNode=async()=>{throw Error('second recovery replayed paid child');};const r=await batch.resumeBatchRun(f.runId,{fingerprint:second.fingerprint});assert.equal(r.success,true,r.error);const grants=Object.values(db.getBatchCheckpoint(f.runId).recoveries);assert.equal(grants.length,2);assert.deepEqual(grants[0],first);assert.equal(grants[1].memoryContinuations,undefined);assert.ok(Math.abs(db.getLoopRun('looprun-'+f.runId).total_cost-.05)<1e-9);});
test('an approved candidate can be revoked after current settings change while preserving its original evidence',async()=>{const f=await fixture({last:true}),p=await prepare(f),before=db.getBatchCheckpoint(f.runId),config=require('../../src/config-manager'),get=config.getConfig;config.getConfig=()=>({...get(),locale:'changed after preparation'});try{const{owner,api}=service(f),review=api.reviewRevocation(f.runId,{owner});const r=await api.revoke(f.runId,{owner,confirmed:true,fingerprint:review.fingerprint});assert.equal(r.status,'aborted');assert.deepEqual(db.getBatchCheckpoint(f.runId).recoveries,before.recoveries);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries,before.entries);assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,false);}finally{config.getConfig=get;}});
test('expired steps retain the first epoch rather than receiving a fresh wall-time allowance',async()=>{const f=await fixture(),now=Date.now;Date.now=()=>now()+4000000;try{await assert.rejects(prepare(f));}finally{Date.now=now;}assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);});
test('a fresh process consumes only the approved original outputs and leaves the original paid child intact',async()=>{const f=await fixture({last:true}),p=await prepare(f),cp=require('child_process'),owners=require('../../src/services/batch-run-lease'),locks=require('../../src/db/reviewed-store-lock'),target=owners.file(f.task.id);owners.claimReview(f.task.id,locks.readLock(target),f.runId).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 engine=require('./src/workflow-manager');engine.executeNode=async()=>{throw Error('fresh 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,optional:r.stepOutputs?.optional}));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.getWorkflowRuns(f.workflow.id).length,1);assert.equal(db.getLoopRun('looprun-'+f.runId).total_cost,.02);});
test('a known paid CLI failure and its original request remain charged once through approved memory continuation',async()=>{const f=await fixture({paidFailure:true}),u=db.getRuntimeUsage(f.runId),own=u.usage.entries.find(e=>e.complete===false);assert.ok(own);assert.equal(own.costUsd,.01);const p=await prepare(f);engine.executeNode=async()=>{throw Error('paid child replay');};const r=await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint});assert.equal(r.success,true,r.error);assert.deepEqual(db.getRuntimeUsage(f.runId),u);assert.ok(Math.abs(db.getLoopRun('looprun-'+f.runId).total_cost-.03)<1e-9);assert.equal(require('../../src/services/workflow-invocation-tree').inspect(db,f.runId,f.project).runs.size,2);});
test('the original task serialization remains provable when its current definition changes before revocation',async()=>{const f=await fixture({last:true});await prepare(f);const before=db.getBatchCheckpoint(f.runId),task=db.getBatchTasks(f.project).find(t=>t.id===f.task.id);db.saveBatchTask(f.project,{...task,steps_json:JSON.stringify([{id:'changed',type:'transform',config:{script:'return {};'}}])});const{owner,api}=service(f),review=api.reviewRevocation(f.runId,{owner});assert.equal((await api.revoke(f.runId,{owner,confirmed:true,fingerprint:review.fingerprint})).status,'aborted');assert.deepEqual(db.getBatchCheckpoint(f.runId).recoveries,before.recoveries);});
test('a preserved memory grant cannot be edited even if its output and approval hashes are recomputed',async()=>{const f=await fixture(),p=await prepare(f),before=db.getBatchCheckpoint(f.runId),next=structuredClone(before),g=Object.values(next.recoveries)[0];g.memoryContinuations[f.key].output._duration='777.77';g.memoryContinuations[f.key].outputHash=hash(g.memoryContinuations[f.key].output);const{approvalHash:_,...body}=g;g.approvalHash=hash(body);next.revision++;assert.throws(()=>db.saveBatchCheckpoint(next,before.revision,()=>true));assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.equal(p.status,'paused');});
function ipc(f){const{EventEmitter}=require('events'),sender=new EventEmitter(),handlers=new Map(),context={currentCwd:f.project},dialogs=[];sender.isDestroyed=()=>false;sender.mainFrame={url:require('url').pathToFileURL(path.resolve('batch-scheduler.html')).href};require('../../src/ipc/batch-continuation-ipc').register({handle:(name,fn)=>handlers.set(name,fn)},context,{BrowserWindow:{fromWebContents:s=>s===sender?{}:null},dialog:{showMessageBox:async(_parent,o)=>{dialogs.push(o);return{response:1};}}});return{dialogs,sender,invoke:input=>handlers.get('batch:continue-run')({sender,senderFrame:sender.mainFrame},f.runId,input)};}
test('owned desktop approval explains original consumed values and prepares separately from execution',async()=>{const f=await fixture({last:true}),api=ipc(f),before=db.getBatchCheckpoint(f.runId),review=await api.invoke({action:'review'});assert.equal(review.success,true);assert.deepEqual(review.review.memoryContinueStepIds,['optional']);const approved=await api.invoke({action:'accept',fingerprint:review.review.fingerprint});assert.equal(approved.success,true);assert.equal(api.dialogs[0].defaultId,0);assert.match(api.dialogs[0].detail,/๊ณผ๊ฑฐ ๊ณ„์† ์ง„ํ–‰ ์ถœ๋ ฅ: optional/);assert.match(api.dialogs[0].detail,/๋‹น์‹œ ์†Œ๋น„๋œ ์›๋ž˜ ๊ฐ’/);assert.deepEqual(db.getBatchCheckpoint(f.runId).entries,before.entries);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);const paused=await api.invoke({action:'review'});assert.deepEqual(paused.review.memoryContinueStepIds,['optional']);assert.equal(paused.review.canResume,true);engine.executeNode=async()=>{throw Error('desktop replayed child');};assert.equal((await api.invoke({action:'resume',fingerprint:paused.review.fingerprint})).success,true);assert.equal(api.dialogs.length,1);assert.equal(api.sender.listenerCount('destroyed'),0);});
test('rehashing the raw candidate and its next intent does not replace the actual child input evidence',async()=>{const f=await fixture(),row=db.getLoopIterations('looprun-'+f.runId)[0],outputs=JSON.parse(row.step_outputs);outputs.optional._duration='999.99';db.saveLoopIteration({...row,step_outputs:JSON.stringify(outputs)});const c=db.getBatchCheckpoint(f.runId),inputs={optional:outputs.optional},step=require('../../src/db/batch-checkpoint-record').stepsFor(db.getBatchTasks(f.project).find(t=>t.id===f.task.id))[1];c.entries['1:1:0'].inputsHash=hash(inputs);c.entries['1:1:0'].configHash=hash(require('../../src/batch-step-runners').interpolateConfig(step.config,inputs));const status=db.getStorageStatus();assert.ok(status.path.startsWith(home+path.sep));if(status.backend==='sqlite'){const native=new(require('better-sqlite3'))(status.path);try{native.prepare('UPDATE batch_checkpoints SET data_json=? WHERE run_id=?').run(JSON.stringify(c),f.runId);}finally{native.close();}}else{const data=JSON.parse(fs.readFileSync(status.path));data.batch_checkpoints=data.batch_checkpoints.map(r=>r.runId===f.runId?c:r);fs.writeFileSync(status.path,JSON.stringify(data));db.reloadJson();}assert.equal(require('../../src/services/batch-memory-continue-proof').verify(db,f.runId).candidateConsumptionVerified,true);await assert.rejects(prepare(f));assert.equal(db.getBatchCheckpoint(f.runId).recoveries,undefined);assert.equal(db.getWorkflowRuns(f.workflow.id).length,1);});
test('missing historical goal observations after preparation block consumption and permit the original proof to be retried',async()=>{const f=await fixture({last:true}),p=await prepare(f),before=db.getBatchCheckpoint(f.runId),get=db.getBatchLoopObservations;db.getBatchLoopObservations=()=>null;try{assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,false);}finally{db.getBatchLoopObservations=get;}assert.deepEqual(db.getBatchCheckpoint(f.runId),before);assert.equal(db.getBatchRun(f.runId).status,'paused');engine.executeNode=async()=>{throw Error('retry replayed original child');};assert.equal((await batch.resumeBatchRun(f.runId,{fingerprint:p.fingerprint})).success,true);});