@davoodmehraban89 / Factor-easy / commits / 4f9a90c
Fork 0

سامانه صدور فاکتور و حسابداری

test(wp1): prove candidate ATF numbering with two PostgreSQL sessions

davoodmehraban89 committed Nov 22, 2026 at 07:41 UTC 4f9a90c9a955800cd0ed83dc0184a5c2e8343a87
4 files changed +153
.github/workflows/wp1-ledger.yml
+9
@@ -90,6 +90,15 @@ jobs:
90 set +a
91 psql "$DB_URL" -v ON_ERROR_STOP=1 -f supabase/tests/0216_attachment_candidate.sql
92
93 + - name: Prove two-session draft-first attachment candidate concurrency
94 + run: |
95 + set -euo pipefail
96 + supabase status -o env > /tmp/supabase-local.env
97 + set -a
98 + . /tmp/supabase-local.env
99 + set +a
100 + node scripts/wp1-attachment-two-session-e2e.mjs
101 +
102 - name: Verify WP1/WP2 journal RPC functions exist
103 run: |
104 set -euo pipefail
docs/ACCOUNTING_CORE_ROADMAP_V1.md
+2
@@ -439,6 +439,8 @@ This register maps execution stages A/B to the **existing** accounting Phase 6 (
439
440 | FIN-QA-SOURCE-JWT-ATOMIC | اثبات واقعی پیوند تراکنشی منبع از قبل ثبت‌شده، rollback و retry | QA مستقل؛ پذیرش Codex اصلی | PR218 migration `20261117110000` و PR224 CI موفق | در بررسی / در پیاده‌سازی | JWT مثبت فروش، پیوند اتمیک، رقابت دو اتصال، replay با شناسه دیگر، برگشت شمارنده/سند در شکستِ پیوند، CI SHA نهایی | QA successor stacked on PR224 | PR224 `6f16c00b` چهار گیت موفق؛ WP2 روی 3f8e8a9c موفق (44982073582) و Security موفق (44982073480)؛ کنترل audit تکمیلی برای SHA بعدی افزوده شد | بررسی WP2/Quality/WP1/Security؛ بررسی مستقل، بدون merge یا تغییر مالی |
441
442 +| FIN-QA-ATF-CONCURRENCY | اثبات هم‌زمانی شماره عطف دائمی در کاندیدای موجود | QA مستقل؛ یکپارچه‌سازی Codex اصلی | ADR0216، `supabase/candidates/0216_attachment_registry.sql`، WP1 | در بررسی / منتظر CI | دو اتصال واقعی با شناسه مشترک/مستقل، عدم جابه‌جایی شرکت، rollback/tombstone/tenant | QA successor stacked on PR225 | WP1 تک‌نشستی روی PR225 موفق؛ آزمون دو‌نشستی جدید هنوز اجرا نشده | WP1 روی SHA جدید، بازبینی Codex اصلی؛ **فقط کاندیدا، نه محصول** |
443 +
444 **Release boundary:** successful Pages run 43606173842 applies only to `main dab1a45`; no candidate above is `منتشرشده`. Competing PR214/215/217/219 are alternative implementations, not sequential milestones. This worker changes documentation only; Codex main owns integration and release decisions.
445
446
docs/EXECUTION_STATUS.md
+7
@@ -1,5 +1,12 @@
1 # وضعیت اجرای فینورا
2
3 +### ۲۰۲۶-۱۱-۲۲ — FIN-QA-ATF-CONCURRENCY؛ آزمون دو‌اتصالی کاندیدای شماره عطف
4 +- **مرحله B/C قبلی پذیرفته‌شده در تست:** PR225 SHA `9122b8b8da0d0a2e4f8976030a6f7c4ef3bcc91a`: Quality `44982300952`، WP1 `44982300977`، WP2 `44982300960`، Security `44982300947` همگی SUCCESS؛ ۲۵۱/۲۵۱ مرورگر و ۴/۴ تکمیلی، Dependency review skipped. PR225 منتشر/ادغام نشده و Codex اصلی باید مستقل بررسی کند.
5 +- **شکاف مشخص:** `supabase/tests/0216_attachment_candidate.sql` تخصیص شماره عطف، retry، tombstone، حذف منطقی و بازگشت را داخل یک نشست PostgreSQL اثبات می‌کند؛ **رقابت دو نشست واقعی** را جداگانه اثبات نکرده بود.
6 +- **اجرای محدود:** `scripts/wp1-attachment-two-session-e2e.mjs` فایل نامتغیر `supabase/candidates/0216_attachment_registry.sql` را در یک schema تصادفی داخل Supabase محلی بار می‌کند. دو process واقعی `psql` هم‌زمان، retry روی شناسه مشترک، رزرو شناسه‌های متفاوت، immutability شرکت، rollback بی‌اثر در شمارنده، tombstone و مرز شرکت/سازمان را بررسی می‌کنند؛ schema در انتها پاک می‌شود. بدون تغییر SQL migration، RPC محصول، کد مالی، سرویس واقعی یا `main`.
7 +- **وضعیت:** در بررسی تا اجرای WP1 روی SHA نهایی. موفقیت تست **فقط قرارداد کاندیدای allocator** است و به معنی اعمال شماره عطف در تمام اسناد یا تکمیل Issue216 نیست. گیت‌ها و بازبینی Codex اصلی باید جدا دیده شوند.
8 +
9 +
10 > **Stage C checkpoint ۲۰۲۶-۱۱-۲۲:** PR225 `3f8e8a9c`، WP2 `44982073582` موفق با JWT واقعی و تزریق شکست در ثبت پیوند، Security `44982073480` موفق (Dependency review skipped). آزمون صحت actor audit، عدم ثبت audit تکراری، حذف audit در rollback و حفظ فیلدهای تجاری بدون تغییر در کاندیدای بعدی اضافه شده‌اند. **نتایج Quality/WP1 و همهٔ گیت‌ها روی SHA نهایی هنوز باید بررسی شوند.** پذیرش مرحله C و انتشار همچنان مسدود است.
11
12
scripts/wp1-attachment-two-session-e2e.mjs new
+135
@@ -0,0 +1,135 @@
1 +import assert from 'node:assert/strict';
2 +import {readFile} from 'node:fs/promises';
3 +import {spawn} from 'node:child_process';
4 +import {randomUUID} from 'node:crypto';
5 +
6 +// QA ONLY: use two real PostgreSQL sessions against a separate-schema copy
7 +// of the EXISTING ATF candidate; this does not integrate its code into Finora.
8 +const db=process.env.DB_URL,api=process.env.API_URL;
9 +assert.ok(db&&api,'Disposable Supabase CLI DB_URL and API_URL required');
10 +const dbUrl=new URL(db),apiUrl=new URL(api);
11 +const loopback=new Set(['127.0.0.1','localhost','[::1]','::1']);
12 +assert.ok(['postgres:','postgresql:'].includes(dbUrl.protocol)&&
13 + loopback.has(dbUrl.hostname)&&dbUrl.port==='54322'&&
14 + loopback.has(apiUrl.hostname)&&apiUrl.port==='54321',
15 + 'Refusing to run against any non-local Supabase environment');
16 +const schema='finora_qa_atf_'+randomUUID().replaceAll('-','').slice(0,16);
17 +const org=randomUUID(),otherOrg=randomUUID(),actor=randomUUID();
18 +const quote=value=>"'"+String(value).replaceAll("'","''")+"'";
19 +const reserve=(voucher,company='C1',organization=org)=>
20 + 'SELECT '+schema+'.finora_reserve_attachment('+
21 + quote(organization)+','+quote(company)+','+quote(voucher)+');';
22 +function psql(sql,stdoutCallback){
23 + return new Promise((resolve,reject)=>{
24 + const child=spawn('psql',[db,'-X','-q','-A','-t','-v','ON_ERROR_STOP=1','-f','-'],
25 + {stdio:['pipe','pipe','pipe']});
26 + let stdout='',stderr='';
27 + child.stdout.on('data',chunk=>{
28 + stdout+=chunk.toString();
29 + if(stdoutCallback)stdoutCallback(stdout);
30 + });
31 + child.stderr.on('data',chunk=>{stderr+=chunk.toString();});
32 + child.on('error',reject);
33 + child.on('close',code=>resolve({code,stdout:stdout.trim(),stderr:stderr.trim()}));
34 + child.stdin.end(sql+'\n');
35 + });
36 +}
37 +async function execute(sql){
38 + const result=await psql(sql);
39 + assert.equal(result.code,0,'Disposable SQL failed: '+result.stderr.slice(-900));
40 + return result.stdout;
41 +}
42 +async function rejected(sql,error){
43 + const result=await psql(sql);
44 + assert.notEqual(result.code,0,'Illegal ATF operation succeeded');
45 + assert.ok((result.stderr+' '+result.stdout).includes(error),
46 + 'Unexpected rejection: expected '+error+', got '+result.stderr.slice(-700));
47 +}
48 +async function scalar(sql){
49 + const txt=await execute(sql);
50 + const rows=txt.split(/\r?\n/).map(x=>x.trim()).filter(Boolean);
51 + assert.equal(rows.length,1,'Wanted one scalar, received: '+txt);
52 + return rows[0];
53 +}
54 +function transactionNumber(result){
55 + assert.equal(result.code,0,'Transaction failed: '+result.stderr.slice(-800));
56 + const rows=result.stdout.split(/\r?\n/).map(x=>x.trim()).filter(x=>/^\d+$/.test(x));
57 + assert.equal(rows.length,1,'Wrong transaction output: '+result.stdout);
58 + return Number(rows[0]);
59 +}
60 +const delay=ms=>new Promise(resolve=>setTimeout(resolve,ms));
61 +let schemaCreated=false;
62 +try{
63 + await execute('CREATE SCHEMA '+schema+';');
64 + schemaCreated=true;
65 + const candidate=await readFile(new URL('../supabase/candidates/0216_attachment_registry.sql',import.meta.url),'utf8');
66 + assert.match(candidate,/Candidate only: not a deployed migration/);
67 + assert.match(candidate,/CREATE FUNCTION private\.finora_reserve_attachment/);
68 + // Load exact candidate text with schema qualification replaced, no business
69 + // migrations, hosted records or real private registry changes.
70 + await execute(candidate.replaceAll('private.',schema+'.'));
71 +
72 + // Reserve V1, then keep the first session's transaction open. Start retry
73 + // only when the first result has been emitted while its lock is still held.
74 + let signal;
75 + const ready=new Promise(resolve=>{signal=resolve;});
76 + let signaled=false;
77 + const first=psql('BEGIN;\n'+reserve('V1')+'\nSELECT pg_sleep(1.1);\nCOMMIT;',output=>{
78 + if(!signaled&&/^\s*1\s*$/m.test(output)){signaled=true;signal();}
79 + });
80 + assert.equal(await Promise.race([ready.then(()=>true),delay(15000).then(()=>false)]),
81 + true,'Session A did not reserve V1 in time');
82 + let retried=false;
83 + const second=psql('BEGIN;\n'+reserve('V1')+'\nCOMMIT;')
84 + .then(x=>{retried=true;return x;});
85 + await delay(120);
86 + assert.equal(retried,false,'Session B bypassed the in-flight V1 transaction');
87 + const pair=await Promise.all([first,second]);
88 + assert.equal(transactionNumber(pair[0]),1);
89 + assert.equal(transactionNumber(pair[1]),1,'Concurrent retry changed the ATF number');
90 + assert.equal(await scalar('SELECT count(*) FROM '+schema+'.finora_attachment_registry WHERE organization_id='+
91 + quote(org)+" AND voucher_id='V1';"),'1');
92 + assert.equal(await scalar('SELECT last_number FROM '+schema+'.finora_attachment_counters WHERE organization_id='+
93 + quote(org)+" AND company_id='C1';"),'1');
94 +
95 + // Two new voucher identities can contend for the same company counter.
96 + const distinct=await Promise.all([psql(reserve('V2')),psql(reserve('V3'))]);
97 + assert.deepEqual(distinct.map(transactionNumber).sort((a,b)=>a-b),[2,3]);
98 + assert.equal(await scalar('SELECT count(DISTINCT attachment_number) FROM '+
99 + schema+'.finora_attachment_registry WHERE organization_id='+quote(org)+
100 + " AND company_id='C1';"),'3');
101 +
102 + // A voucher identifier is permanently bound to its original company.
103 + await rejected(reserve('V1','C2'),'FINORA_ATTACHMENT_COMPANY_IMMUTABLE');
104 + assert.equal(await scalar('SELECT count(*) FROM '+schema+
105 + '.finora_attachment_registry WHERE organization_id='+quote(org)+
106 + " AND company_id='C2';"),'0');
107 +
108 + // Aborted allocation isn't issued and must not leak the number or row.
109 + await execute('BEGIN;\n'+reserve('ABORTED')+'\nROLLBACK;');
110 + assert.equal(await scalar('SELECT count(*) FROM '+schema+
111 + '.finora_attachment_registry WHERE organization_id='+quote(org)+
112 + " AND voucher_id='ABORTED';"),'0');
113 + assert.equal(await scalar(reserve('V4')),'4');
114 +
115 + // A committed tombstone keeps the number consumed and blocks resurrection.
116 + await execute('SELECT '+schema+'.finora_tombstone_attachment('+
117 + quote(org)+",'C1','V1',"+quote(actor)+'::uuid);');
118 + await rejected(reserve('V1'),'FINORA_ATTACHMENT_DELETED');
119 + assert.equal(await scalar(reserve('V5')),'5');
120 + assert.equal(await scalar('SELECT attachment_number FROM '+schema+
121 + '.finora_attachment_registry WHERE organization_id='+quote(org)+
122 + " AND voucher_id='V1' AND deleted_by="+quote(actor)+'::uuid AND deleted_at IS NOT NULL;'),'1');
123 +
124 + // Identical display sequence numbers may exist in DIFFERENT org/company scopes.
125 + assert.equal(await scalar(reserve('C2_V1','C2')),'1');
126 + assert.equal(await scalar(reserve('V1','C1',otherOrg)),'1');
127 + // UPDATE/DELETE/TRUNCATE and direct privileges are already covered by the
128 + // existing transactional supabase/tests/0216_attachment_candidate.sql.
129 + console.log('FINORA_ATF_TWO_SESSION_CANDIDATE_PASS: two PostgreSQL sessions, in-flight idempotency, unique competing vouchers, immutable company, abort and tombstone, organization/company isolation; candidate only');
130 +}finally{
131 + if(schemaCreated){
132 + const cleaned=await psql('DROP SCHEMA IF EXISTS '+schema+' CASCADE;');
133 + assert.equal(cleaned.code,0,'Disposable QA schema cleanup failed: '+cleaned.stderr.slice(-700));
134 + }
135 +}