Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions supabase/migrations/20260923070000_context_enrichment_scope.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
-- Revalidate and lock request scope for both reuse/claim and final evidence save.
-- Shared row locks allow parallel collectors but serialize cancellation or subject removal.
-- No provider calls, automatic retries, or API dispatch are enabled.
begin;
create or replace function public.claim_context_enrichment(p_owner uuid,p_request uuid,p_module jsonb)
returns jsonb language plpgsql set search_path='' as $$
declare req public.context_requests; previous public.context_attempts; found_result public.context_results; attempt uuid;
begin
select * into strict req from public.context_requests where owner_id=p_owner and id=p_request for share;
if jsonb_typeof(req.output->'subjectIds') is distinct from 'array' or (req.output->'subjectIds' ? (p_module->>'subjectId')) is not true or req.status not in ('partial','completed') then raise exception 'Subject outside completed metadata request'; end if;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These checks accept malformed subject lists when a valid subject is present, so claim and evidence completion still proceed for invalid scope metadata. Validate every subjectIds element as a UUID string in both the claim and completion predicates.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 10:

<comment>These checks accept malformed subject lists when a valid subject is present, so claim and evidence completion still proceed for invalid scope metadata. Validate every `subjectIds` element as a UUID string in both the claim and completion predicates.</comment>

<file context>
@@ -0,0 +1,62 @@
+declare req public.context_requests; previous public.context_attempts; found_result public.context_results; attempt uuid;
+begin
+ select * into strict req from public.context_requests where owner_id=p_owner and id=p_request for share;
+ if jsonb_typeof(req.output->'subjectIds') is distinct from 'array' or (req.output->'subjectIds' ? (p_module->>'subjectId')) is not true or req.status not in ('partial','completed') then raise exception 'Subject outside completed metadata request'; end if;
+ if p_module->>'fingerprint' !~ '^[a-f0-9]{64}$' or p_module->>'topic' not in ('catalog_metadata','lyrics','song_summary','artwork_branding','artist_research','musicbrainz_recordings','mlc_recordings','mlc_works','mlc_work_candidates','chartmetric_candidates','songstats_context','spotify_release_context','social_context','catalog_valuation') then raise exception 'Invalid enrichment module'; end if;
+ if coalesce(p_module->>'evidenceKind','interpretation') not in ('observation','estimate','interpretation') then raise exception 'Invalid evidence kind'; end if;
</file context>

if p_module->>'fingerprint' !~ '^[a-f0-9]{64}$' or p_module->>'topic' not in ('catalog_metadata','lyrics','song_summary','artwork_branding','artist_research','musicbrainz_recordings','mlc_recordings','mlc_works','mlc_work_candidates','chartmetric_candidates','songstats_context','spotify_release_context','social_context','catalog_valuation') then raise exception 'Invalid enrichment module'; end if;
if coalesce(p_module->>'evidenceKind','interpretation') not in ('observation','estimate','interpretation') then raise exception 'Invalid evidence kind'; end if;
if p_module->>'topic' in ('musicbrainz_recordings','mlc_recordings','mlc_works','mlc_work_candidates','chartmetric_candidates','songstats_context','spotify_release_context','social_context') and coalesce(p_module->>'evidenceKind','')<>'observation' then raise exception 'Provider lookup requires observation evidence'; end if;
if p_module->>'topic'='catalog_valuation' and coalesce(p_module->>'evidenceKind','')<>'estimate' then raise exception 'Valuation requires estimate evidence'; end if;
perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(p_owner::text||(p_module->>'fingerprint'),0));
select r.* into found_result from public.context_results r join public.context_documents d on d.current_result_id=r.id
where r.owner_id=p_owner and r.reuse_key=p_module->>'fingerprint' and r.status='accepted'
and not exists(select 1 from public.context_result_sources rs join public.context_source_versions v on v.id=rs.source_version_id join public.context_sources s on s.id=v.source_id where rs.result_id=r.id and (s.withdrawn_at is not null or v.removed_at is not null)) limit 1;
if found_result.id is not null then return jsonb_build_object('state','reused','resultId',found_result.id,'content',found_result.normalized_response); end if;
select * into previous from public.context_attempts where owner_id=p_owner and input->>'fingerprint'=p_module->>'fingerprint' limit 1;
-- An interrupted provider call may already have incurred expense. Do not guess or retry it.
if previous.id is not null then return jsonb_build_object('state','unknown','attemptId',previous.id); end if;
insert into public.context_attempts(owner_id,request_id,module,attempt,status,provider,model,recipe_version,schema_version,input,started_at)
values(p_owner,p_request,p_module->>'fingerprint',1,'running',p_module->>'provider',p_module->>'model',p_module->>'key','1',p_module,now()) returning id into attempt;
return jsonb_build_object('state','claimed','attemptId',attempt);
end $$;

