From 1848a6c10b83882c1aef824d34132ee8d4ba4a26 Mon Sep 17 00:00:00 2001 From: abaishu0730 Date: Fri, 23 Oct 2026 13:00:34 +0800 Subject: [PATCH] fix: keep BPM reconciliation responsive and task based --- src/modules/bpm/arrival-monitor.cjs | 8 +- src/modules/bpm/scan-store.cjs | 11 ++- src/modules/order-execution/coordinator.cjs | 11 ++- tests/bpm/todo-arrival-identity.test.cjs | 83 +++++++++++++++++++ .../execution-responsiveness.test.cjs | 61 ++++++++++++++ 5 files changed, 165 insertions(+), 9 deletions(-) create mode 100644 tests/bpm/todo-arrival-identity.test.cjs create mode 100644 tests/order-rules/execution-responsiveness.test.cjs diff --git a/src/modules/bpm/arrival-monitor.cjs b/src/modules/bpm/arrival-monitor.cjs index 8a2b2b4..543c5e7 100644 --- a/src/modules/bpm/arrival-monitor.cjs +++ b/src/modules/bpm/arrival-monitor.cjs @@ -4,8 +4,8 @@ const {dayPolicy}=require('../../shared/schedule.cjs'); const {normalizeArrival}=require('./list-client.cjs'); const {BpmSignalRClient}=require('./signalr-client.cjs'); function todoArrival(row){ - if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null||row.revision==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502}); - return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),revision:row.revision,processVersion:row.processVersion||'',recordKey:JSON.stringify([row.instanceId,row.taskId,row.revision])}; + if(row.source!=='todo'||!['portal-v4','portal-v8'].includes(row.portalSource)||row.instanceId==null)throw Object.assign(new Error('真实待办身份不完整。'),{status:502}); + return {...normalizeArrival({taskId:row.taskId,startTime:row.receivedAt,serialNum:row.serialNum,processName:row.processName,activityName:row.nodeName,processInstanceSubject:row.title},'todo:'+row.portalSource),kind:'todo',instanceId:String(row.instanceId),...(row.revision==null?{}:{revision:row.revision}),processVersion:row.processVersion||'',recordKey:String(row.taskId)}; } class BpmArrivalMonitor{ constructor({workspace,manager,scanner,provider,settings,onTodoReconciled,hubClient=new BpmSignalRClient(),clock=()=>Date.now(),debounceMs=750,pollMs=5000,retryMs=[2000,5000,15000,60000],sourceRetryMs=[2000,5000,15000,60000,300000]}){ @@ -16,7 +16,7 @@ class BpmArrivalMonitor{ active(entry){try{return !this.stopped&&this.entries.get(entry.id)===entry&&this.workspace.getConnection(entry.id).status!=='disabled';}catch{return false;}} source(entry,kind){return entry.sources[kind]||=( {status:'pending',failures:0,nextAttempt:0,lastSuccessAt:null,lastFailureAt:null} );} sourceSuccess(entry,kind){if(!entry||!this.active(entry))return;const source=this.source(entry,kind);Object.assign(source,{status:'healthy',failures:0,nextAttempt:0,lastSuccessAt:new Date(this.clock()).toISOString(),message:null});if(['todo','inform'].every(k=>this.source(entry,k).status==='healthy'))entry.lastSyncAt=new Date(this.clock()).toISOString();} - sourceFailure(entry,kind,error){if(!entry||!this.active(entry))return;const source=this.source(entry,kind),delay=this.sourceRetryMs[Math.min(source.failures++,this.sourceRetryMs.length-1)];Object.assign(source,{status:'error',lastFailureAt:new Date(this.clock()).toISOString(),nextAttempt:this.clock()+delay,message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);} + sourceFailure(entry,kind,error){if(!entry||!this.active(entry))return;const source=this.source(entry,kind),delay=this.sourceRetryMs[Math.min(source.failures++,this.sourceRetryMs.length-1)];Object.assign(source,{status:'error',lastFailureAt:new Date(this.clock()).toISOString(),nextAttempt:this.clock()+delay,message:error?.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error?.status===401?'需要恢复BPM登录。':error?.status===403?'没有读取权限。':error?.status===409?'连接忙碌或已暂停。':'读取失败,等待重试。'});entry.lastFailureAt=source.lastFailureAt;entry.dirty.add(kind);} deliveryState(id){return this.scanner.store.deliveries?.summary(id)||{status:'healthy',pending:0};} snapshot(id){const e=this.entries.get(id);if(e)return {status:e.status,lastSignalAt:e.lastSignalAt||null,lastSyncAt:e.lastSyncAt||null,lastFailureAt:e.lastFailureAt||null,nextRetryAt:Number.isFinite(e.nextRetry)?new Date(e.nextRetry).toISOString():null,nextReconcileAt:new Date(e.nextReconcile).toISOString(),delivery:this.deliveryState(id),sources:Object.fromEntries(['todo','inform'].map(kind=>{const s=this.source(e,kind);return [kind,{status:s.status,lastSuccessAt:s.lastSuccessAt,lastFailureAt:s.lastFailureAt,retryAt:s.nextAttempt?new Date(s.nextAttempt).toISOString():null,message:s.message||null}];}))}; let status='removed';try{status=this.workspace.getConnection(id).status==='disabled'||!this.scanner.store.config().enabled?'paused':'waiting';}catch{}return {status,lastSignalAt:null,lastSyncAt:null,nextReconcileAt:null,sources:{},delivery:this.deliveryState(id)}; @@ -85,7 +85,7 @@ class BpmArrivalMonitor{ // Delivery has its own persisted outcome; a callback cannot rewrite a committed read. if(delivery)await this.publishPending(id,canCommit).catch(()=>{}); return {...result,runId}; - }catch(error){this.scanner.store.fail(runId,error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;} + }catch(error){this.scanner.store.fail(runId,error.code==='TODO_IDENTITY_AMBIGUOUS'?error.message:error.status===401?'需要恢复BPM登录。':error.status===409?'连接忙碌或已暂停。':'待办对账失败,请稍后重试。');this.sourceFailure(entry,'todo',error);throw error;} }).finally(()=>this.todoPending.delete(id));this.todoPending.set(id,promise);return {runId,promise}; } publishPending(id,canDeliver=()=>true){ diff --git a/src/modules/bpm/scan-store.cjs b/src/modules/bpm/scan-store.cjs index 68f4855..fe93411 100644 --- a/src/modules/bpm/scan-store.cjs +++ b/src/modules/bpm/scan-store.cjs @@ -27,7 +27,16 @@ class BpmScanStore{ let added=0;const now=new Date().toISOString(); const insert=this.db.prepare('INSERT OR IGNORE INTO arrivals VALUES(?,?,?,?,?,?,?)');const update=this.db.prepare('UPDATE arrivals SET day=?,value=?,last_seen=? WHERE connection_id=? AND source=? AND task_id=?'); const prior=this.db.prepare('SELECT value FROM arrivals WHERE connection_id=? AND source=? AND task_id=?'); - for(const row of rows){if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。');const key=row.recordKey||row.taskId,old=prior.get(connectionId,row.source,key),snapshot=old?JSON.parse(old.value).origin:null,saved={...row};delete saved.origin;if(snapshot||connection)saved.origin=snapshot||{id:connectionId,name:connection.name,owner:connection.owner,identity:connection.identity||''};const value=JSON.stringify(saved);added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key);} + // Older todo rows used an instance/task/revision storage key. Reuse their + // original key so an absent or newly reported revision cannot duplicate a task. + const priorTodo=this.db.prepare("SELECT task_id AS storageKey,value FROM arrivals WHERE connection_id=? AND source=? AND CAST(json_extract(value,'$.taskId') AS TEXT)=? LIMIT 2"); + for(const row of rows){ + if(!row.arrivalDay||!row.taskId||!row.source)throw invalid('流程记录无效。'); + const todo=row.source.startsWith('todo:'),matches=todo?priorTodo.all(connectionId,row.source,String(row.taskId)):[]; + if(matches.length>1)throw Object.assign(new Error('此待办对应多条旧到达记录,请人工核验任务身份后再同步。'),{status:409,code:'TODO_IDENTITY_AMBIGUOUS'}); + const existing=matches[0],key=todo?(existing?.storageKey||String(row.taskId)):(row.recordKey||row.taskId),old=existing||prior.get(connectionId,row.source,key),snapshot=old?JSON.parse(old.value).origin:null,saved={...row}; + delete saved.origin;if(snapshot||connection)saved.origin=snapshot||{id:connectionId,name:connection.name,owner:connection.owner,identity:connection.identity||''};const value=JSON.stringify(saved);added+=Number(insert.run(connectionId,row.source,key,row.arrivalDay,value,now,now).changes);update.run(row.arrivalDay,value,now,connectionId,row.source,key); + } if(delivery)this.deliveries.enqueue(delivery); this.db.prepare('UPDATE runs SET status=?,finished_at=?,seen=?,added=?,message=? WHERE id=? AND status=?').run('success',now,rows.length,added,'',id,'running');this.prune();return {seen:rows.length,added}; });} diff --git a/src/modules/order-execution/coordinator.cjs b/src/modules/order-execution/coordinator.cjs index 1a3848e..a9b7463 100644 --- a/src/modules/order-execution/coordinator.cjs +++ b/src/modules/order-execution/coordinator.cjs @@ -167,6 +167,7 @@ class OrderExecutionCoordinator{ const rows=trustedRows===undefined?await this.provider.scan(connection,principal):clone(trustedRows);if(!Array.isArray(rows))throw Error('待办提供器返回格式无效。'); if(trustedRows===undefined&&eligibility.state(this.store))eligibility.recordCurrentScan(this.store,{connectionId:connection.id,rows,startedAt:this.query.startedAt,finishedAt:this.now()}); let considered=0;const observed=new Set(),discovered=[]; + const window=this.store.snapshot().window; // Commit the entire discovery set before probes, captures, exceptions or archives yield. this.store.transaction(()=>{ for(const raw of rows){ @@ -186,7 +187,6 @@ class OrderExecutionCoordinator{ const rules=this.store.all('rules').map(r=>this.store.executionRule(r)||(!testing?r.draft:null)).filter(rule=>rule&&matchesScope(rule,row)); if(!rules.length&&!task)continue; const id=task?.id||taskIdentity.taskIdentity(row); - const window=this.store.snapshot().window; const baseline=this.store.settings().processingSince; const received=Date.parse(eligibleAt); // Pre-activation backlog requires explicit admission. Eligible missed-window work is @@ -251,7 +251,6 @@ class OrderExecutionCoordinator{ this.reconcileArchive(task); const order=task.orderId&&this.store.get('orders',task.orderId); if(!needsRuntimeCheck(order))continue; - const window=this.store.snapshot().window; if(window&&!reserved(order)&&Date.parse(eligibility.orderTime(this.store,order))hint.connectionId===connection.id&&hint.status==='pending') .sort((a,b)=>Date.parse(a.startedAt)-Date.parse(b.startedAt)); for(const hint of pending){ - if(!this.store.settings().processingEnabled)return; + if(this.stopped||!this.store.settings().processingEnabled)return; await this.consumeDiscovery(hint,connection); + // Trusted scans may finish entirely in microtasks. Let health checks and + // pause/stop requests run before consuming the next durable delivery. + await new Promise(resolve=>setImmediate(resolve)); + if(this.stopped||!this.store.settings().processingEnabled)return; } const last=this.store.get('execution-scans',connection.id); const window=this.store.snapshot().window; diff --git a/tests/bpm/todo-arrival-identity.test.cjs b/tests/bpm/todo-arrival-identity.test.cjs new file mode 100644 index 0000000..18789c8 --- /dev/null +++ b/tests/bpm/todo-arrival-identity.test.cjs @@ -0,0 +1,83 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),os=require('node:os'),path=require('node:path'); +const {normalizeTodo}=require('../../src/modules/bpm/todo-client.cjs'); +const {normalizeArrival}=require('../../src/modules/bpm/list-client.cjs'); +const {BpmArrivalMonitor,todoArrival}=require('../../src/modules/bpm/arrival-monitor.cjs'); +const {BpmScanStore}=require('../../src/modules/bpm/scan-store.cjs'); +const {BpmScanner}=require('../../src/modules/bpm/scanner.cjs'); +const raw={taskId:'T1',processInstanceId:'I1',processName:'测试订单评审',activityName:'订单专员',processVersion:'2',serialNum:'TEST-1',processInstanceSubject:'测试订单',startTime:'2026-10-23T09:00:00'}; + +test('native todo arrivals accept absent business revision without inventing zero and retain a reported zero',()=>{ + for(const portalSource of ['portal-v4','portal-v8']){ + for(const value of [undefined,null]){ + const arrival=todoArrival(normalizeTodo({...raw,revision:value},portalSource)); + assert.equal(arrival.taskId,'T1');assert.equal(arrival.source,'todo:'+portalSource); + assert.equal(Object.hasOwn(arrival,'revision'),false); + assert.equal(arrival.arrivalDay,'2026-10-23'); + } + const zero=todoArrival(normalizeTodo({...raw,revision:0},portalSource)); + assert.equal(zero.revision,0); + assert.equal(todoArrival(normalizeTodo({...raw,revision:'2'},portalSource)).revision,'2'); + } + for(const patch of [{source:'history'},{portalSource:'untrusted'},{instanceId:null},{taskId:''},{receivedAt:'invalid'}])assert.throws(()=>todoArrival({...normalizeTodo(raw,'portal-v4'),...patch}),error=>error.status===502); +}); + +function fixture(t){ + const dir=fs.mkdtempSync(path.join(os.tmpdir(),'todo-arrival-identity-')); + let store=new BpmScanStore(dir),monitor,scanner,rows=[normalizeTodo(raw,'portal-v4')],calls=0; + const connection={id:'c1',name:'原始连接',owner:'admin',status:'connected'},principal={user:{username:'admin',role:'admin'},sessionId:'test'}; + const workspace={getConnection:()=>({...connection}),snapshot:()=>({connections:[{...connection}],calendar:{overrides:[]}})}; + const manager={sessions:new Map(),epoch:()=>0,ensure:async()=>({status:'connected'}),authorize(){},run:async(id,work)=>work(),vault:()=>({read:async()=>({storageState:{cookies:[],origins:[]}})}),scanArrivals:async()=>[]}; + const hints=[]; + function open(){scanner=new BpmScanner({store,workspace,manager,settings:()=>({schedule:{weekends:true}})});monitor=new BpmArrivalMonitor({workspace,manager,scanner,provider:{scan:async()=>{calls++;return structuredClone(rows);}},onTodoReconciled:payload=>hints.push(payload),settings:()=>({schedule:{weekends:true}}),hubClient:{connect:async()=>({stop:async()=>{}})},clock:()=>Date.parse('2026-10-23T02:00:00Z'),debounceMs:1});} + open(); + t.after(async()=>{await monitor.stop();await scanner.stop();store.close();fs.rmSync(dir,{recursive:true,force:true});}); + return {connection,principal,hints,get store(){return store;},get monitor(){return monitor;},get calls(){return calls;},setRows:value=>rows=value,async restart(){await monitor.stop();await scanner.stop();store.close();store=new BpmScanStore(dir);open();}}; +} +async function reconciled(f){await f.monitor.tick();await f.monitor.entries.get('c1').connecting;const deadline=Date.now()+2500;while(f.monitor.snapshot('c1').sources.todo.status!=='healthy'||f.monitor.entries.get('c1').sync){if(Date.now()>deadline)assert.fail('todo read did not reach a committed healthy state');await new Promise(resolve=>setTimeout(resolve,5));}} + +test('monitor commits native missing-revision todos once and later reported revisions update the same persisted task',async t=>{ + const f=fixture(t);await reconciled(f); + assert.equal(f.calls,1);assert.equal(f.store.status().runs.find(run=>run.kind==='todo').status,'success'); + const first=f.store.list({kind:'todo'}).groups[0].items[0];assert.equal(Object.hasOwn(first,'revision'),false); + assert.equal(f.hints.length,1);assert.equal(Object.hasOwn(f.hints[0].rows[0],'revision'),false); + const firstRecord=f.store.ledger({scope:'all',kind:'todo',business:'all',page:1,pageSize:25},[],[]).items[0].recordId; + f.setRows([normalizeTodo({...raw,revision:0},'portal-v4')]); + assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,0); + assert.equal(f.store.list({kind:'todo'}).total,1);assert.equal(f.store.list({kind:'todo'}).groups[0].items[0].revision,0); + await f.restart();f.setRows([normalizeTodo({...raw,revision:'2'},'portal-v4')]); + assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,0); + assert.equal(f.store.list({kind:'todo'}).total,1); + const current=f.store.ledger({scope:'all',kind:'todo',business:'all',page:1,pageSize:25},[],[]).items[0];assert.equal(current.recordId,firstRecord);assert.equal(current.revision,'2'); + f.setRows([normalizeTodo({...raw,revision:'2'},'portal-v8'),normalizeTodo({...raw,taskId:'T2'},'portal-v4')]); + assert.equal((await f.monitor.startTodoScan('c1',f.principal).promise).added,2);assert.equal(f.store.list({kind:'todo'}).total,3); + assert.equal(f.calls,4);assert.equal(f.store.status().runs.some(run=>run.status==='error'),false); +}); + +test('monitor reuses legacy todo storage identity without duplicating the task or rewriting unrelated inform evidence',async t=>{ + const f=fixture(t),legacy={...normalizeArrival(raw,'todo:portal-v4'),kind:'todo',instanceId:'I1',revision:7,processVersion:'2',recordKey:'["I1","T1",7]'},inform=normalizeArrival(raw,'portal-v4'); + f.store.complete(f.store.begin('c1','admin','todo'),'c1',[legacy],f.connection); + // Seed the pre-fix persisted key independently of the current writer. + f.store.db.prepare("UPDATE arrivals SET task_id=? WHERE source='todo:portal-v4'").run('["I1","T1",7]'); + f.store.complete(f.store.begin('c1','admin'),'c1',[inform],f.connection); + const before=f.store.db.prepare('SELECT * FROM arrivals ORDER BY source').all();await f.restart();f.connection.name='连接已改名'; + const result=await f.monitor.startTodoScan('c1',f.principal).promise; + assert.equal(result.added,0);assert.equal(f.store.list({kind:'todo'}).total,1);assert.equal(f.store.list().total,1); + const todo=f.store.db.prepare("SELECT * FROM arrivals WHERE source='todo:portal-v4'").get(),oldTodo=before.find(row=>row.source==='todo:portal-v4'); + assert.equal(todo.task_id,'["I1","T1",7]');assert.equal(todo.first_seen,oldTodo.first_seen); + assert.deepEqual(JSON.parse(todo.value).origin,JSON.parse(oldTodo.value).origin);assert.equal(Object.hasOwn(JSON.parse(todo.value),'revision'),false); + assert.deepEqual(f.store.db.prepare("SELECT * FROM arrivals WHERE source='portal-v4'").get(),before.find(row=>row.source==='portal-v4')); +}); + +test('ambiguous legacy task identities require manual review and roll back every row and delivery in the read',async t=>{ + const f=fixture(t),arrival={...normalizeArrival(raw,'todo:portal-v4'),kind:'todo',instanceId:'I1',processVersion:'2'}; + const insert=f.store.db.prepare('INSERT INTO arrivals VALUES(?,?,?,?,?,?,?)'); + for(const revision of [7,8])insert.run('c1','todo:portal-v4',JSON.stringify(['I1','T1',revision]),'2026-10-23',JSON.stringify({...arrival,revision,origin:{id:'c1',name:'旧连接',owner:'admin'}}),'2026-10-23T01:00:00Z','2026-10-23T01:00:00Z'); + const before=f.store.db.prepare('SELECT * FROM arrivals ORDER BY task_id').all(); + // A valid earlier row must not survive when a later row is ambiguous. + f.setRows([normalizeTodo({...raw,taskId:'T2'},'portal-v4'),normalizeTodo(raw,'portal-v4')]); + await assert.rejects(f.monitor.startTodoScan('c1',f.principal).promise,error=>error.status===409&&error.code==='TODO_IDENTITY_AMBIGUOUS'&&/人工核验/.test(error.message)); + assert.deepEqual(f.store.db.prepare('SELECT * FROM arrivals ORDER BY task_id').all(),before); + assert.equal(f.store.deliveries.summary('c1').pending,0);assert.deepEqual(f.hints,[]); + const run=f.store.status().runs[0];assert.equal(run.status,'error');assert.match(run.message,/人工核验/); +}); diff --git a/tests/order-rules/execution-responsiveness.test.cjs b/tests/order-rules/execution-responsiveness.test.cjs new file mode 100644 index 0000000..a8376b9 --- /dev/null +++ b/tests/order-rules/execution-responsiveness.test.cjs @@ -0,0 +1,61 @@ +'use strict'; +const test=require('node:test'),assert=require('node:assert/strict'); +const {OrderExecutionCoordinator}=require('../../src/modules/order-execution/coordinator.cjs'); +const principal={user:{username:'admin',role:'admin'},sessionId:'responsiveness-test'}; +function fixture(t){ + const records=new Map(),connection={id:'c1',owner:'admin',status:'connected'}; + let processingEnabled=true,transactionDepth=0,snapshots=0; + const store={ + all:kind=>[...(records.get(kind)?.values()||[])].map(item=>structuredClone(item)), + get:(kind,id)=>structuredClone(records.get(kind)?.get(id)||null), + put(kind,item){if(!records.has(kind))records.set(kind,new Map());records.get(kind).set(item.id,structuredClone(item));return item;}, + transaction(work){transactionDepth++;try{return work();}finally{transactionDepth--; }}, + settings:()=>({processingEnabled,processingSince:null}), + snapshot(){snapshots++;return {window:{start:'2026-10-23T00:00:00Z',end:'2026-10-23T03:00:00Z',available:false}};}, + executionRule:record=>record?.draft, + fields:()=>({samples:[],processes:[]}),discoveryBlockers:()=>[], + }; + const provider={capabilities:async()=>({liveTodo:true,pdfExport:true}),scan:async()=>{throw Error('Unexpected live scan');},capture:async()=>{throw Error('Synthetic capture unavailable');}}; + const execution=new OrderExecutionCoordinator({store,systemPrincipal:principal,clock:()=>new Date('2026-10-23T02:00:00Z'), + workspace:{getConnection:()=>connection,snapshot:()=>({connections:[connection]})},provider, + archive:{capabilities:async()=>({automaticArchive:true,pdfExport:true})},onException:async()=>{}, + }); + t.after(()=>execution.stop()); + return {store,execution,provider,connection,setProcessing:value=>{processingEnabled=value;},get snapshots(){return snapshots;},get inTransaction(){return transactionDepth!==0;}}; +} +test('one discovery set resolves its window once and registers every row before external work',async t=>{ + const f=fixture(t),rows=Array.from({length:17},(_,index)=>({source:'todo',portalSource:'portal-v4',taskId:String(index+1),instanceId:'i'+index,processName:'Synthetic process',nodeName:'Notification',receivedAt:'2026-10-23T01:00:00Z',title:'订单号:TEST-'+index})); + f.store.put('rules',{id:'r',draft:{id:'r',categoryId:'r',processNames:['Synthetic process'],scopes:[{processName:'Synthetic process',nodeName:'Notification'}]}}); + let firstProbe; + f.provider.capabilities=async()=>{ + firstProbe||={snapshots:f.snapshots,inTransaction:f.inTransaction,tasks:f.store.all('execution-tasks'),targetCount:f.store.get('execution-scans','c1').targetCount}; + return {liveTodo:true,pdfExport:true}; + }; + await f.execution.scan({connectionId:'c1',idempotencyKey:'complete-discovery'},principal,{rows}); + assert.equal(firstProbe.snapshots,1,'the complete discovery set must use one window snapshot'); + assert.equal(firstProbe.inTransaction,false,'external work must start after the discovery transaction'); + assert.equal(firstProbe.tasks.length,17,'all task rows must be committed before any probe or capture'); + assert.equal(firstProbe.targetCount,17);assert.equal(f.store.all('execution-tasks').length,17); +}); +for(const action of ['pause','stop'])test(`historical delivery drain yields before the second hint so an event-loop ${action} preserves pending work`,async t=>{ + const f=fixture(t); + for(let index=0;index<20;index++)f.execution.notifyDiscovery({connectionId:'c1',runId:'run-'+index,rows:[],startedAt:new Date(Date.parse('2026-10-23T01:00:00Z')+index*1000).toISOString(),finishedAt:new Date(Date.parse('2026-10-23T01:00:01Z')+index*1000).toISOString()}); + let completedAtSignal; + const signal=new Promise(resolve=>setImmediate(()=>{ + completedAtSignal=f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length; + if(action==='pause')f.setProcessing(false);else void f.execution.stop(); + resolve(); + })); + await f.execution.background();await signal; + assert.equal(completedAtSignal,1,'an independent event-loop callback must run before consuming a second historical hint'); + const hints=f.store.all('execution-discovery-runs'); + assert.equal(hints.filter(item=>item.status==='complete').length,1); + assert.equal(hints.filter(item=>item.status==='pending').length,19); + assert.deepEqual(hints.filter(item=>item.status==='pending').map(item=>item.runId),Array.from({length:19},(_,index)=>'run-'+(index+1))); + assert.equal(f.store.get('execution-discoveries','c1').status,'pending'); + if(action==='pause'){ + f.setProcessing(true);await f.execution.background(); + assert.equal(f.store.all('execution-discovery-runs').filter(item=>item.status==='complete').length,20); + assert.equal(f.store.get('execution-discoveries','c1').status,'complete'); + } +});