From b7024950a5860ea740fe9826b228be660cfadf0f Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Wed, 23 Sep 2026 09:22:04 +0200 Subject: [PATCH] fix(context): revalidate request scope during evidence completion --- ...0260923070000_context_enrichment_scope.sql | 62 +++++++++++++++++++ supabase/tests/README.md | 6 ++ supabase/tests/context_completion_scope.sql | 50 +++++++++++++++ 3 files changed, 118 insertions(+) create mode 100644 supabase/migrations/20260923070000_context_enrichment_scope.sql create mode 100644 supabase/tests/context_completion_scope.sql diff --git a/supabase/migrations/20260923070000_context_enrichment_scope.sql b/supabase/migrations/20260923070000_context_enrichment_scope.sql new file mode 100644 index 0000000..fb63d09 --- /dev/null +++ b/supabase/migrations/20260923070000_context_enrichment_scope.sql @@ -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; + 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; +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; + 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; + 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 $$; + +commit; diff --git a/supabase/tests/README.md b/supabase/tests/README.md index 7854c36..547cafe 100644 --- a/supabase/tests/README.md +++ b/supabase/tests/README.md @@ -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. diff --git a/supabase/tests/context_completion_scope.sql b/supabase/tests/context_completion_scope.sql new file mode 100644 index 0000000..12a6f48 --- /dev/null +++ b/supabase/tests/context_completion_scope.sql @@ -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 + 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;