create or replace function public.complete_context_enrichment(p_owner uuid,p_request uuid,p_attempt uuid,p_result jsonb)
returns jsonb language plpgsql set search_path='' as $$
declare req public.context_requests; a public.context_attempts; d public.context_documents; result uuid; source uuid; version uuid; item jsonb; hash text; evidence_sources jsonb;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

Rename the single-letter row variables a and d to precise names such as attempt_row and document_row throughout complete_context_enrichment; their current names obscure the data flow in this complex transaction.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 30:

<comment>Rename the single-letter row variables `a` and `d` to precise names such as `attempt_row` and `document_row` throughout `complete_context_enrichment`; their current names obscure the data flow in this complex transaction.</comment>

<file context>
@@ -0,0 +1,62 @@
+
+create or replace function public.complete_context_enrichment(p_owner uuid,p_request uuid,p_attempt uuid,p_result jsonb)
+returns jsonb language plpgsql set search_path='' as $$
+declare req public.context_requests; a public.context_attempts; d public.context_documents; result uuid; source uuid; version uuid; item jsonb; hash text; evidence_sources jsonb;
+begin
+ -- Lock request before attempt; keep status and membership stable through commit.
</file context>

begin
-- Lock request before attempt; keep status and membership stable through commit.
select * into strict req from public.context_requests where owner_id=p_owner and id=p_request for share;
select * into strict a from public.context_attempts where owner_id=p_owner and request_id=p_request and id=p_attempt for update;
if jsonb_typeof(req.output->'subjectIds') is distinct from 'array' or (req.output->'subjectIds' ? (a.input->>'subjectId')) is not true or req.status not in ('partial','completed') then raise exception 'Subject outside completed metadata request'; end if;
if a.status='succeeded' then return jsonb_build_object('state','saved','attemptId',a.id); end if;
if a.status<>'running' then raise exception 'Attempt not running'; end if;
evidence_sources:=coalesce(p_result->'observedSources',a.input->'sources');
if jsonb_typeof(evidence_sources) is distinct from 'array' then raise exception 'Invalid evidence sources'; end if;
if p_result->>'coverage' not in ('full','partial','unknown') or p_result->'content' is null or jsonb_array_length(evidence_sources)=0 then raise exception 'Missing evidence'; end if;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: p_result->'content' is null does not reject {"content": null}: -> returns SQL NULL only for a missing key, so a JSON-null content passes and is stored as an accepted result with JSON-null normalized_response. The source loop in this same function already guards item->'content'='null'::jsonb; apply the same guard to the top-level content.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 40:

<comment>`p_result->'content' is null` does not reject `{"content": null}`: `->` returns SQL NULL only for a missing key, so a JSON-null content passes and is stored as an `accepted` result with JSON-null `normalized_response`. The source loop in this same function already guards `item->'content'='null'::jsonb`; apply the same guard to the top-level content.</comment>

<file context>
@@ -0,0 +1,62 @@
+ if a.status<>'running' then raise exception 'Attempt not running'; end if;
+ evidence_sources:=coalesce(p_result->'observedSources',a.input->'sources');
+ if jsonb_typeof(evidence_sources) is distinct from 'array' then raise exception 'Invalid evidence sources'; end if;
+ if p_result->>'coverage' not in ('full','partial','unknown') or p_result->'content' is null or jsonb_array_length(evidence_sources)=0 then raise exception 'Missing evidence'; end if;
+ insert into public.context_documents(owner_id,subject_id,topic) values(p_owner,(a.input->>'subjectId')::uuid,a.input->>'topic') on conflict do nothing;
+ select * into strict d from public.context_documents where owner_id=p_owner and subject_id=(a.input->>'subjectId')::uuid and topic=a.input->>'topic' for update;
</file context>

