سامانه صدور فاکتور و حسابداری
Requests: harden Wave 4 scheduler and outbox delivery boundary (#27)
* State: start Wave 4 scheduler and outbox boundary * Requests: harden scheduler and outbox delivery boundary * Tests: disambiguate Wave 4b replay assertion * State: record Wave 4b CI test repair * Tests: restore Wave 4b DO delimiter and qualify replay ids * Tests: preserve PL/pgSQL dollar quote literally
davoodmehraban89 committed
Oct 2, 2026 at 10:26 UTC
41aff95d11a66c67e2c64df3eac11a122f94dfd7
5 files changed
+338
-3
.github/workflows/quality.yml
+4
@@ -212,6 +212,10 @@ jobs:
212
run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002072000_request_wave4_operational_integrity.sql
213
- name: Execute Wave 4 outbox/SLA/delegation assertions
214
run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave4_operational_integrity.sql
215
+ - name: Apply Wave 4b scheduler and outbox delivery boundary
216
+ run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002073500_request_wave4b_scheduler_outbox_delivery.sql
217
+ - name: Execute Wave 4b scheduler/outbox adversarial assertions
218
+ run: psql -v ON_ERROR_STOP=1 -f supabase/tests/request_wave4b_scheduler_outbox_delivery.sql
219
- name: Apply D4a authorized work queue
220
run: psql -v ON_ERROR_STOP=1 -f supabase/migrations/20261002033000_request_workflow_d4a_work_queue.sql
221
- name: Execute D4a work queue assertions
PROJECT_STATE.md
+5
-3
@@ -14,6 +14,8 @@ This is high-assurance accounting/ERP software. Posted financial history, tenant
14
## Current change ledger
15
| Date | Request / decision | Status | Evidence / next action |
16
|---|---|---|---|
17
+| 2026-10-02 | Wave 4b first disposable-DB run exposed an ambiguous PL/pgSQL test variable in the final replay assertion. | **TEST FIX APPLIED / RETEST PENDING** | Product migration executed through all scheduler/outbox assertions; failure was confined to the final test query where local variable `k` shadowed temp-table column `k`. Renamed/qualified the assertion; no production permission or state-machine rollback. |
18
+| 2026-10-02 | Owner said «ادامه بده» after Wave 4 F-420/F-421/F-422 merge. | **IMPLEMENTED ON BRANCH / CI PENDING** | Added server-clock five-minute scheduler slots, durable run/claim evidence, replay binding, skip-locked overdue claims, stable outbox destination command identity, lease claims, retry/backoff, dead-letter and idempotent authorized replay. D4c destination consumers remain disabled. Production migration is NOT APPLIED pending the schema-change gate. |
19
| 2026-10-02 | Owner supplied environment/connection handoff and directed it to be enforced while continuing work. | **LIVE RECONCILED / ACTIVE OPERATING CONTEXT** | Verified GitHub target `davoodmehraban89/Factor-easy` with admin/read-write access, canonical `main`, and Supabase target `hcsixhqbyuhpshfwqpjx` = Finora / `ACTIVE_HEALTHY`. GitHub + Supabase remain source of truth; Gmail/Notion are optional support only, and Railway/Render are not deployment truth unless a later explicit project decision makes them so. Detected concurrent branch advancement during Wave 4 and refused a non-fast-forward overwrite; re-read the newer head before continuing. |
20
| 2026-10-02 | Wave 4 remediation F-420/F-421/F-422 from canonical audit register. | **IMPLEMENTED ON BRANCH / NOT YET VERIFIED** | F-420 rejects duplicate normalized `onApproved` target/action identities; F-421 binds SLA editor values to logical step keys across reorder/remove/key-edit; F-422 adds actor-scoped delegation idempotency, explicit overlap rejection and revoke retry audit dedupe. Disposable-DB + Real-DOM gates added. CI/merge/production remain NOT VERIFIED at this checkpoint. |
21
| 2026-10-02 | Owner supplied the current remediation/audit package plus manual GitHub QA workflow and directed continuation of both roadmap execution and defect remediation. | **F-412 + WAVE 3 F-415/F-416 VERIFIED / PRODUCTION RECONCILED** | PR #23 merged as `d13498f3af03f544c05168727b440f053de1d733`. Main Quality `36973781026` SUCCESS including disposable D1 DB adversarial tests; Security `36973781055` SUCCESS (Release/QA safety + CodeQL; PR Dependency Review remains externally blocked by disabled Dependency Graph); Release gate `36973927530` SUCCESS; gated Pages `36973959986` SUCCESS. Production migrations `20261002063121 request_wave2_duplicate_code_guard` and `20261002063123 request_wave3_decision_idempotency` applied. Read-only production reconciliation: duplicate legacy code groups=0; replay actor binding, reauthorization and immutable event-outcome reconstruction are present. Next: Wave 4 F-420/F-421/F-422; D4c consumers remain disabled. |
@@ -65,9 +67,9 @@ Automatic background scheduling for SLA scans; delivery/dispatch consumers for D
67
The connected Supabase tool now exposes the owner-specified production target `hcsixhqbyuhpshfwqpjx` (`Finora`, `ACTIVE_HEALTHY`, PostgreSQL 17.6.1). Live migration history includes the C8/D1/D2/D3 and Wave 1 request migrations through two recorded `request_wave1_legacy_transition_guard` applications. Read-only production inspection confirmed the current private legacy transition implementation authorizes tenant/module/capability before replay, rejects D3 step-runtime bypass, binds replay to actor+action, and the public wrapper is `SECURITY INVOKER`. No production DDL was required for this reconciliation.
68
69
## Exact next executable work
68
-1. Execute Wave 4 remediation F-420/F-421/F-422: explicit outbox action identity, logical-step SLA binding, delegation retry/overlap safety, then scheduler claim/idempotency/clock policy.
69
-2. Keep D4c external/destination consumers disabled until destination-idempotency, retry/dead-letter, authorization and audit contracts are implemented and adversarially verified.
70
-3. Continue compliance/accounting roadmap only with sourced legal/tax/accounting evidence and controlled cutover safeguards.
70
+1. Verify Wave 4b CI; after explicit schema-change approval, apply and reconcile `request_wave4b_scheduler_outbox_delivery` in production.
71
+2. Keep D4c destination consumers disabled until a real destination adapter enforces `destination_command_key` idempotency and its authorization/audit behavior is adversarially verified.
72
+3. Then continue Wave 5 identity/bootstrap/offboarding remediation before broader roadmap work.
73
74
## Live QA open items
75
- Exact Taxpayer-System print redesign: owner reference images were received in chat and implementation was reported complete; retain regression coverage and do not silently redesign away from the approved reference.
docs/REQUEST_WORKFLOW_WAVE4B_VERIFICATION.md
new
+19
@@ -0,0 +1,19 @@
1
+# Request Workflow Wave 4b Verification
2
+
3
+Status: IMPLEMENTED ON BRANCH / CI PENDING
4
+
5
+## Scope
6
+- SLA escalation scheduler policy: five-minute schedule slots, server-authoritative clock, durable run identity, replay binding, bounded batches and row claims with `FOR UPDATE SKIP LOCKED`.
7
+- Scheduler evidence: durable private run/run-item records plus system audit entries; no fake human actor is recorded.
8
+- Outbox delivery contract: stable destination command key, lease-style claim token, stale-claim recovery, bounded exponential retry, dead-letter state, idempotent operator replay and dispatch evidence.
9
+- Service worker entry points are not granted to `anon` or `authenticated`; production `service_role` grant is conditional at migration time.
10
+- D4c destination consumers remain disabled. A real destination adapter must enforce the supplied `destination_command_key` before D4c can be called end-to-end verified.
11
+
12
+## Clock / claim policy
13
+The database server clock is authoritative. Scheduler callers provide only a five-minute schedule slot; slots too far from the server clock are rejected. A committed slot is unique per organization/job. Step claims use row locks with skip-locked semantics and only rows still active, due, and not already escalated can transition.
14
+
15
+## Retry / replay policy
16
+Outbox claims expire after ten minutes. Delivery attempts are capped at five; retry delay is server-derived exponential backoff capped at one hour. The fifth failed attempt enters `dead_letter`. Authorized workflow configurators can replay a dead letter with an idempotency key; the stable destination command key is never regenerated.
17
+
18
+## Verification gate
19
+Disposable PostgreSQL assertions cover scheduler replay/slot/clock behavior, escalation evidence, stable command identity across retries, stale-claim rejection, retry scheduling, dead-letter transition, replay idempotency and audit dedupe. Production application and external destination consumers are NOT VERIFIED until separately executed.
supabase/migrations/20261002073500_request_wave4b_scheduler_outbox_delivery.sql
new
+217
@@ -0,0 +1,217 @@
1
+-- Wave 4b: explicit SLA scheduler policy and durable outbox delivery state machine.
2
+-- D4c destination consumers remain disabled; this migration only establishes the server-side contract.
3
+
4
+create table if not exists private.request_scheduler_runs(
5
+ id uuid primary key default gen_random_uuid(),
6
+ organization_id uuid not null references public.organizations(id) on delete cascade,
7
+ job_key text not null check(job_key in ('request_sla_escalation')),
8
+ run_key text not null check(char_length(trim(run_key)) between 8 and 200),
9
+ schedule_slot timestamptz not null,
10
+ server_clock timestamptz not null,
11
+ batch_limit integer not null check(batch_limit between 1 and 200),
12
+ processed_count integer not null default 0 check(processed_count between 0 and 200),
13
+ status text not null default 'running' check(status in ('running','completed')),
14
+ created_at timestamptz not null default now(),
15
+ completed_at timestamptz,
16
+ unique(organization_id,job_key,run_key),
17
+ unique(organization_id,job_key,schedule_slot)
18
+);
19
+create table if not exists private.request_scheduler_run_items(
20
+ id uuid primary key default gen_random_uuid(),
21
+ scheduler_run_id uuid not null references private.request_scheduler_runs(id) on delete cascade,
22
+ organization_id uuid not null references public.organizations(id) on delete cascade,
23
+ request_instance_id uuid not null references public.request_instances(id) on delete cascade,
24
+ step_instance_id uuid not null references private.request_step_instances(id) on delete cascade,
25
+ due_at timestamptz not null,
26
+ claimed_at timestamptz not null,
27
+ outcome text not null check(outcome='escalated'),
28
+ created_at timestamptz not null default now(),
29
+ unique(step_instance_id)
30
+);
31
+create index if not exists request_scheduler_runs_org_created_idx on private.request_scheduler_runs(organization_id,created_at desc);
32
+create index if not exists request_scheduler_items_run_idx on private.request_scheduler_run_items(scheduler_run_id,created_at);
33
+revoke all on private.request_scheduler_runs,private.request_scheduler_run_items from public,anon,authenticated;
34
+
35
+alter table private.request_outbox add column if not exists claim_token uuid;
36
+alter table private.request_outbox add column if not exists claimed_at timestamptz;
37
+alter table private.request_outbox add column if not exists last_attempt_at timestamptz;
38
+alter table private.request_outbox add column if not exists last_worker_id text;
39
+alter table private.request_outbox add column if not exists dead_lettered_at timestamptz;
40
+alter table private.request_outbox add column if not exists replay_count integer not null default 0 check(replay_count between 0 and 100);
41
+alter table private.request_outbox add column if not exists last_replay_key text;
42
+alter table private.request_outbox add column if not exists destination_command_key text;
43
+alter table private.request_outbox add column if not exists destination_receipt text;
44
+update private.request_outbox set destination_command_key='request-outbox:'||id::text where destination_command_key is null;
45
+alter table private.request_outbox alter column destination_command_key set not null;
46
+create unique index if not exists request_outbox_destination_command_uidx on private.request_outbox(destination_command_key);
47
+alter table private.request_outbox drop constraint if exists request_outbox_status_check;
48
+alter table private.request_outbox add constraint request_outbox_status_check check(status in ('pending','processing','dispatched','failed','dead_letter'));
49
+alter table private.request_outbox drop constraint if exists request_outbox_last_worker_id_check;
50
+alter table private.request_outbox add constraint request_outbox_last_worker_id_check check(last_worker_id is null or char_length(trim(last_worker_id)) between 3 and 120);
51
+alter table private.request_outbox drop constraint if exists request_outbox_last_replay_key_check;
52
+alter table private.request_outbox add constraint request_outbox_last_replay_key_check check(last_replay_key is null or char_length(trim(last_replay_key)) between 8 and 200);
53
+
54
+create or replace function private.enqueue_request_outbox(p_request_instance_id uuid,p_workflow_schema jsonb,p_revision bigint)
55
+returns integer language plpgsql security definer set search_path=''
56
+as $$
57
+declare v_action jsonb;v_org uuid;v_count integer:=0;v_id uuid;
58
+begin
59
+ select organization_id into v_org from public.request_instances where id=p_request_instance_id;
60
+ if v_org is null then raise exception 'request instance not found';end if;
61
+ if jsonb_typeof(p_workflow_schema->'onApproved')<>'array' then return 0;end if;
62
+ for v_action in select value from jsonb_array_elements(p_workflow_schema->'onApproved') loop
63
+ v_id:=gen_random_uuid();
64
+ insert into private.request_outbox(id,organization_id,request_instance_id,event_key,target_module,action_key,payload,destination_command_key)
65
+ values(v_id,v_org,p_request_instance_id,'approved:'||p_revision::text,lower(trim(v_action->>'targetModule')),lower(trim(v_action->>'actionKey')),jsonb_build_object('requestInstanceId',p_request_instance_id,'requestRevision',p_revision,'config',coalesce(v_action->'payload','{}'::jsonb)),'request-outbox:'||v_id::text)
66
+ on conflict(request_instance_id,event_key,target_module,action_key) do nothing;
67
+ if found then v_count:=v_count+1;end if;
68
+ end loop;
69
+ return v_count;
70
+end $$;
71
+revoke all on function private.enqueue_request_outbox(uuid,jsonb,bigint) from public,anon,authenticated;
72
+
73
+create or replace function private.request_run_sla_scheduler(p_organization_id uuid,p_run_key text,p_schedule_slot timestamptz,p_limit integer default 100)
74
+returns table(run_id uuid,processed_count integer,server_clock timestamptz,replayed boolean)
75
+language plpgsql security definer set search_path=''
76
+as $$
77
+declare v_clock timestamptz:=statement_timestamp();v_run private.request_scheduler_runs%rowtype;v_step private.request_step_instances%rowtype;v_count integer:=0;
78
+begin
79
+ if char_length(trim(coalesce(p_run_key,''))) not between 8 and 200 then raise exception 'scheduler run_key must be between 8 and 200 characters';end if;
80
+ if p_limit is null or p_limit<1 or p_limit>200 then raise exception 'scheduler batch limit must be between 1 and 200';end if;
81
+ if p_schedule_slot is null or mod(extract(epoch from p_schedule_slot)::bigint,300)<>0 then raise exception 'scheduler slot must align to a 5-minute UTC boundary';end if;
82
+ if p_schedule_slot>v_clock+interval '30 seconds' or p_schedule_slot<v_clock-interval '1 hour' then raise exception 'scheduler slot is outside the accepted server-clock window';end if;
83
+ select * into v_run from private.request_scheduler_runs r where r.organization_id=p_organization_id and r.job_key='request_sla_escalation' and r.run_key=trim(p_run_key);
84
+ if found then
85
+ if v_run.schedule_slot<>p_schedule_slot or v_run.batch_limit<>p_limit then raise exception 'scheduler run_key is already bound to a different command' using errcode='23505';end if;
86
+ return query select v_run.id,v_run.processed_count,v_run.server_clock,true;return;
87
+ end if;
88
+ if exists(select 1 from private.request_scheduler_runs r where r.organization_id=p_organization_id and r.job_key='request_sla_escalation' and r.schedule_slot=p_schedule_slot) then raise exception 'scheduler slot is already claimed' using errcode='23505';end if;
89
+ insert into private.request_scheduler_runs(organization_id,job_key,run_key,schedule_slot,server_clock,batch_limit)
90
+ values(p_organization_id,'request_sla_escalation',trim(p_run_key),p_schedule_slot,v_clock,p_limit) returning * into v_run;
91
+ for v_step in
92
+ select * from private.request_step_instances s
93
+ where s.organization_id=p_organization_id and s.state='active' and s.due_at is not null and s.due_at<=v_clock and s.escalated_at is null
94
+ order by s.due_at,s.id for update skip locked limit p_limit
95
+ loop
96
+ update private.request_step_instances set escalated_at=v_clock,escalation_level=escalation_level+1 where id=v_step.id and escalated_at is null;
97
+ if found then
98
+ insert into private.request_scheduler_run_items(scheduler_run_id,organization_id,request_instance_id,step_instance_id,due_at,claimed_at,outcome)
99
+ values(v_run.id,p_organization_id,v_step.request_instance_id,v_step.id,v_step.due_at,v_clock,'escalated');
100
+ insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data)
101
+ values(p_organization_id,null,'request_step_sla_escalated_system','request_step_instance',v_step.id::text,
102
+ jsonb_build_object('requestInstanceId',v_step.request_instance_id,'stepKey',v_step.step_key,'dueAt',v_step.due_at,'serverClock',v_clock,'schedulerRunId',v_run.id));
103
+ v_count:=v_count+1;
104
+ end if;
105
+ end loop;
106
+ update private.request_scheduler_runs set processed_count=v_count,status='completed',completed_at=statement_timestamp() where id=v_run.id returning * into v_run;
107
+ return query select v_run.id,v_run.processed_count,v_run.server_clock,false;
108
+end $$;
109
+revoke all on function private.request_run_sla_scheduler(uuid,text,timestamptz,integer) from public,anon,authenticated;
110
+
111
+create or replace function public.request_run_sla_scheduler(p_organization_id uuid,p_run_key text,p_schedule_slot timestamptz,p_limit integer default 100)
112
+returns table(run_id uuid,processed_count integer,server_clock timestamptz,replayed boolean)
113
+language sql security definer set search_path=''
114
+as $$ select * from private.request_run_sla_scheduler(p_organization_id,p_run_key,p_schedule_slot,p_limit) $$;
115
+revoke all on function public.request_run_sla_scheduler(uuid,text,timestamptz,integer) from public,anon,authenticated;
116
+do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_run_sla_scheduler(uuid,text,timestamptz,integer) to service_role';end if;end $$;
117
+
118
+create or replace function private.request_claim_outbox(p_worker_id text,p_limit integer default 25)
119
+returns table(outbox_id uuid,organization_id uuid,request_instance_id uuid,target_module text,action_key text,payload jsonb,destination_command_key text,claim_token uuid,attempts integer,server_clock timestamptz)
120
+language plpgsql security definer set search_path=''
121
+as $$
122
+declare v_clock timestamptz:=statement_timestamp();
123
+begin
124
+ if char_length(trim(coalesce(p_worker_id,''))) not between 3 and 120 then raise exception 'worker_id must be between 3 and 120 characters';end if;
125
+ if p_limit is null or p_limit<1 or p_limit>100 then raise exception 'outbox claim limit must be between 1 and 100';end if;
126
+ update private.request_outbox o set status='dead_letter',dead_lettered_at=v_clock,claim_token=null,claimed_at=null,last_error=coalesce(o.last_error,'claim lease expired after maximum attempts')
127
+ where o.status='processing' and o.claimed_at<v_clock-interval '10 minutes' and o.attempts>=5;
128
+ return query
129
+ with candidates as (
130
+ select o.id from private.request_outbox o
131
+ where ((o.status in('pending','failed') and o.available_at<=v_clock) or (o.status='processing' and o.claimed_at<v_clock-interval '10 minutes'))
132
+ and o.attempts<5
133
+ order by o.available_at,o.created_at,o.id
134
+ for update skip locked limit p_limit
135
+ ), claimed as (
136
+ update private.request_outbox o set status='processing',claim_token=gen_random_uuid(),claimed_at=v_clock,last_attempt_at=v_clock,last_worker_id=trim(p_worker_id),attempts=o.attempts+1,last_error=case when o.status='processing' then coalesce(o.last_error,'stale claim recovered') else o.last_error end
137
+ from candidates c where o.id=c.id
138
+ returning o.id,o.organization_id,o.request_instance_id,o.target_module,o.action_key,o.payload,o.destination_command_key,o.claim_token,o.attempts
139
+ )
140
+ select c.id,c.organization_id,c.request_instance_id,c.target_module,c.action_key,c.payload,c.destination_command_key,c.claim_token,c.attempts,v_clock from claimed c;
141
+end $$;
142
+revoke all on function private.request_claim_outbox(text,integer) from public,anon,authenticated;
143
+
144
+create or replace function public.request_claim_outbox(p_worker_id text,p_limit integer default 25)
145
+returns table(outbox_id uuid,organization_id uuid,request_instance_id uuid,target_module text,action_key text,payload jsonb,destination_command_key text,claim_token uuid,attempts integer,server_clock timestamptz)
146
+language sql security definer set search_path=''
147
+as $$ select * from private.request_claim_outbox(p_worker_id,p_limit) $$;
148
+revoke all on function public.request_claim_outbox(text,integer) from public,anon,authenticated;
149
+do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_claim_outbox(text,integer) to service_role';end if;end $$;
150
+
151
+create or replace function private.request_complete_outbox(p_outbox_id uuid,p_claim_token uuid,p_destination_receipt text default null)
152
+returns boolean language plpgsql security definer set search_path=''
153
+as $$
154
+declare v_org uuid;v_clock timestamptz:=statement_timestamp();v_key text;
155
+begin
156
+ if p_claim_token is null then raise exception 'claim token is required';end if;
157
+ update private.request_outbox o set status='dispatched',dispatched_at=v_clock,destination_receipt=nullif(left(trim(coalesce(p_destination_receipt,'')),500),''),claim_token=null,claimed_at=null,last_error=null
158
+ where o.id=p_outbox_id and o.status='processing' and o.claim_token=p_claim_token
159
+ returning o.organization_id,o.destination_command_key into v_org,v_key;
160
+ if not found then raise exception 'outbox claim is stale or invalid' using errcode='40001';end if;
161
+ insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data)
162
+ values(v_org,null,'request_outbox_dispatched','request_outbox',p_outbox_id::text,jsonb_build_object('destinationCommandKey',v_key,'serverClock',v_clock));
163
+ return true;
164
+end $$;
165
+revoke all on function private.request_complete_outbox(uuid,uuid,text) from public,anon,authenticated;
166
+create or replace function public.request_complete_outbox(p_outbox_id uuid,p_claim_token uuid,p_destination_receipt text default null)
167
+returns boolean language sql security definer set search_path='' as $$ select private.request_complete_outbox(p_outbox_id,p_claim_token,p_destination_receipt) $$;
168
+revoke all on function public.request_complete_outbox(uuid,uuid,text) from public,anon,authenticated;
169
+do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_complete_outbox(uuid,uuid,text) to service_role';end if;end $$;
170
+
171
+create or replace function private.request_fail_outbox(p_outbox_id uuid,p_claim_token uuid,p_error text)
172
+returns text language plpgsql security definer set search_path=''
173
+as $$
174
+declare v_row private.request_outbox%rowtype;v_clock timestamptz:=statement_timestamp();v_next text;v_delay interval;
175
+begin
176
+ if p_claim_token is null then raise exception 'claim token is required';end if;
177
+ select * into v_row from private.request_outbox o where o.id=p_outbox_id and o.status='processing' and o.claim_token=p_claim_token for update;
178
+ if not found then raise exception 'outbox claim is stale or invalid' using errcode='40001';end if;
179
+ if v_row.attempts>=5 then v_next:='dead_letter';v_delay:=interval '0';else v_next:='failed';v_delay:=make_interval(secs=>least(3600,60*(2^greatest(v_row.attempts-1,0))::integer));end if;
180
+ update private.request_outbox set status=v_next,available_at=v_clock+v_delay,last_error=left(coalesce(nullif(trim(p_error),''),'delivery failed'),1000),dead_lettered_at=case when v_next='dead_letter' then v_clock else null end,claim_token=null,claimed_at=null where id=p_outbox_id;
181
+ insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,after_data)
182
+ values(v_row.organization_id,null,case when v_next='dead_letter' then 'request_outbox_dead_lettered' else 'request_outbox_retry_scheduled' end,'request_outbox',p_outbox_id::text,
183
+ jsonb_build_object('destinationCommandKey',v_row.destination_command_key,'attempts',v_row.attempts,'nextState',v_next,'availableAt',v_clock+v_delay,'serverClock',v_clock));
184
+ return v_next;
185
+end $$;
186
+revoke all on function private.request_fail_outbox(uuid,uuid,text) from public,anon,authenticated;
187
+create or replace function public.request_fail_outbox(p_outbox_id uuid,p_claim_token uuid,p_error text)
188
+returns text language sql security definer set search_path='' as $$ select private.request_fail_outbox(p_outbox_id,p_claim_token,p_error) $$;
189
+revoke all on function public.request_fail_outbox(uuid,uuid,text) from public,anon,authenticated;
190
+do $$ begin if exists(select 1 from pg_roles where rolname='service_role') then execute 'grant execute on function public.request_fail_outbox(uuid,uuid,text) to service_role';end if;end $$;
191
+
192
+create or replace function private.request_replay_dead_letter(p_organization_id uuid,p_outbox_id uuid,p_idempotency_key text,p_reason text)
193
+returns boolean language plpgsql security definer set search_path=''
194
+as $$
195
+declare v_row private.request_outbox%rowtype;v_clock timestamptz:=statement_timestamp();v_before integer;
196
+begin
197
+ if auth.uid() is null then raise exception 'authentication required' using errcode='28000';end if;
198
+ if p_organization_id not in(select private.current_organization_ids()) then raise exception 'organization access denied' using errcode='42501';end if;
199
+ if not private.has_org_capability(p_organization_id,'requests_workflow','configure') then raise exception 'requests_workflow configure capability required' using errcode='42501';end if;
200
+ if char_length(trim(coalesce(p_idempotency_key,''))) not between 8 and 200 then raise exception 'replay idempotency_key must be between 8 and 200 characters';end if;
201
+ select * into v_row from private.request_outbox o where o.id=p_outbox_id and o.organization_id=p_organization_id for update;
202
+ if not found then raise exception 'outbox item not found';end if;
203
+ if v_row.last_replay_key=trim(p_idempotency_key) then return true;end if;
204
+ if v_row.status<>'dead_letter' then raise exception 'only dead-letter outbox items can be replayed';end if;
205
+ v_before:=v_row.attempts;
206
+ update private.request_outbox set status='pending',attempts=0,available_at=v_clock,last_error=null,dead_lettered_at=null,claim_token=null,claimed_at=null,replay_count=replay_count+1,last_replay_key=trim(p_idempotency_key) where id=p_outbox_id;
207
+ insert into public.organization_audit(organization_id,actor_user_id,action,entity_type,entity_id,before_data,after_data)
208
+ values(p_organization_id,auth.uid(),'request_outbox_replayed','request_outbox',p_outbox_id::text,jsonb_build_object('status','dead_letter','attempts',v_before),
209
+ jsonb_build_object('status','pending','destinationCommandKey',v_row.destination_command_key,'reason',left(coalesce(p_reason,''),500),'serverClock',v_clock,'idempotencyKey',trim(p_idempotency_key)));
210
+ return true;
211
+end $$;
212
+revoke all on function private.request_replay_dead_letter(uuid,uuid,text,text) from public,anon;
213
+grant execute on function private.request_replay_dead_letter(uuid,uuid,text,text) to authenticated;
214
+create or replace function public.request_replay_dead_letter(p_organization_id uuid,p_outbox_id uuid,p_idempotency_key text,p_reason text default null)
215
+returns boolean language sql security invoker set search_path='' as $$ select private.request_replay_dead_letter(p_organization_id,p_outbox_id,p_idempotency_key,p_reason) $$;
216
+revoke all on function public.request_replay_dead_letter(uuid,uuid,text,text) from public,anon;
217
+grant execute on function public.request_replay_dead_letter(uuid,uuid,text,text) to authenticated;
supabase/tests/request_wave4b_scheduler_outbox_delivery.sql
new
+93
@@ -0,0 +1,93 @@
1
+\set ON_ERROR_STOP on
2
+set role authenticated;
3
+select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
4
+select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
5
+select set_config('request.jwt.claim.member_active','true',false);
6
+select set_config('request.jwt.claim.entitled','true',false);
7
+select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
8
+create temporary table w4b_ids(k text primary key,v uuid);
9
+insert into w4b_ids select 'type',request_type_version_id from public.request_publish_type_version(
10
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','W4B_OPS','Wave 4b operations',null,
11
+ '{"schemaVersion":1,"fields":[{"key":"subject","label":"Subject","type":"text","required":true}]}'::jsonb,
12
+ '{"schemaVersion":2,"steps":[{"key":"approve","title":"Approve","mode":"sequential","requiredApprovals":1,"requiredCapability":"approve","slaHours":1}],"onApproved":[{"targetModule":"commerce","actionKey":"create_purchase_draft","payload":{"source":"wave4b"}}]}'::jsonb,0);
13
+insert into w4b_ids values('sla_instance',public.request_create_instance(
14
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from w4b_ids where k='type'),'{"subject":"sla"}'::jsonb,'wave4b-create-sla-0001'));
15
+reset role;
16
+update private.request_step_instances set due_at=statement_timestamp()-interval '5 minutes' where request_instance_id=(select v from w4b_ids where k='sla_instance') and state='active';
17
+
18
+create temporary table w4b_scheduler as
19
+select * from public.request_run_sla_scheduler('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','wave4b-scheduler-run-0001',date_trunc('hour',statement_timestamp()),100);
20
+do $$ declare r record;i uuid;begin
21
+ select * into r from w4b_scheduler;i=(select v from w4b_ids where k='sla_instance');
22
+ if r.processed_count<>1 or r.replayed then raise exception 'scheduler first run contract mismatch';end if;
23
+ if not exists(select 1 from private.request_step_instances where request_instance_id=i and escalated_at is not null and escalation_level=1) then raise exception 'scheduler did not escalate overdue step';end if;
24
+ if not exists(select 1 from private.request_scheduler_run_items x where x.scheduler_run_id=r.run_id and x.request_instance_id=i and x.outcome='escalated') then raise exception 'scheduler claim evidence missing';end if;
25
+ if not exists(select 1 from public.organization_audit a where a.action='request_step_sla_escalated_system' and a.actor_user_id is null and a.after_data->>'schedulerRunId'=r.run_id::text) then raise exception 'scheduler system audit evidence missing';end if;
26
+end $$;
27
+do $$ declare r record;begin
28
+ select * into r from public.request_run_sla_scheduler('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','wave4b-scheduler-run-0001',date_trunc('hour',statement_timestamp()),100);
29
+ if r.processed_count<>1 or not r.replayed then raise exception 'scheduler replay was not stable';end if;
30
+end $$;
31
+do $$ begin begin
32
+ perform * from public.request_run_sla_scheduler('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','wave4b-scheduler-run-0002',date_trunc('hour',statement_timestamp()),100);
33
+ raise exception 'duplicate scheduler slot unexpectedly succeeded';
34
+ exception when unique_violation then null;end;end $$;
35
+do $$ begin begin
36
+ perform * from public.request_run_sla_scheduler('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','wave4b-scheduler-future',date_trunc('hour',statement_timestamp())+interval '2 hours',100);
37
+ raise exception 'future scheduler clock unexpectedly accepted';
38
+ exception when others then if position('server-clock window' in sqlerrm)=0 then raise;end if;end;end $$;
39
+
40
+set role authenticated;
41
+select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
42
+select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
43
+select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
44
+insert into w4b_ids values('delivery_instance',public.request_create_instance(
45
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from w4b_ids where k='type'),'{"subject":"delivery"}'::jsonb,'wave4b-create-delivery-0001'));
46
+do $$ declare r record;begin select * into r from public.request_step_decide((select v from w4b_ids where k='delivery_instance'),'approve',1,'wave4b-approve-delivery-0001','approve') limit 1;if r.status<>'approved' then raise exception 'delivery request did not approve';end if;end $$;
47
+reset role;
48
+insert into w4b_ids select 'outbox',id from private.request_outbox where request_instance_id=(select v from w4b_ids where k='delivery_instance');
49
+create temporary table w4b_claim1 as select * from public.request_claim_outbox('wave4b-worker-a',10) where outbox_id=(select v from w4b_ids where k='outbox');
50
+do $$ declare r record;begin select * into r from w4b_claim1;if r.attempts<>1 or r.destination_command_key<>'request-outbox:'||r.outbox_id::text or r.claim_token is null then raise exception 'first outbox claim contract mismatch';end if;end $$;
51
+select public.request_fail_outbox((select v from w4b_ids where k='outbox'),(select claim_token from w4b_claim1),'temporary destination failure');
52
+do $$ begin if not exists(select 1 from private.request_outbox where id=(select v from w4b_ids where k='outbox') and status='failed' and attempts=1 and available_at>last_attempt_at) then raise exception 'retry scheduling state mismatch';end if;end $$;
53
+update private.request_outbox set available_at=statement_timestamp()-interval '1 second' where id=(select v from w4b_ids where k='outbox');
54
+create temporary table w4b_claim2 as select * from public.request_claim_outbox('wave4b-worker-b',10) where outbox_id=(select v from w4b_ids where k='outbox');
55
+do $$ declare a text;b text;begin a=(select destination_command_key from w4b_claim1);b=(select destination_command_key from w4b_claim2);if a<>b or (select attempts from w4b_claim2)<>2 then raise exception 'destination command identity was not stable across retry';end if;end $$;
56
+select public.request_complete_outbox((select v from w4b_ids where k='outbox'),(select claim_token from w4b_claim2),'destination-receipt-1');
57
+do $$ begin if not exists(select 1 from private.request_outbox where id=(select v from w4b_ids where k='outbox') and status='dispatched' and dispatched_at is not null and destination_receipt='destination-receipt-1') then raise exception 'outbox completion state mismatch';end if;end $$;
58
+do $$ begin begin perform public.request_complete_outbox((select v from w4b_ids where k='outbox'),(select claim_token from w4b_claim2),'duplicate');raise exception 'stale claim unexpectedly completed twice';exception when serialization_failure then null;end;end $$;
59
+
60
+set role authenticated;
61
+select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
62
+select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
63
+select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
64
+insert into w4b_ids values('dead_instance',public.request_create_instance(
65
+ 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from w4b_ids where k='type'),'{"subject":"dead"}'::jsonb,'wave4b-create-dead-0001'));
66
+do $$ declare r record;begin select * into r from public.request_step_decide((select v from w4b_ids where k='dead_instance'),'approve',1,'wave4b-approve-dead-0001','approve') limit 1;if r.status<>'approved' then raise exception 'dead-letter request did not approve';end if;end $$;
67
+reset role;
68
+insert into w4b_ids select 'dead_outbox',id from private.request_outbox where request_instance_id=(select v from w4b_ids where k='dead_instance');
69
+do $$ declare n integer;tok uuid;s text;begin
70
+ for n in 1..5 loop
71
+ update private.request_outbox set available_at=statement_timestamp()-interval '1 second' where id=(select v from w4b_ids where k='dead_outbox');
72
+ select claim_token into tok from public.request_claim_outbox('wave4b-dead-worker',10) where outbox_id=(select v from w4b_ids where k='dead_outbox');
73
+ if tok is null then raise exception 'dead-letter attempt % was not claimable',n;end if;
74
+ s:=public.request_fail_outbox((select v from w4b_ids where k='dead_outbox'),tok,'persistent failure');
75
+ if n<5 and s<>'failed' then raise exception 'attempt % should schedule retry',n;end if;
76
+ if n=5 and s<>'dead_letter' then raise exception 'attempt 5 should dead-letter';end if;
77
+ end loop;
78
+end $$;
79
+do $$ begin if not exists(select 1 from private.request_outbox where id=(select v from w4b_ids where k='dead_outbox') and status='dead_letter' and attempts=5 and dead_lettered_at is not null) then raise exception 'dead-letter terminal state missing';end if;end $$;
80
+
81
+set role authenticated;
82
+select set_config('request.jwt.claim.sub','11111111-1111-1111-1111-111111111111',false);
83
+select set_config('request.jwt.claim.org','aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',false);
84
+select set_config('request.jwt.claim.capabilities','read,configure,create,edit,approve',false);
85
+select public.request_replay_dead_letter('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from w4b_ids where k='dead_outbox'),'wave4b-replay-dead-0001','operator reviewed destination');
86
+select public.request_replay_dead_letter('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',(select v from w4b_ids where k='dead_outbox'),'wave4b-replay-dead-0001','operator reviewed destination');
87
+reset role;
88
+do $$ declare v_destination_key text;begin
89
+ select o.destination_command_key into v_destination_key from private.request_outbox o where o.id=(select x.v from w4b_ids x where x.k='dead_outbox');
90
+ if not exists(select 1 from private.request_outbox where id=(select x.v from w4b_ids x where x.k='dead_outbox') and status='pending' and attempts=0 and replay_count=1 and last_replay_key='wave4b-replay-dead-0001') then raise exception 'dead-letter replay state mismatch';end if;
91
+ if v_destination_key<>'request-outbox:'||(select x.v from w4b_ids x where x.k='dead_outbox')::text then raise exception 'destination command key changed across dead-letter replay';end if;
92
+ if (select count(*) from public.organization_audit where action='request_outbox_replayed' and entity_id=(select x.v from w4b_ids x where x.k='dead_outbox')::text)<>1 then raise exception 'replay idempotency duplicated audit evidence';end if;
93
+end $$;