From dc8e488825d340eadacea4501bb29b8f93c45c58 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:26:24 -0400 Subject: [PATCH 1/3] Add single-video YouTube locator entry for Context A manager can now save one music-video URL into the Context Engine without the engine inventing anything about it. create_context_video_request stores the video as its own subject with a customer-assertion locator document and six explicit gaps, so the uploader/channel, performers, credited artists, recording match, captions, language and media version stay unresolved or uncollected instead of silently becoming artist, lyrics or brand facts. No artist, recording, roster, song or identifier rows are created, no song or artist document is written, and the function is service-role only. The video kind was already permitted by the subject constraints, so no table or constraint changes are needed. Fixture-tested on disposable PostgreSQL; a new CI workflow covers PostgreSQL 15 and 16. Refs recoupable/app#2131 Co-Authored-By: Claude Fable 5.1 --- .github/workflows/context-video-entry.yml | 32 +++++ .../20261010213100_context_video_entry.sql | 68 ++++++++++ supabase/tests/README.md | 15 +++ supabase/tests/context_video_entry.sql | 124 ++++++++++++++++++ tests/test_context_video_entry.py | 97 ++++++++++++++ 5 files changed, 336 insertions(+) create mode 100644 .github/workflows/context-video-entry.yml create mode 100644 supabase/migrations/20261010213100_context_video_entry.sql create mode 100644 supabase/tests/context_video_entry.sql create mode 100644 tests/test_context_video_entry.py diff --git a/.github/workflows/context-video-entry.yml b/.github/workflows/context-video-entry.yml new file mode 100644 index 0000000..26bdcdc --- /dev/null +++ b/.github/workflows/context-video-entry.yml @@ -0,0 +1,32 @@ +name: Context video locator transactions + +on: + pull_request: + branches: [main] + push: + branches: [main] + +permissions: + contents: read + +jobs: + context-video-entry: + runs-on: ubuntu-24.04 + timeout-minutes: 10 + strategy: + fail-fast: false + matrix: + postgres: [15, 16] + steps: + - uses: actions/checkout@v4 + - name: Install PostgreSQL + run: | + sudo apt-get update + sudo apt-get install -y postgresql-common + sudo /usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y + sudo apt-get update + sudo apt-get install -y postgresql-${{ matrix.postgres }} + - name: Test single-video locator entry + run: | + export PATH="/usr/lib/postgresql/${{ matrix.postgres }}/bin:$PATH" + python3 -m unittest discover -s tests -p 'test_context_video_entry.py' diff --git a/supabase/migrations/20261010213100_context_video_entry.sql b/supabase/migrations/20261010213100_context_video_entry.sql new file mode 100644 index 0000000..961ccda --- /dev/null +++ b/supabase/migrations/20261010213100_context_video_entry.sql @@ -0,0 +1,68 @@ +-- A submitted YouTube video URL identifies a locator, not verified video metadata, +-- a recording match, an uploader-as-artist link, captions or lyrics. The uploading +-- channel, performers, credited artists and the recording stay explicitly unresolved +-- until separate evidence links them. No artist, recording, roster or lyrics rows +-- are created, and no song or artist brand document is touched. +begin; +create function public.create_context_video_request(p_owner uuid,p_actor uuid,p_video text,p_key text) +returns jsonb language plpgsql set search_path='' as $$ +declare resource uuid; subject uuid; r public.context_requests; request_fingerprint text; uri text; + source uuid; source_version uuid; document public.context_documents; v_attempt uuid; result uuid; + snapshot jsonb; snapshot_hash text; gaps jsonb; +begin + if p_video is null or p_video !~ '^[A-Za-z0-9_-]{11}$' then raise exception 'Invalid YouTube video identifier'; end if; + request_fingerprint:=encode(sha256(convert_to('youtube-video-locator-v1:'||p_video,'UTF8')),'hex'); + uri:='https://www.youtube.com/watch?v='||p_video; + insert into public.context_resources(provider,resource_kind,provider_id,canonical_url) + values('youtube','video',p_video,uri) + on conflict(provider,resource_kind,provider_id) do update set provider_id=excluded.provider_id returning id into resource; + insert into public.context_requests(owner_id,created_by,resource_id,idempotency_key,input_fingerprint,input) + values(p_owner,p_actor,resource,p_key,request_fingerprint, + jsonb_build_object('kind','video','url',uri,'videoId',p_video,'identityConfirmed',false)) + on conflict(owner_id,idempotency_key) do nothing; + select * into strict r from public.context_requests where owner_id=p_owner and idempotency_key=p_key for update; + if r.input_fingerprint<>request_fingerprint then raise exception 'Idempotency key already used for different input'; end if; + if r.status in ('completed','partial','cancelled') then return to_jsonb(r)-'claim_token'; end if; + -- The video is its own subject. It is never attached to an artist, recording or release here. + insert into public.context_subjects(kind,resource_id) values('video',resource) + on conflict(resource_id) do update set resource_id=excluded.resource_id returning id into subject; + insert into public.context_resource_links(resource_id,subject_id,relation,status,evidence) + values(resource,subject,'identity','accepted',jsonb_build_object('source','submitted_youtube_video_url')) + on conflict(resource_id,subject_id,relation) do nothing; + if not exists(select 1 from public.context_resource_links where resource_id=resource and subject_id=subject and relation='identity' and status='accepted') + then raise exception 'Video locator identity is disputed'; end if; + -- Every unknown stays an explicit unknown. Nothing below is fetched or inferred. + snapshot:=jsonb_build_object('url',uri,'youtubeVideoId',p_video,'submittedBy',p_actor, + 'metadataVerified',false,'uploaderIsArtist','unknown','recordingMatch','unresolved', + 'captions','uncollected','language','unknown','mediaVersion','unknown'); + snapshot_hash:=encode(sha256(convert_to(snapshot::text,'UTF8')),'hex'); + insert into public.context_sources(owner_id,source_url,kind) values(p_owner,uri,'customer') + 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; + insert into public.context_source_versions(owner_id,source_id,fingerprint,content) + values(p_owner,source,snapshot_hash,snapshot) + on conflict(source_id,fingerprint) do update set fingerprint=excluded.fingerprint returning id into source_version; + insert into public.context_documents(owner_id,subject_id,topic) values(p_owner,subject,'video_locator') on conflict do nothing; + select * into strict document from public.context_documents where owner_id=p_owner and subject_id=subject and topic='video_locator' for update; + insert into public.context_attempts(owner_id,request_id,module,attempt,status,provider,recipe_version,schema_version,started_at,finished_at,provider_cost_micros,provider_cost_status) + values(p_owner,r.id,'video_locator:'||subject,1,'succeeded','user_submission','youtube-video-url-v1','1',now(),now(),0,'confirmed') + on conflict(request_id,module,attempt) do update set finished_at=now() returning id into v_attempt; + 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,v_attempt,subject,'video_locator',snapshot_hash,'accepted','customer_assertion',snapshot,snapshot, + '{"extent":"partial","scope":"submitted_locator","metadataVerified":false}') returning id into result; + insert into public.context_result_sources(owner_id,result_id,source_version_id) values(p_owner,result,source_version); + if not public.accept_context_result(p_owner,document.id,result,document.revision) then raise exception 'Video locator acceptance conflict'; end if; + gaps:=jsonb_build_array( + jsonb_build_object('topic','video_metadata','status','uncollected','reason','Title, description and channel were not fetched.'), + jsonb_build_object('topic','uploader_attribution','status','unresolved','reason','The uploading channel is not assumed to be the artist, a performer or a credited artist.'), + jsonb_build_object('topic','recording_match','status','unresolved','reason','No recording, release or artist was matched or created for this video.'), + jsonb_build_object('topic','captions','status','uncollected','reason','Captions and transcripts were not collected; no lyrics were inferred.'), + jsonb_build_object('topic','media_version','status','unknown','reason','Original, live, remix or dubbed version is unknown.'), + jsonb_build_object('topic','video_narrative','status','unavailable','reason','Video analysis is not enabled; no narrative or visual interpretation was inferred.')); + update public.context_requests set status='partial',output=jsonb_build_object('subjectIds',jsonb_build_array(subject),'gaps',gaps),updated_at=now() + where id=r.id returning * into r; + return to_jsonb(r)-'claim_token'; +end $$; +revoke all on function public.create_context_video_request(uuid,uuid,text,text) from public,anon,authenticated; +grant execute on function public.create_context_video_request(uuid,uuid,text,text) to service_role; +commit; diff --git a/supabase/tests/README.md b/supabase/tests/README.md index 4c858db..51b3db8 100644 --- a/supabase/tests/README.md +++ b/supabase/tests/README.md @@ -1,5 +1,20 @@ # Context foundation tests +## Single-video locator entry + +After `20261010213100_context_video_entry.sql`, run `context_video_entry.sql` in a +disposable database transaction, or `python3 -m unittest discover -s tests -p +'test_context_video_entry.py'` from the repository root (local PostgreSQL on PATH; +on macOS export `LC_ALL=C` if `pg_ctl` reports a multithreaded postmaster). The +fixture saves one YouTube video as a `video` subject with a `video_locator` +customer assertion and six explicit gaps, then checks identifier validation, +same-key replay, key conflicts, a second video, workspace isolation, source +withdrawal and browser-role denial. It asserts no account, roster, song, song +identifier, artist, recording or release row is created and no song or artist +document is written. No provider is called. The chain applied in CI includes the +catalog and name/brief/text entry migrations so the `video` kind is checked against +the current subject constraints. + ## Brief snapshots After `20260926170000_context_brief_snapshots.sql`, run `context_brief_snapshots.sql` diff --git a/supabase/tests/context_video_entry.sql b/supabase/tests/context_video_entry.sql new file mode 100644 index 0000000..d0c0484 --- /dev/null +++ b/supabase/tests/context_video_entry.sql @@ -0,0 +1,124 @@ +-- Run inside a disposable database transaction and roll back all rows. +-- Covers the single-video YouTube locator entry: saved as an unresolved video subject, +-- scoped to one workspace, replayable by key, with no artist/recording/lyrics side effects. +do $$ +declare owner uuid:=gen_random_uuid(); outsider uuid:=gen_random_uuid(); video text:='AbCdEfGhI_1'; other text:='OtherIdAB_2'; video_input text; + req jsonb; again jsonb; second jsonb; foreign_req jsonb; docs jsonb; saved public.context_results; subject uuid; link public.context_resource_links; + accounts_before bigint; requests_before bigint; results_before bigint; attempts_before bigint; revision_before bigint; source uuid; +begin + insert into public.accounts(id,name) values(owner,'Video fixture owner'),(outsider,'Other workspace'); + select count(*) into accounts_before from public.accounts; + -- Eleven URL-safe characters are a valid shape; shorter, longer, spaced, empty and null are not. + foreach video_input in array array['short','AbCdEfGhI_12','not a video','',null] loop + begin + perform public.create_context_video_request(owner,owner,video_input,'bad'); + raise exception 'TEST_FAILURE: invalid video identifier accepted: %',coalesce(video_input,''); + exception when others then + if SQLERRM like 'TEST_FAILURE:%' or SQLERRM<>'Invalid YouTube video identifier' then raise; end if; + end; + end loop; + begin + perform public.create_context_video_request(owner,owner,'https://www.youtube.com/watch?v='||video,'bad-url'); + raise exception 'TEST_FAILURE: full URL accepted as identifier'; + exception when others then + if SQLERRM like 'TEST_FAILURE:%' or SQLERRM<>'Invalid YouTube video identifier' then raise; end if; + end; + + req:=public.create_context_video_request(owner,owner,video,'video-entry'); + if req->>'status'<>'partial' or req->'input'->>'kind'<>'video' or req->'input'->>'videoId'<>video + or req->'input'->>'identityConfirmed'<>'false' or req->'input'->>'url'<>'https://www.youtube.com/watch?v='||video + then raise exception 'Video locator was not saved as an unresolved partial request'; end if; + if req ? 'claim_token' then raise exception 'Claim token leaked'; end if; + if jsonb_array_length(req->'output'->'subjectIds')<>1 then raise exception 'Expected exactly one video subject'; end if; + subject:=(req->'output'->'subjectIds'->>0)::uuid; + if jsonb_array_length(req->'output'->'gaps')<>6 then raise exception 'Expected six explicit gaps'; end if; + if not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='uploader_attribution' and g->>'status'='unresolved') + or not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='recording_match' and g->>'status'='unresolved') + or not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='captions' and g->>'status'='uncollected') + or not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='video_metadata' and g->>'status'='uncollected') + or not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='media_version' and g->>'status'='unknown') + or not exists(select 1 from jsonb_array_elements(req->'output'->'gaps') g where g->>'topic'='video_narrative' and g->>'status'='unavailable') + then raise exception 'Gap states are not the expected distinct unresolved/uncollected/unknown/unavailable set'; end if; + + if not exists(select 1 from public.context_subjects s join public.context_resources r on r.id=s.resource_id + where s.id=subject and s.kind='video' and s.artist_id is null and s.song_isrc is null + and r.provider='youtube' and r.resource_kind='video' and r.provider_id=video) + then raise exception 'Video subject is not backed by the YouTube video resource'; end if; + select l.* into strict link from public.context_resource_links l join public.context_subjects s on s.id=l.subject_id + where l.subject_id=subject and l.relation='identity'; + if link.status<>'accepted' or link.evidence->>'source'<>'submitted_youtube_video_url' then raise exception 'Locator identity evidence missing'; end if; + if exists(select 1 from public.context_resource_links where subject_id=subject and relation in ('credited_artist','release_member')) + then raise exception 'Video was linked to an artist or release without evidence'; end if; + + select r.* into strict saved from public.context_results r where r.owner_id=owner and r.subject_id=subject and r.topic='video_locator'; + if saved.evidence_kind<>'customer_assertion' or saved.status<>'accepted' + or saved.normalized_response->>'metadataVerified'<>'false' or saved.normalized_response->>'uploaderIsArtist'<>'unknown' + or saved.normalized_response->>'recordingMatch'<>'unresolved' or saved.normalized_response->>'captions'<>'uncollected' + or saved.normalized_response->>'language'<>'unknown' or saved.normalized_response->>'mediaVersion'<>'unknown' + or saved.normalized_response ? 'title' or saved.normalized_response ? 'channel' or saved.normalized_response ? 'lyrics' + or saved.coverage->>'extent'<>'partial' or saved.coverage->>'scope'<>'submitted_locator' + then raise exception 'Video metadata, attribution or lyrics were invented'; end if; + if not exists(select 1 from public.context_attempts a where a.id=saved.attempt_id and a.provider='user_submission' + and a.provider_cost_micros=0 and a.provider_cost_status='confirmed' and a.recipe_version='youtube-video-url-v1') + then raise exception 'Locator attempt is not a zero-cost confirmed user submission'; end if; + + if (select count(*) from public.context_documents where owner_id=owner)<>1 + or not exists(select 1 from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator' and current_result_id=saved.id) + then raise exception 'Expected exactly one accepted video_locator document'; end if; + if exists(select 1 from public.context_documents where topic in ('lyrics','song_summary','artist_metadata','artist_brand','release_metadata','video_narrative','era','artwork_branding')) + then raise exception 'Song or artist documents were written from a video locator'; end if; + docs:=public.read_context_documents(owner,(req->>'id')::uuid); + if jsonb_array_length(docs)<>1 or docs->0->>'topic'<>'video_locator' or docs->0->>'evidenceKind'<>'customer_assertion' + or docs->0->>'coverage'<>'partial' or docs->0->>'subjectId'<>subject::text + then raise exception 'read_context_documents does not expose the single locator document'; end if; + + -- No artist, roster, recording or identifier rows were created by saving a video URL. + if (select count(*) from public.accounts)<>accounts_before then raise exception 'Accounts were created'; end if; + if (select count(*) from public.account_artist_ids)<>0 then raise exception 'Roster rows were created'; end if; + if (select count(*) from public.songs)<>0 or (select count(*) from public.song_identifiers)<>0 then raise exception 'Recording rows were created'; end if; + if exists(select 1 from public.context_subjects where kind in ('artist','recording','release')) then raise exception 'Artist, recording or release subjects were created'; end if; + + -- Replay with the same key and video returns the same request without new rows. + select count(*),(select count(*) from public.context_results),(select count(*) from public.context_attempts) + into requests_before,results_before,attempts_before from public.context_requests; + again:=public.create_context_video_request(owner,owner,video,'video-entry'); + if again->>'id'<>req->>'id' or again->>'status'<>'partial' then raise exception 'Replay created another request'; end if; + if (select count(*) from public.context_requests)<>requests_before or (select count(*) from public.context_results)<>results_before + or (select count(*) from public.context_attempts)<>attempts_before then raise exception 'Replay wrote new rows'; end if; + begin + perform public.create_context_video_request(owner,owner,other,'video-entry'); + raise exception 'TEST_FAILURE: conflicting idempotency key accepted'; + exception when others then + if SQLERRM like 'TEST_FAILURE:%' or SQLERRM<>'Idempotency key already used for different input' then raise; end if; + end; + + -- A second video for the same workspace is a distinct subject; the first document is untouched. + select revision into strict revision_before from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator'; + second:=public.create_context_video_request(owner,owner,other,'video-entry-2'); + if second->>'id'=req->>'id' or (second->'output'->'subjectIds'->>0)::uuid=subject then raise exception 'Second video reused the first subject'; end if; + if (select revision from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator')<>revision_before + then raise exception 'Second video rewrote the first locator document'; end if; + + -- Another workspace cannot read the request; its own save of the same video is scoped separately. + if public.read_context_request(outsider,(req->>'id')::uuid) is not null then raise exception 'Another workspace read the video request'; end if; + if jsonb_array_length(public.read_context_documents(outsider,(req->>'id')::uuid))<>0 then raise exception 'Another workspace read locator documents'; end if; + foreign_req:=public.create_context_video_request(outsider,outsider,video,'video-entry'); + if foreign_req->>'id'=req->>'id' or foreign_req->>'owner_id'<>outsider::text then raise exception 'Workspaces shared a request'; end if; + if (select count(*) from public.context_documents where subject_id=subject and topic='video_locator')<>2 + or (select count(*) from public.context_documents where owner_id=owner and subject_id=subject)<>1 + then raise exception 'Locator documents are not owner scoped'; end if; + if jsonb_array_length(public.read_context_documents(owner,(req->>'id')::uuid))<>1 then raise exception 'Owner read leaked across workspaces'; end if; + + -- Withdrawing the submitted source removes the locator from reads without deleting history. + select s.id into strict source from public.context_sources s where s.owner_id=owner and s.kind='customer' and s.source_url='https://www.youtube.com/watch?v='||video; + if not public.withdraw_context_source(owner,source) then raise exception 'Source withdrawal failed'; end if; + if jsonb_array_length(public.read_context_documents(owner,(req->>'id')::uuid))<>0 then raise exception 'Withdrawn locator still readable'; end if; + if jsonb_array_length(public.read_context_documents(outsider,(foreign_req->>'id')::uuid))<>1 then raise exception 'Withdrawal crossed workspaces'; end if; + + if pg_catalog.has_function_privilege('authenticated','public.create_context_video_request(uuid,uuid,text,text)','EXECUTE') + or pg_catalog.has_function_privilege('anon','public.create_context_video_request(uuid,uuid,text,text)','EXECUTE') + then raise exception 'Browser role can execute video context function'; end if; + if not pg_catalog.has_function_privilege('service_role','public.create_context_video_request(uuid,uuid,text,text)','EXECUTE') + then raise exception 'Service role cannot execute video context function'; end if; + raise notice 'PASS: context_video_entry'; +end $$; diff --git a/tests/test_context_video_entry.py b/tests/test_context_video_entry.py new file mode 100644 index 0000000..a0f4739 --- /dev/null +++ b/tests/test_context_video_entry.py @@ -0,0 +1,97 @@ +"""Single-video YouTube locator transactions on disposable PostgreSQL, without hosted credentials or provider calls.""" +import pathlib +import subprocess +import tempfile +import unittest + +ROOT = pathlib.Path(__file__).resolve().parents[1] +# The actual Context entry chain, so the video subject is checked against the current +# constraint set rather than only the original foundation. +MIGRATIONS = [ + '20260920010000_context_foundation.sql', + '20260920020000_context_spotify_pipeline.sql', + '20260922070000_context_catalog_entry.sql', + '20260924040000_context_release_entry.sql', + '20260925100000_context_songwriter_name_entry.sql', + '20260925110000_context_company_name_entry.sql', + '20260925120000_context_campaign_brief_entry.sql', + '20260925130000_context_supporting_text_entry.sql', + '20261010213100_context_video_entry.sql', +] +PORT = '52131' +FUNCTION = 'public.create_context_video_request(uuid,uuid,text,text)' + + +class ContextVideoEntry(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory(prefix='recoup-video-') + cls.addClassCleanup(cls.tmp.cleanup) + cls.cluster = pathlib.Path(cls.tmp.name) / 'pg' + subprocess.run(['initdb', '-D', str(cls.cluster), '-A', 'trust'], check=True, capture_output=True) + subprocess.run(['pg_ctl', '-D', str(cls.cluster), '-l', str(pathlib.Path(cls.tmp.name) / 'pg.log'), + '-o', f"-k {cls.tmp.name} -p {PORT} -c listen_addresses=''", '-w', 'start'], + check=True, capture_output=True) + cls.addClassCleanup(cls.stop) + cls.sql(''' + CREATE ROLE service_role BYPASSRLS; CREATE ROLE anon; CREATE ROLE authenticated; + CREATE SCHEMA storage; + CREATE TABLE storage.buckets(id text PRIMARY KEY,name text,public boolean,file_size_limit bigint); + CREATE TABLE storage.objects(id uuid PRIMARY KEY,bucket_id text); + CREATE TABLE public.accounts(id uuid PRIMARY KEY DEFAULT gen_random_uuid(),name text); + CREATE TABLE public.songs(isrc text PRIMARY KEY,name text,album text); + CREATE TABLE public.song_identifiers(song text,platform text,identifier_type text,value text); + CREATE TABLE public.account_artist_ids(account_id uuid,artist_id uuid); + CREATE TABLE public.catalogs(id uuid PRIMARY KEY,name text,updated_at timestamptz DEFAULT now()); + CREATE TABLE public.account_catalogs(account uuid,catalog uuid); + GRANT USAGE ON SCHEMA public TO service_role; + ''') + for migration in MIGRATIONS: + cls.sql((ROOT / 'supabase/migrations' / migration).read_text()) + + @classmethod + def stop(cls): + subprocess.run(['pg_ctl', '-D', str(cls.cluster), '-m', 'immediate', '-w', 'stop'], + check=True, capture_output=True) + + @classmethod + def sql(cls, sql): + result = subprocess.run(['psql', '-h', cls.tmp.name, '-p', PORT, '-d', 'postgres', + '-XAt', '-v', 'ON_ERROR_STOP=1'], + input=sql, text=True, capture_output=True) + if result.returncode: + raise AssertionError(result.stderr) + return result + + def test_video_locator_lifecycle_scope_and_side_effects(self): + fixture = (ROOT / 'supabase/tests/context_video_entry.sql').read_text() + result = self.sql('begin;\n' + fixture + '\nrollback;') + self.assertIn('PASS: context_video_entry', result.stderr) + + def test_fixture_rolled_back_and_no_rows_remain(self): + result = self.sql(''' + select (select count(*) from public.context_requests) + + (select count(*) from public.context_subjects) + + (select count(*) from public.context_documents) + + (select count(*) from public.accounts) + + (select count(*) from public.account_artist_ids) + + (select count(*) from public.songs) + + (select count(*) from public.song_identifiers); + ''') + self.assertEqual(result.stdout.strip(), '0') + + def test_browser_roles_cannot_execute(self): + result = self.sql(f''' + select pg_catalog.has_function_privilege('anon','{FUNCTION}','EXECUTE')::text + || ',' || pg_catalog.has_function_privilege('authenticated','{FUNCTION}','EXECUTE')::text + || ',' || pg_catalog.has_function_privilege('service_role','{FUNCTION}','EXECUTE')::text; + ''') + self.assertEqual(result.stdout.strip(), 'false,false,true') + + def test_video_kind_survives_current_subject_constraints(self): + result = self.sql(''' + select count(*) from pg_catalog.pg_constraint + where conname in ('context_subjects_kind_check','context_subjects_check') + and pg_catalog.pg_get_constraintdef(oid) like '%video%'; + ''') + self.assertEqual(result.stdout.strip(), '2') From 718a36f5c31d3aec516c456ca7cc1b84b54cc631 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 16:39:43 -0400 Subject: [PATCH 2/3] Check video locator rollback after the fixture actually runs The standalone row-count test ran alphabetically before the lifecycle fixture, so it always counted an empty database and could not catch a fixture that leaked rows. The check now runs inside the lifecycle test, immediately after the rolled-back fixture, and also counts resources, sources and results. Refs recoupable/app#2131 Co-Authored-By: Claude Opus 5.5 --- tests/test_context_video_entry.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/test_context_video_entry.py b/tests/test_context_video_entry.py index a0f4739..780e3a9 100644 --- a/tests/test_context_video_entry.py +++ b/tests/test_context_video_entry.py @@ -67,18 +67,20 @@ def test_video_locator_lifecycle_scope_and_side_effects(self): fixture = (ROOT / 'supabase/tests/context_video_entry.sql').read_text() result = self.sql('begin;\n' + fixture + '\nrollback;') self.assertIn('PASS: context_video_entry', result.stderr) - - def test_fixture_rolled_back_and_no_rows_remain(self): - result = self.sql(''' - select (select count(*) from public.context_requests) + # Checked after the fixture in the same test, so the rollback is actually exercised. + remaining = self.sql(''' + select (select count(*) from public.context_resources) + + (select count(*) from public.context_requests) + (select count(*) from public.context_subjects) + + (select count(*) from public.context_sources) + + (select count(*) from public.context_results) + (select count(*) from public.context_documents) + (select count(*) from public.accounts) + (select count(*) from public.account_artist_ids) + (select count(*) from public.songs) + (select count(*) from public.song_identifiers); ''') - self.assertEqual(result.stdout.strip(), '0') + self.assertEqual(remaining.stdout.strip(), '0') def test_browser_roles_cannot_execute(self): result = self.sql(f''' From 23262f99d2a6c010f00c459a4b1814d6623c3843 Mon Sep 17 00:00:00 2001 From: Sidney Swift <158200036+sidneyswift@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:42:17 -0400 Subject: [PATCH 3/3] Pin re-submitting the same video under a new idempotency key The fixture covered same-key replay, key conflicts, a second video and a second workspace, but not the most likely duplicate path: the same video in the same workspace with a fresh key. It now asserts that this reuses the subject, resource, source and document, appends exactly one request, attempt and accepted result, and advances the single locator document. Co-Authored-By: Claude Fable 5.1 --- supabase/tests/README.md | 4 +++- supabase/tests/context_video_entry.sql | 21 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/supabase/tests/README.md b/supabase/tests/README.md index 51b3db8..7b15635 100644 --- a/supabase/tests/README.md +++ b/supabase/tests/README.md @@ -8,7 +8,9 @@ disposable database transaction, or `python3 -m unittest discover -s tests -p on macOS export `LC_ALL=C` if `pg_ctl` reports a multithreaded postmaster). The fixture saves one YouTube video as a `video` subject with a `video_locator` customer assertion and six explicit gaps, then checks identifier validation, -same-key replay, key conflicts, a second video, workspace isolation, source +same-key replay, key conflicts, re-submission of the same video under a new key +(one subject, source and document; one more request, attempt and result), a +second video, workspace isolation, source withdrawal and browser-role denial. It asserts no account, roster, song, song identifier, artist, recording or release row is created and no song or artist document is written. No provider is called. The chain applied in CI includes the diff --git a/supabase/tests/context_video_entry.sql b/supabase/tests/context_video_entry.sql index d0c0484..8a4fcb4 100644 --- a/supabase/tests/context_video_entry.sql +++ b/supabase/tests/context_video_entry.sql @@ -3,7 +3,7 @@ -- scoped to one workspace, replayable by key, with no artist/recording/lyrics side effects. do $$ declare owner uuid:=gen_random_uuid(); outsider uuid:=gen_random_uuid(); video text:='AbCdEfGhI_1'; other text:='OtherIdAB_2'; video_input text; - req jsonb; again jsonb; second jsonb; foreign_req jsonb; docs jsonb; saved public.context_results; subject uuid; link public.context_resource_links; + req jsonb; again jsonb; resubmit jsonb; second jsonb; foreign_req jsonb; docs jsonb; saved public.context_results; subject uuid; link public.context_resource_links; accounts_before bigint; requests_before bigint; results_before bigint; attempts_before bigint; revision_before bigint; source uuid; begin insert into public.accounts(id,name) values(owner,'Video fixture owner'),(outsider,'Other workspace'); @@ -92,6 +92,25 @@ begin if SQLERRM like 'TEST_FAILURE:%' or SQLERRM<>'Idempotency key already used for different input' then raise; end if; end; + -- Re-submitting the same video with a new key reuses the subject, source and document: + -- it appends one request, attempt and accepted result and advances the single locator document. + select revision into strict revision_before from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator'; + resubmit:=public.create_context_video_request(owner,owner,video,'video-entry-resubmit'); + if resubmit->>'id'=req->>'id' or resubmit->>'status'<>'partial' or (resubmit->'output'->'subjectIds'->>0)::uuid<>subject + then raise exception 'Resubmission did not reuse the video subject in a new partial request'; end if; + if (select count(*) from public.context_requests)<>requests_before+1 or (select count(*) from public.context_attempts)<>attempts_before+1 + or (select count(*) from public.context_results)<>results_before+1 + then raise exception 'Resubmission did not append exactly one request, attempt and result'; end if; + if (select count(*) from public.context_subjects)<>1 or (select count(*) from public.context_resources)<>1 + or (select count(*) from public.context_sources where owner_id=owner)<>1 or (select count(*) from public.context_documents where owner_id=owner)<>1 + then raise exception 'Resubmission duplicated the subject, resource, source or document'; end if; + if not exists(select 1 from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator' + and revision=revision_before+1 and current_result_id<>saved.id) + then raise exception 'Resubmission did not advance the single locator document'; end if; + if (select count(*) from public.account_artist_ids)<>0 or (select count(*) from public.songs)<>0 + or exists(select 1 from public.context_documents where topic<>'video_locator') + then raise exception 'Resubmission created artist, recording or non-locator rows'; end if; + -- A second video for the same workspace is a distinct subject; the first document is untouched. select revision into strict revision_before from public.context_documents where owner_id=owner and subject_id=subject and topic='video_locator'; second:=public.create_context_video_request(owner,owner,other,'video-entry-2');