insert into public.context_documents(owner_id,subject_id,topic) values(p_owner,(a.input->>'subjectId')::uuid,a.input->>'topic') on conflict do nothing;
select * into strict d from public.context_documents where owner_id=p_owner and subject_id=(a.input->>'subjectId')::uuid and topic=a.input->>'topic' for update;
insert into public.context_results(owner_id,attempt_id,subject_id,topic,reuse_key,status,evidence_kind,raw_response,normalized_response,coverage)
values(p_owner,p_attempt,d.subject_id,d.topic,a.input->>'fingerprint','accepted',coalesce(a.input->>'evidenceKind','interpretation'),p_result->'trace',p_result->'content',jsonb_build_object('extent',p_result->>'coverage','recipe',a.recipe_version)) returning id into result;
for item in select value from jsonb_array_elements(evidence_sources) loop
if item->'content' is null or item->'content'='null'::jsonb or not exists(select 1 from jsonb_array_elements(a.input->'sources') declared where declared->>'url'=item->>'url' and declared->>'kind'=item->>'kind') then raise exception 'Undeclared or empty source evidence'; end if;
insert into public.context_sources(owner_id,source_url,kind) values(p_owner,item->>'url',item->>'kind')
on conflict(owner_id,kind,source_url) where withdrawn_at is null and source_url is not null do update set source_url=excluded.source_url returning id into source;
hash:=encode(sha256(convert_to((item->'content')::text,'UTF8')),'hex');
insert into public.context_source_versions(owner_id,source_id,fingerprint,content) values(p_owner,source,hash,item->'content')
on conflict(source_id,fingerprint) do update set fingerprint=excluded.fingerprint returning id into version;
insert into public.context_result_sources(owner_id,result_id,source_version_id) values(p_owner,result,version) on conflict do nothing;
end loop;
-- A slower analysis cannot replace an attempt started after it.
if exists(select 1 from public.context_results r join public.context_attempts newer on newer.id=r.attempt_id where r.id=d.current_result_id and newer.started_at>a.started_at)
then update public.context_results set status='stale' where id=result;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: When a newer attempt is already current, this path marks the new result stale but still returns state='saved' with the stale resultId and content. The receipt is indistinguishable from a genuinely accepted save, so callers can surface non-current content. Return an explicit non-saved state (or fall through to accept_context_result semantics) for the stale branch instead of reporting saved.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 56:

<comment>When a newer attempt is already current, this path marks the new result `stale` but still returns `state='saved'` with the stale `resultId` and content. The receipt is indistinguishable from a genuinely accepted save, so callers can surface non-current content. Return an explicit non-saved state (or fall through to `accept_context_result` semantics) for the stale branch instead of reporting `saved`.</comment>

<file context>
@@ -0,0 +1,62 @@
+ end loop;
+ -- A slower analysis cannot replace an attempt started after it.
+ if exists(select 1 from public.context_results r join public.context_attempts newer on newer.id=r.attempt_id where r.id=d.current_result_id and newer.started_at>a.started_at)
+ then update public.context_results set status='stale' where id=result;
+ else if not public.accept_context_result(p_owner,d.id,result,d.revision) then raise exception 'Source no longer acceptable'; end if; end if;
+ update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=p_result->>'costStatus' where id=p_attempt;
</file context>

else if not public.accept_context_result(p_owner,d.id,result,d.revision) then raise exception 'Source no longer acceptable'; end if; end if;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Custom agent: Enforce Clear Code Style and Maintainability Practices

This nested branch hides the stale-result and acceptance-failure paths in one line. Format it as a clear elsif branch with separate condition, exception, and terminator lines.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 57:

<comment>This nested branch hides the stale-result and acceptance-failure paths in one line. Format it as a clear `elsif` branch with separate condition, exception, and terminator lines.</comment>

<file context>
@@ -0,0 +1,62 @@
+ -- A slower analysis cannot replace an attempt started after it.
+ if exists(select 1 from public.context_results r join public.context_attempts newer on newer.id=r.attempt_id where r.id=d.current_result_id and newer.started_at>a.started_at)
+ then update public.context_results set status='stale' where id=result;
+ else if not public.accept_context_result(p_owner,d.id,result,d.revision) then raise exception 'Source no longer acceptable'; end if; end if;
+ update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=p_result->>'costStatus' where id=p_attempt;
+ return jsonb_build_object('state','saved','resultId',result,'content',p_result->'content');
</file context>

update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=p_result->>'costStatus' where id=p_attempt;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: provider_cost_status=p_result->>'costStatus' assigns NULL when the payload omits costStatus, violating the column's NOT NULL constraint. That aborts the completion at the last statement: evidence is rolled back, the attempt stays running, and claim_context_enrichment will then return unknown forever (no retry, paid provider call lost). Wrap it: provider_cost_status=coalesce(p_result->>'costStatus','unknown'). Note provider_cost_micros is already guarded with CASE in the same statement, so this column should be too.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/migrations/20260923070000_context_enrichment_scope.sql, line 58:

