سامانه صدور فاکتور و حسابداری
Mirrored from https://github.com/davoodmehraban89/Factor-easy.git
Synced Dec 3, 22:00 UTC
fix: bound reconciliation to one scoped read and distinguish read-back result
davoodmehraban89 committed
Nov 24, 2026 at 11:25 UTC
b3e8cbfdff7fa7605ef8a877a54553a40299d676
4 files changed
+32
-22
PROJECT_STATE.md
+2
@@ -705,3 +705,5 @@ Next action: run and inspect Quality on the latest PR212 head. If any browser te
705
### 2026-11-24 — FIN-B02 candidate checkpoint
706
- B02 branch stacked on PR252, original A01 browser regressions traced. Implemented bounded organization-scoped upsert CAS recovery: exact immutable request, complete target preimage/postimage checks, no rebase, one replay only when all preimages unchanged, state-equivalent readback when all postimages/version match, no automatic delete recovery, divergence/read error/stale context remains paused. Read-back is not an actor/audit receipt. Newer edits remain pending for subsequent normal CAS. No database changes.
707
- Existing operational settings test now hydrates through real pullAll from seeded synthetic server, no dirty-state bypass; original persistence/audit/permission assertions retained. Existing transient invoice browser test uses realistic SDK transport error, preserves automatic exact recovery expectation. Added focused Node tests of no duplicate writes, lost ACK, divergent/partial/failed read, wrong tenant, delete, retry bound, newer edit and stale tenant. Exact candidate CI pending; no local test execution claimed. Explicit resolution of divergent and deletion cases remains open. Next inspect A01/B01/B02 CI, preserve previous REDs and plan #229 after dependency gate.
708
+
709
+- B02 safety review: use one scoped bounded read-back statement for the entire upsert batch (max 50 requests, 10-second read deadline, fail closed on truncated/duplicate rows); distinguish read-back equivalence badge from direct acknowledged save. Browser mock respects org/ID filters instead of unfiltered pagination. Exact CI pending. No claim of transaction/audit identity.
js/sync.js
+23
-17
@@ -55,11 +55,11 @@ function keyOfRecord(coll,item){return coll==='settings'?'main':String(item&&ite
55
function stripOwner(item){const c=Object.assign({},item);delete c.ownerUserId;delete c._serverVersion;delete c.accountingPostingPending;delete c.accountingPostingPendingAt;return c;}
56
function setSyncBadge(state){
57
const el=document.getElementById('sync-badge');if(!el)return;
58
- const map={saved:['✔ ذخیره شد','#059669'],saving:['⏳ در حال ذخیره…','#d97706'],error:['⚠️ ذخیره نشد؛ تلاش مجدد…','#dc2626'],conflict:['⚠️ ذخیره تأیید نشد؛ تغییرات محفوظ است','#dc2626']};
58
+ const map={saved:['✔ ذخیره شد','#059669'],saving:['⏳ در حال ذخیره…','#d97706'],error:['⚠️ ذخیره نشد؛ تلاش مجدد…','#dc2626'],conflict:['⚠️ ذخیره تأیید نشد؛ تغییرات محفوظ است','#dc2626'],reconciled:['✔ تطابق داده با سرور تأیید شد','#059669']};
59
const m=map[state];if(!m)return;
60
el.textContent=m[0];el.style.background=m[1];el.style.display='block';
61
clearTimeout(setSyncBadge._t);
62
- if(state==='saved')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
62
+ if(state==='saved'||state==='reconciled')setSyncBadge._t=setTimeout(()=>{el.style.display='none';},2000);
63
}
64
async function pullAll({signal}={}){
65
const capture=finoraCaptureRead(),uid=capture.context.uid;
@@ -126,33 +126,38 @@ function finoraComparableRecord(data,id){
126
if(!data||typeof data!=='object'||Array.isArray(data))throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
127
return finoraCanonicalJson(stripOwner({...data,id}));
128
}
129
-async function finoraReadRecoveryRow(context,request,stillCurrent){
129
+async function finoraReadRecoveryRows(context,requests,stillCurrent){
130
const controller=new AbortController(),timer=setTimeout(()=>controller.abort(),10000);
131
try{
132
- let query=sb.from('records').select('collection,id,data,version,organization_id').eq('organization_id',context.org).eq('collection',request.collection).eq('id',request.id).range(0,1);
132
+ const ids=[...new Set(requests.map(r=>r.id))];
133
+ // One bounded statement, not a series of individually timed observations.
134
+ let query=sb.from('records').select('collection,id,data,version,organization_id').eq('organization_id',context.org).in('id',ids).range(0,999);
135
if(typeof query.abortSignal==='function')query=query.abortSignal(controller.signal);
136
const {data,error}=await finoraAbortableRead(query,controller.signal);
135
- if(controller.signal.aborted||!stillCurrent()||error||!Array.isArray(data))throw finoraSyncIssue('FINORA_RECOVERY_READ_FAILED');
136
- const matches=data.filter(r=>r.collection===request.collection&&r.id===request.id);
137
- if(matches.length>1||matches.some(r=>r.organization_id!=null&&r.organization_id!==context.org))throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
138
- if(!matches.length)return null;
139
- const row=matches[0];
140
- if(!Number.isSafeInteger(row.version)||row.version<1)throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
141
- return row;
137
+ if(controller.signal.aborted||!stillCurrent()||error||!Array.isArray(data)||data.length>=1000)throw finoraSyncIssue('FINORA_RECOVERY_READ_FAILED');
138
+ const wanted=new Set(requests.map(r=>r.collection+'|'+r.id)),rows=new Map();
139
+ for(const row of data){
140
+ const key=row.collection+'|'+row.id;
141
+ if(!wanted.has(key))continue;
142
+ if(rows.has(key)||(row.organization_id!=null&&row.organization_id!==context.org)||!Number.isSafeInteger(row.version)||row.version<1)throw finoraSyncIssue('FINORA_RECOVERY_ROW_INVALID');
143
+ rows.set(key,row);
144
+ }
145
+ return rows;
146
}finally{clearTimeout(timer);}
147
}
148
async function finoraSendVersionedBatch(args,up,context,snapshotSerial){
149
const stillCurrent=()=>finoraSyncContextMatches(context)&&snapshotSerial===finoraSnapshotSerial&&finoraHydratedTenant===finoraTenantKey(context);
150
const send=async()=>{try{return await sb.rpc('finora_sync_records_v2',JSON.parse(JSON.stringify(args)));}catch(error){return {error};}};
151
const result=await send();
148
- if(!result?.error||!finoraSyncTransportUnknown(result.error)||!stillCurrent()||!context.org||args.p_deletes.length||!up.length)return result;
152
+ if(!result?.error||!finoraSyncTransportUnknown(result.error)||!stillCurrent()||!context.org||args.p_deletes.length||!up.length||up.length>50)return result;
153
try{
154
// Keep the immutable request, original CAS revisions and base payloads.
155
// Read-back may establish state equivalence, never an audit/actor receipt.
156
+ const rows=await finoraReadRecoveryRows(context,args.p_upserts,stillCurrent);
157
let unchanged=true,applied=true;
158
for(let i=0;i<up.length;i++){
159
if(!stillCurrent())throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
155
- const r=up[i],request=args.p_upserts[i],row=await finoraReadRecoveryRow(context,request,stillCurrent);
160
+ const r=up[i],request=args.p_upserts[i],row=rows.get(r.key);
161
const version=row?.version??0,actual=row?finoraComparableRecord(row.data,request.id):null;
162
const before=syncSnap.get(r.key);
163
const beforeComparable=before===undefined?null:finoraComparableRecord(JSON.parse(before),request.id);
@@ -161,7 +166,7 @@ async function finoraSendVersionedBatch(args,up,context,snapshotSerial){
166
applied=applied&&version===request.expected_version+1&&actual===desired;
167
}
168
if(!stillCurrent())throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
164
- if(applied)return {data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:[]},error:null};
169
+ if(applied)return {data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:[]},error:null,reconciled:true};
170
if(unchanged)return await send(); // One exact CAS replay, never a new revision/ID.
171
return {error:finoraSyncIssue('FINORA_RECOVERY_DIVERGENT')};
172
}catch(error){return {error};}
@@ -174,7 +179,7 @@ async function runSync(){
179
const context=finoraSyncContext(),snapshotSerial=finoraSnapshotSerial;
180
try{
181
if(finoraHydratedTenant!==finoraTenantKey(context))throw finoraSyncIssue('FINORA_SYNC_SNAPSHOT_REQUIRED');
177
- let guardLoops=0;
182
+ let guardLoops=0,reconciled=false;
183
do{
184
if(!finoraSyncContextMatches(context)||snapshotSerial!==finoraSnapshotSerial)throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
185
syncAgain=false;
@@ -191,7 +196,7 @@ async function runSync(){
196
p_deletes:deletes,
197
p_organization_id:context.org
198
};
194
- const {data,error}=await finoraSendVersionedBatch(args,up,context,snapshotSerial);
199
+ const {data,error,reconciled:readBack}=await finoraSendVersionedBatch(args,up,context,snapshotSerial);
200
if(!finoraSyncContextMatches(context)||snapshotSerial!==finoraSnapshotSerial)throw finoraSyncIssue('FINORA_SYNC_CONTEXT_CHANGED');
201
if(error)throw error;
202
if(!data||!Array.isArray(data.upserts)||!Array.isArray(data.deletes))throw finoraSyncIssue('FINORA_SYNC_ACK_INVALID');
@@ -220,12 +225,13 @@ async function runSync(){
225
deletes.forEach(r=>{
226
const key=r.collection+'|'+r.id;syncSnap.delete(key);syncVersionSnap.delete(key);
227
});
228
+ reconciled=reconciled||readBack===true;
229
syncFailCount=0;
230
guardLoops++;
231
}while(guardLoops<5);
232
const d=computeDiff();
233
syncPending=(d.up.length>0||d.del.length>0);
228
- if(syncPending){scheduleSync(500);}else{setSyncBadge('saved');}
234
+ if(syncPending){scheduleSync(500);}else{setSyncBadge(reconciled?'reconciled':'saved');}
235
}catch(err){
236
// The old tenant's completion must not alter the new tenant's status or retry queue.
237
if(finoraSyncContextMatches(context)){console.error('sync error',err);await handleSyncError(err);}
scripts/pending-sync-preservation.test.mjs
+1
-1
@@ -21,7 +21,7 @@ async function harness(organization=true){
21
finoraAbortableRead:async q=>q,finoraOrganizationRead:async q=>q,alert:x=>alerts.push(x),
22
canWrite:()=>true,requireWrite:()=>true,refreshAllSurfaces(){},
23
localStorage:{setItem(_k,v){c.selectedOrg=v;}},fetchCurrentUser:async(_u,options)=>({...c.currentUser,organizationId:options?.organizationId||c.selectedOrg}),
24
- sb:{auth:{getUser:async()=>({data:{user:{id:'U1'}}})},from:()=>({select(){return this},eq(){return this},order(){return this},range(){return this},then(a,b){return read().then(a,b)}}),
24
+ sb:{auth:{getUser:async()=>({data:{user:{id:'U1'}}})},from:()=>({select(){return this},eq(){return this},in(){return this},order(){return this},range(){return this},then(a,b){return read().then(a,b)}}),
25
rpc:async(name,args)=>{requests.push({name,args});return {data:{upserts:args.p_upserts.map(r=>({collection:r.collection,id:r.id,version:r.expected_version+1})),deletes:args.p_deletes.map(({collection,id})=>({collection,id}))},error:null};}}
26
};
27
vm.createContext(c);vm.runInContext(syncSource,c);if(organization)vm.runInContext(orgReader+'\n'+switcher,c);
scripts/phase0-invoice-persistence.spec.js
+6
-4
@@ -69,11 +69,13 @@ async function authenticatedMockBrowser(page,companyId='QA_CO',url=BASE){
69
return Promise.resolve({data:allowed?[{id:'QA_F0_MEMBER',organization_id:'QA_ORG',status:'active'}]:[],error:null}).then(resolve,reject);
70
}
71
}}}
72
- : {select:()=>({
73
- eq(){return this;},
72
+ : {select:()=>{const filters={},sets={};return {
73
+ eq(field,value){filters[field]=value;return this;},
74
+ in(field,values){sets[field]=values;return this;},
75
order(){return this;},
75
- async range(from,to){const rows=(await window.qaF0Read()).filter(r=>r.collection).sort((a,b)=>a.collection.localeCompare(b.collection)||a.id.localeCompare(b.id));return {data:rows.slice(from,to+1),error:null};}
76
- })};
76
+ async range(from,to){const rows=(await window.qaF0Read()).filter(r=>r.collection&&Object.entries(filters).every(([k,v])=>(k==='organization_id'?(r[k]||'QA_ORG'):r[k])===v)&&Object.entries(sets).every(([k,v])=>v.includes(r[k]))).sort((a,b)=>a.collection.localeCompare(b.collection)||a.id.localeCompare(b.id));return {data:rows.slice(from,to+1),error:null};}
77
+ }}};
78
+
79
sb.rpc=async(name,args)=>{
80
if(name!=='finora_sync_records_v2')throw Error('Unexpected RPC '+name);
81
return await window.qaF0Write(args);