<comment>`provider_cost_status=p_result->>'costStatus'` assigns NULL when the payload omits `costStatus`, violating the column's NOT NULL constraint. That aborts the completion at the last statement: evidence is rolled back, the attempt stays `running`, and `claim_context_enrichment` will then return `unknown` forever (no retry, paid provider call lost). Wrap it: `provider_cost_status=coalesce(p_result->>'costStatus','unknown')`. Note `provider_cost_micros` is already guarded with CASE in the same statement, so this column should be too.</comment>

<file context>
@@ -0,0 +1,62 @@
+ if exists(select 1 from public.context_results r join public.context_attempts newer on newer.id=r.attempt_id where r.id=d.current_result_id and newer.started_at>a.started_at)
+ then update public.context_results set status='stale' where id=result;
+ else if not public.accept_context_result(p_owner,d.id,result,d.revision) then raise exception 'Source no longer acceptable'; end if; end if;
+ update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=p_result->>'costStatus' where id=p_attempt;
+ return jsonb_build_object('state','saved','resultId',result,'content',p_result->'content');
+end $$;
</file context>
Suggested change
update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=p_result->>'costStatus' where id=p_attempt;
update public.context_attempts set status='succeeded',finished_at=now(),provider_cost_micros=case when jsonb_typeof(p_result->'costUsd')='number' then round((p_result->>'costUsd')::numeric*1000000)::bigint else null end,provider_cost_status=coalesce(p_result->>'costStatus','unknown') where id=p_attempt;

return jsonb_build_object('state','saved','resultId',result,'content',p_result->'content');
end $$;

commit;
6 changes: 6 additions & 0 deletions supabase/tests/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@ This is the additive foundation for recoupable/app#2116, not activation of the c
After both Context Engine migrations, run `supabase/tests/context_pipeline.sql`. It exercises real transactions for retry identity, input conflicts, worker claims, saved context, artist reuse across two tracks and owner-scoped reads. It rolls back synthetic fixtures. Use a disposable database with the existing accounts, songs, social/roster and organization tables; do not run test fixtures in production.

The opt-in API `lib/context/__tests__/pipeline.live.test.ts` uses the same stored functions against local PostgreSQL with real Spotify metadata. This is not deployed Supabase or paid-enrichment validation.

## Enrichment completion scope

After the enrichment migrations through `20260923070000_context_enrichment_scope.sql`, run `context_completion_scope.sql` in a disposable local database. It rolls back its fixtures and checks cancellation after claim, removed/missing/malformed subject membership, wrong owner, valid completion, duplicate completion, and cancellation before an idempotent response. Rejected completions must leave no documents, results or sources.

Both claim and completion acquire a shared request row lock before examining scope. This permits concurrent collectors while preventing status/output updates until their transaction finishes. API actor/workspace authorization remains required; this migration does not enable workflow dispatch.
50 changes: 50 additions & 0 deletions supabase/tests/context_completion_scope.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
-- Disposable local database only. No provider calls; all fixtures roll back.
begin;
do $$
declare owner uuid:=gen_random_uuid(); resource uuid; subject uuid; request uuid;
module jsonb; claim jsonb; saved jsonb; payload jsonb; invalid_output jsonb; mode text;
begin
insert into public.accounts(id) values(owner);
insert into public.context_resources(provider,resource_kind,provider_id,canonical_url)
values('spotify','release',gen_random_uuid()::text,'https://example.com/fixture') returning id into resource;
insert into public.context_subjects(kind,resource_id) values('release',resource) returning id into subject;
insert into public.context_requests(owner_id,created_by,resource_id,idempotency_key,input_fingerprint,input,status,output)
values(owner,owner,resource,'scope-fixture',repeat('a',64),'{}','completed',jsonb_build_object('subjectIds',jsonb_build_array(subject))) returning id into request;
module:=jsonb_build_object('key','scope-v1','topic','spotify_release_context','subjectId',subject,'provider','fixture','model','none','evidenceKind','observation','fingerprint',repeat('b',64),'sources',jsonb_build_array(jsonb_build_object('url','https://example.com/fixture','kind','provider_metadata','content',jsonb_build_object('fixture',true))));
payload:=jsonb_build_object('content',jsonb_build_object('fixture',true),'coverage','full','trace','{}'::jsonb,'costStatus','unknown');
claim:=public.claim_context_enrichment(owner,request,module);
for mode in select unnest(array['cancelled','removed','null','missing','object']) loop

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The scope guards accept status in ('partial','completed'), but every iteration of this test only exercises 'completed'. A regression that broke the 'partial' path (e.g. restricting the guard to 'completed' only) would pass this suite. Add one iteration — e.g. a 'partial' mode that keeps valid subjectIds and status 'partial' and expects a successful save/completion — to cover the allowed path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At supabase/tests/context_completion_scope.sql, line 16:

<comment>The scope guards accept `status in ('partial','completed')`, but every iteration of this test only exercises 'completed'. A regression that broke the 'partial' path (e.g. restricting the guard to 'completed' only) would pass this suite. Add one iteration — e.g. a 'partial' mode that keeps valid subjectIds and status 'partial' and expects a successful save/completion — to cover the allowed path.</comment>

<file context>
@@ -0,0 +1,50 @@
+ module:=jsonb_build_object('key','scope-v1','topic','spotify_release_context','subjectId',subject,'provider','fixture','model','none','evidenceKind','observation','fingerprint',repeat('b',64),'sources',jsonb_build_array(jsonb_build_object('url','https://example.com/fixture','kind','provider_metadata','content',jsonb_build_object('fixture',true))));
+ payload:=jsonb_build_object('content',jsonb_build_object('fixture',true),'coverage','full','trace','{}'::jsonb,'costStatus','unknown');
+ claim:=public.claim_context_enrichment(owner,request,module);
+ for mode in select unnest(array['cancelled','removed','null','missing','object']) loop
+  invalid_output:=case mode when 'cancelled' then jsonb_build_object('subjectIds',jsonb_build_array(subject)) when 'removed' then '{"subjectIds":[]}'::jsonb when 'null' then null when 'missing' then '{}'::jsonb else jsonb_build_object('subjectIds',jsonb_build_object(subject::text,true)) end;
+  update public.context_requests set status=case when mode='cancelled' then 'cancelled' else 'completed' end,output=invalid_output where id=request;
</file context>

invalid_output:=case mode when 'cancelled' then jsonb_build_object('subjectIds',jsonb_build_array(subject)) when 'removed' then '{"subjectIds":[]}'::jsonb when 'null' then null when 'missing' then '{}'::jsonb else jsonb_build_object('subjectIds',jsonb_build_object(subject::text,true)) end;
update public.context_requests set status=case when mode='cancelled' then 'cancelled' else 'completed' end,output=invalid_output where id=request;
begin
perform public.complete_context_enrichment(owner,request,(claim->>'attemptId')::uuid,payload);
raise exception 'TEST_FAILURE: saved after %',mode;
exception when others then
if SQLERRM not like 'Subject outside completed metadata request%' then raise; end if;
end;
begin
perform public.claim_context_enrichment(owner,request,module);
raise exception 'TEST_FAILURE: claimed after %',mode;
exception when others then
if SQLERRM not like 'Subject outside completed metadata request%' then raise; end if;
end;
end loop;
if exists(select 1 from public.context_results where owner_id=owner) or exists(select 1 from public.context_documents where owner_id=owner) or exists(select 1 from public.context_sources where owner_id=owner) then raise exception 'TEST_FAILURE: rejected save left evidence'; end if;
update public.context_requests set status='completed',output=jsonb_build_object('subjectIds',jsonb_build_array(subject)) where id=request;
begin
perform public.complete_context_enrichment(gen_random_uuid(),request,(claim->>'attemptId')::uuid,payload);
raise exception 'TEST_FAILURE: wrong owner accepted';
exception when no_data_found then null; end;
saved:=public.complete_context_enrichment(owner,request,(claim->>'attemptId')::uuid,payload);
if saved->>'state' is distinct from 'saved' then raise exception 'TEST_FAILURE: valid save rejected'; end if;
perform public.complete_context_enrichment(owner,request,(claim->>'attemptId')::uuid,payload);
if (select count(*) from public.context_results where owner_id=owner)<>1 then raise exception 'TEST_FAILURE: duplicate completion'; end if;
update public.context_requests set status='cancelled' where id=request;
begin
perform public.complete_context_enrichment(owner,request,(claim->>'attemptId')::uuid,payload);
raise exception 'TEST_FAILURE: succeeded attempt bypassed cancellation';
exception when others then
if SQLERRM not like 'Subject outside completed metadata request%' then raise; end if;
end;
end $$;
rollback;