From 96450e2835054a9805c45643fd6564e3e140b52e Mon Sep 17 00:00:00 2001 From: Owen Date: Thu, 19 Nov 2026 15:20:44 -0700 Subject: [PATCH 1/2] Allow published meetings near cancelled schedule placeholders --- .github/workflows/ci.yml | 2 + docs/calendar-sync.md | 3 + sql/tests/test_calendar_sync.py | 60 +++++++ ...9150000_cancelled_calendar_placeholder.sql | 164 ++++++++++++++++++ 4 files changed, 229 insertions(+) create mode 100644 supabase/migrations/20261119150000_cancelled_calendar_placeholder.sql diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f8b3f8db..760d997c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -128,3 +128,5 @@ jobs: # baseline is fixed. - name: Lint new migrations run: .github/scripts/lint-migrations.sh "${{ github.event.pull_request.base.sha }}" + - name: Calendar identity SQL contracts + run: python3 -m unittest discover -s sql/tests -p test_calendar_sync.py -v diff --git a/docs/calendar-sync.md b/docs/calendar-sync.md index 575c9b66..e8a83379 100644 --- a/docs/calendar-sync.md +++ b/docs/calendar-sync.md @@ -37,6 +37,9 @@ lease prevents overlapping writes, and a replaced lease token cannot commit. Retries preserve IDs and slugs. A single exact date/type/organization/time match can bind an annual-schedule placeholder to an eSCRIBE GUID; multiple matches or possible nearby reschedules without an established identity are held for review. +Cancelled annual-schedule entries do not hold publication or document ingestion of +an independently published event on a nearby date; the cancelled record stays +separate. Active entries (including unknown status) still require reschedule review. Once established, the GUID wins over annual fallback dates. Distinct published GUIDs may share a date. Only explicit cancellation changes status; disappearance from a feed never cancels or deletes an event. diff --git a/sql/tests/test_calendar_sync.py b/sql/tests/test_calendar_sync.py index d91c0c22..db84e701 100644 --- a/sql/tests/test_calendar_sync.py +++ b/sql/tests/test_calendar_sync.py @@ -31,6 +31,7 @@ def setUp(self): """) self.sql(MIGRATION.read_text()) self.sql((MIGRATION.parent / "20261020162205_47_16_calendar_document_reconciliation.sql").read_text()) + self.sql((Path(__file__).resolve().parents[2] / 'supabase/migrations/20261119150000_cancelled_calendar_placeholder.sql').read_text()) self.date = self.sql("SELECT ((now() AT TIME ZONE 'America/Vancouver')::date+7)::text")[0] self.event = dict(source_type='official_schedule', source_id='reviewed-entry', meeting_date=self.date, title='Regular Council', type='Regular Council', organization_name='Council', @@ -133,3 +134,62 @@ def test_first_published_documents_after_event_date_reuse_calendar_record(self): self.sql("UPDATE meetings SET archive_path='archive/published',has_agenda=true WHERE id="+target) self.assertEqual(self.sql('SELECT id,slug FROM meetings')[0],before) self.assertEqual(self.sql('SELECT count(*) FROM meetings')[0],'1') + + def published_next_day(self, **changes): + moved = self.sql("SELECT ((now() AT TIME ZONE 'America/Vancouver')::date+8)::text")[0] + return {**self.event, 'source_type': 'escribe', 'source_id': 'new-published-guid', + 'source_url': 'https://pub-langford.escribemeetings.com/meetingscalendarview.aspx', + 'meeting_date': moved, 'start_time': '17:30', **changes} + + def test_cancelled_nearby_schedule_does_not_hide_new_published_meeting(self): + self.apply([self.event]) + feed = self.published_next_day() + result, _ = self.apply([feed]) + self.assertEqual(json.loads(result)['held'], 1) + # Release an already-discovered, unlinked source once the old date is cancelled. + self.apply([{**self.event, 'cancelled': True}]) + old = self.sql('SELECT row_to_json(m) FROM meetings m')[0] + result, _ = self.apply([feed]) + self.assertEqual(json.loads(result)['created'], 1) + self.assertEqual(json.loads(result)['held'], 0) + new_id = self.sql("SELECT ingested_meeting_id FROM source_meetings WHERE source_type='escribe'")[0] + self.assertEqual(self.sql(f"SELECT status,meeting_date,meta->'calendar'->>'start_time' FROM meetings WHERE id={new_id}")[0], + 'Planned|' + feed['meeting_date'] + '|17:30') + self.assertEqual(self.sql(f'SELECT row_to_json(m) FROM meetings m WHERE id<>{new_id}')[0], old) + result, _ = self.apply([feed]) + self.assertEqual(json.loads(result)['created'], 0) + self.assertEqual(self.sql('SELECT count(*) FROM meetings')[0], '2') + source_id = self.sql("SELECT id FROM source_meetings WHERE source_type='escribe'")[0] + self.assertEqual(self.sql(f'SELECT reconcile_calendar_source({source_id})')[0], new_id) + self.assertEqual(self.sql(f'SELECT row_to_json(m) FROM meetings m WHERE id<>{new_id}')[0], old) + + def insert_next_day_document_source(self): + return self.sql("""INSERT INTO source_meetings(municipality_id,source_type,source_id,meeting_date,title,meeting_type,raw,status) + VALUES(1,'escribe','new-documents',(now() AT TIME ZONE 'America/Vancouver')::date+8, + 'Council Meeting','Regular Council','{}','discovered') RETURNING id""")[0].splitlines()[0] + + def test_documents_near_cancelled_schedule_do_not_link_or_raise_reschedule_hold(self): + self.apply([{**self.event, 'cancelled': True}]) + old = self.sql('SELECT row_to_json(m) FROM meetings m')[0] + source_id = self.insert_next_day_document_source() + # NULL lets normal document ingestion create its own meeting; never reuse the cancellation. + self.assertEqual(self.sql(f'SELECT reconcile_calendar_source({source_id})')[0], '') + self.assertEqual(self.sql(f'SELECT ingested_meeting_id FROM source_meetings WHERE id={source_id}')[0], '') + self.assertEqual(self.sql('SELECT row_to_json(m) FROM meetings m')[0], old) + + def test_active_nearby_schedule_still_holds_calendar_and_documents_alongside_cancellation(self): + self.apply([{**self.event, 'cancelled': True}]) + active_date = self.sql("SELECT ((now() AT TIME ZONE 'America/Vancouver')::date+9)::text")[0] + self.apply([{**self.event, 'source_id': 'active-schedule', 'meeting_date': active_date}]) + document_source = self.insert_next_day_document_source() + for status in ['Planned', None]: + with self.subTest(status=status): + value = 'NULL' if status is None else "'Planned'" + self.sql(f"UPDATE meetings SET status={value} WHERE meeting_date='{active_date}'") + result, _ = self.apply([self.published_next_day()]) + self.assertEqual(json.loads(result)['held'], 1) + self.assertEqual(json.loads(result)['created'], 0) + _, error = self.sql(f'SELECT reconcile_calendar_source({document_source})', success=False) + self.assertIn('Possible calendar reschedule requires review before ingestion', error) + self.assertEqual(self.sql('SELECT count(*) FROM meetings')[0], '2') + self.assertEqual(self.sql("SELECT count(*) FROM source_meetings WHERE source_type='escribe' AND ingested_meeting_id IS NOT NULL")[0], '0') diff --git a/supabase/migrations/20261119150000_cancelled_calendar_placeholder.sql b/supabase/migrations/20261119150000_cancelled_calendar_placeholder.sql new file mode 100644 index 00000000..e9a51e7e --- /dev/null +++ b/supabase/migrations/20261119150000_cancelled_calendar_placeholder.sql @@ -0,0 +1,164 @@ +-- A cancelled annual-schedule placeholder must remain its own record, but must +-- not hold a separately published eSCRIBE event on a nearby date (Dec 7/8, 2026). +-- Keep exact-date matching, established identities and all active/unknown-status +-- reschedule safeguards unchanged. Replacing functions preserves their grants. +-- No existing meetings or source identities are changed by this migration. + +CREATE OR REPLACE FUNCTION public.apply_calendar_sync(p_token uuid, p_events jsonb, p_warnings jsonb DEFAULT '[]'::jsonb) RETURNS jsonb + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'public' + AS $_$ +DECLARE + muni bigint; item jsonb; source_row source_meetings%ROWTYPE; org bigint; target bigint; + candidates bigint; match_id bigint; event_date date; today date := (now() AT TIME ZONE 'America/Vancouver')::date; + created_count int:=0; updated_count int:=0; held_count int:=0; typ meeting_type; provenance jsonb; +BEGIN + SELECT municipality_id INTO STRICT muni FROM calendar_sync_state + WHERE token=p_token AND status='running' AND lease_until>now() FOR UPDATE; + IF coalesce(jsonb_typeof(p_events),'')<>'array' OR jsonb_array_length(p_events)>64 THEN + RAISE EXCEPTION 'Calendar batch exceeds allowed size'; + END IF; + FOR item IN SELECT value FROM jsonb_array_elements(p_events) LOOP + event_date := (item->>'meeting_date')::date; + IF coalesce(item->>'source_type','') NOT IN ('escribe','official_schedule') + OR coalesce(length(item->>'source_id'),0) NOT BETWEEN 1 AND 150 + OR coalesce(length(item->>'title'),0) NOT BETWEEN 1 AND 150 + OR coalesce(item->>'cancelled','') NOT IN ('true','false') + OR ((item->>'start_time') IS NOT NULL AND item->>'start_time' !~ '^([01][0-9]|2[0-3]):[0-5][0-9]$') + OR coalesce(item->>'type','') NOT IN ('Regular Council','Special Council','Inauguration','Committee of the Whole','Public Hearing','Advisory Committee') + OR coalesce(item->>'organization_name','') NOT IN ('Council','Community Advisory Committee','Sustainable Development Advisory Committee','Capital West Accessibility Advisory Committee') + OR coalesce(item->>'source_url','') NOT IN ( + 'https://pub-langford.escribemeetings.com/meetingscalendarview.aspx', + 'https://langford.ca/wp-content/uploads/2025/12/2026-Council-Year-Calendar-Council-Committees.pdf') + OR event_date IS NULL OR event_date>today+180 OR event_date>'type')::meeting_type; + SELECT id INTO org FROM organizations WHERE municipality_id=muni AND name=item->>'organization_name'; + IF org IS NULL THEN + INSERT INTO organizations(name,municipality_id,classification) + VALUES(item->>'organization_name',muni,'Committee') RETURNING id INTO org; + END IF; + -- Preserve documents/archive metadata and the source's existing public-record link. + INSERT INTO source_meetings(municipality_id,source_type,source_id,meeting_date,title,meeting_type,source_url,raw,status) + VALUES(muni,item->>'source_type',item->>'source_id',event_date,item->>'title',item->>'type',item->>'source_url', + jsonb_build_object('calendar',item),'scheduled') + ON CONFLICT(municipality_id,source_type,source_id) DO UPDATE SET + last_seen_at=now(),raw=source_meetings.raw||excluded.raw, + meeting_date=excluded.meeting_date,title=excluded.title,meeting_type=excluded.meeting_type, + source_url=coalesce(source_meetings.source_url,excluded.source_url) + RETURNING * INTO source_row; + target := source_row.ingested_meeting_id; + IF target IS NULL THEN + SELECT id INTO target FROM meetings WHERE calendar_source_id=source_row.id; + END IF; + IF target IS NOT NULL AND NOT EXISTS(SELECT 1 FROM meetings WHERE id=target AND municipality_id=muni) THEN + RAISE EXCEPTION 'Calendar source mapping crosses municipality'; + END IF; + IF target IS NOT NULL AND item->>'source_type'='official_schedule' AND EXISTS( + SELECT 1 FROM source_meetings WHERE ingested_meeting_id=target AND source_type='escribe') THEN + CONTINUE; -- Published identity always outranks the annual schedule, even after rescheduling. + END IF; + IF target IS NULL AND item->>'source_type'='escribe' THEN + -- Bind one future reviewed schedule entry to its published eSCRIBE identity. + -- Multiple same-day/source events are held, never collapsed by date/type alone. + SELECT count(*),min(m.id) INTO candidates,match_id FROM meetings m + JOIN source_meetings s ON s.id=m.calendar_source_id + WHERE m.municipality_id=muni AND m.organization_id=org AND m.type=typ + AND m.meeting_date=event_date AND s.source_type='official_schedule' + AND (m.meta->'calendar'->>'start_time' IS NULL OR item->>'start_time' IS NULL + OR m.meta->'calendar'->>'start_time'=item->>'start_time') + AND NOT EXISTS(SELECT 1 FROM source_meetings alias WHERE alias.ingested_meeting_id=m.id + AND alias.source_type='escribe' AND alias.source_id<>source_row.source_id); + IF candidates>1 OR (candidates=1 AND (SELECT count(*) FROM jsonb_array_elements(p_events) e + WHERE e->>'source_type'='escribe' AND e->>'meeting_date'=event_date::text + AND e->>'type'=typ::text AND e->>'organization_name'=item->>'organization_name')>1) THEN + held_count:=held_count+1; CONTINUE; + END IF; + IF candidates=1 THEN target:=match_id; END IF; + IF candidates=0 AND EXISTS(SELECT 1 FROM meetings m JOIN source_meetings s ON s.id=m.calendar_source_id + WHERE m.municipality_id=muni AND m.organization_id=org AND m.type=typ + AND s.source_type='official_schedule' AND abs(m.meeting_date-event_date)<=14 + AND m.status IS DISTINCT FROM 'Cancelled' + AND NOT EXISTS(SELECT 1 FROM source_meetings alias WHERE alias.ingested_meeting_id=m.id AND alias.source_type='escribe')) THEN + held_count:=held_count+1; CONTINUE; -- Possible reschedule before identity was established. + END IF; + END IF; + -- Avoid creating a schedule duplicate if a public processed record already exists + -- without a source mapping. This needs explicit reconciliation, not a blind merge. + IF target IS NULL AND EXISTS(SELECT 1 FROM meetings m LEFT JOIN source_meetings s ON s.id=m.calendar_source_id + WHERE m.municipality_id=muni AND m.organization_id=org AND m.meeting_date=event_date AND m.type=typ + AND (item->>'source_type'='official_schedule' OR m.calendar_source_id IS NULL OR s.source_type='official_schedule')) THEN + held_count:=held_count+1; CONTINUE; + END IF; + provenance:=jsonb_build_object('source_url',item->>'source_url','source_id',item->>'source_id', + 'source_type',item->>'source_type','verified_at',now(),'start_time',item->'start_time'); + IF target IS NULL THEN + INSERT INTO meetings(municipality_id,organization_id,title,meeting_date,type,status,calendar_source_id,meta) + VALUES(muni,org,item->>'title',event_date,typ,CASE WHEN (item->>'cancelled')::boolean THEN 'Cancelled' ELSE 'Planned' END, + source_row.id,jsonb_build_object('calendar',provenance)) RETURNING id INTO target; + created_count:=created_count+1; + ELSE + -- Calendar refresh cannot erase content, downgrade a completed meeting, or un-cancel one. + UPDATE meetings SET calendar_source_id=coalesce(calendar_source_id,source_row.id), + title=CASE WHEN archive_path IS NULL AND status='Planned' THEN item->>'title' ELSE title END, + type=CASE WHEN archive_path IS NULL AND status='Planned' THEN typ ELSE type END, + organization_id=CASE WHEN archive_path IS NULL AND status='Planned' THEN org ELSE organization_id END, + meta=coalesce(meta,'{}')||jsonb_build_object('calendar',provenance), + meeting_date=CASE WHEN archive_path IS NULL AND NOT coalesce(has_agenda,false) + AND NOT coalesce(has_minutes,false) AND NOT coalesce(has_transcript,false) THEN event_date ELSE meeting_date END, + status=CASE WHEN (item->>'cancelled')::boolean AND status='Planned' THEN 'Cancelled' ELSE status END + WHERE id=target AND municipality_id=muni; + updated_count:=updated_count+1; + END IF; + UPDATE source_meetings SET ingested_meeting_id=target WHERE id=source_row.id; + END LOOP; + provenance:=jsonb_build_object('created',created_count,'updated',updated_count,'held',held_count,'warnings',p_warnings); + UPDATE calendar_sync_state SET status='succeeded',finished_at=now(),lease_until=NULL,result=provenance,last_error=NULL + WHERE token=p_token; + RETURN provenance; +END $_$; + +CREATE OR REPLACE FUNCTION public.reconcile_calendar_source(p_source_meeting_id bigint) RETURNS bigint + LANGUAGE plpgsql SECURITY DEFINER + SET search_path TO 'public' + AS $$ +DECLARE source source_meetings%ROWTYPE; candidate bigint; matches bigint; siblings bigint; org_name text; +BEGIN + SELECT * INTO STRICT source FROM source_meetings WHERE id=p_source_meeting_id FOR UPDATE; + IF source.municipality_id<>(SELECT id FROM municipalities WHERE slug='langford') OR source.source_type<>'escribe' THEN RETURN NULL; END IF; + IF source.ingested_meeting_id IS NOT NULL THEN + IF NOT EXISTS(SELECT 1 FROM meetings WHERE id=source.ingested_meeting_id AND municipality_id=source.municipality_id) THEN + RAISE EXCEPTION 'Calendar source mapping crosses municipality'; + END IF; + RETURN source.ingested_meeting_id; + END IF; + org_name:=CASE WHEN source.meeting_type='Advisory Committee' THEN source.title ELSE 'Council' END; + SELECT count(*),min(m.id) INTO matches,candidate FROM meetings m + JOIN organizations o ON o.id=m.organization_id + WHERE m.municipality_id=source.municipality_id AND m.calendar_source_id IS NOT NULL + AND m.meeting_date=source.meeting_date AND m.type::text=source.meeting_type AND o.name=org_name + AND NOT EXISTS(SELECT 1 FROM source_meetings alias WHERE alias.ingested_meeting_id=m.id + AND alias.source_type='escribe' AND alias.id<>source.id); + SELECT count(*) INTO siblings FROM source_meetings s WHERE s.municipality_id=source.municipality_id + AND s.source_type='escribe' AND s.meeting_date=source.meeting_date AND s.meeting_type=source.meeting_type + AND (source.meeting_type<>'Advisory Committee' OR s.title=source.title); + IF matches>1 OR (matches=1 AND siblings>1) THEN + RAISE EXCEPTION 'Ambiguous published sources for calendar placeholder; review before ingestion'; + END IF; + IF matches=0 THEN + IF EXISTS(SELECT 1 FROM meetings m JOIN organizations o ON o.id=m.organization_id + JOIN source_meetings origin ON origin.id=m.calendar_source_id + WHERE m.municipality_id=source.municipality_id AND m.type::text=source.meeting_type + AND o.name=org_name AND abs(m.meeting_date-source.meeting_date)<=14 + AND origin.source_type='official_schedule' + AND m.status IS DISTINCT FROM 'Cancelled' + AND NOT EXISTS(SELECT 1 FROM source_meetings alias WHERE alias.ingested_meeting_id=m.id AND alias.source_type='escribe')) THEN + RAISE EXCEPTION 'Possible calendar reschedule requires review before ingestion'; + END IF; + RETURN NULL; + END IF; + PERFORM id FROM meetings WHERE id=candidate FOR UPDATE; + UPDATE source_meetings SET ingested_meeting_id=candidate WHERE id=source.id; + RETURN candidate; +END $$; From 512dd8678f42d91a1df193c3ff473a1dde6929e9 Mon Sep 17 00:00:00 2001 From: Owen Date: Thu, 19 Nov 2026 15:28:37 -0700 Subject: [PATCH 2/2] Refresh generated nullable Supabase auth declarations --- apps/web/app/db/schema.d.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/apps/web/app/db/schema.d.ts b/apps/web/app/db/schema.d.ts index fb6a0a47..83e1eff4 100644 --- a/apps/web/app/db/schema.d.ts +++ b/apps/web/app/db/schema.d.ts @@ -356,6 +356,7 @@ export interface AuthOneTimeTokens { created_at: Generated; expires_at: Timestamp | null; id: string; + link_token_hash: string | null; relates_to: string; token_hash: string; token_type: AuthOneTimeTokenType; @@ -378,6 +379,7 @@ export interface AuthRefreshTokens { export interface AuthSamlProviders { attribute_mapping: Json | null; created_at: Timestamp | null; + dedicated_scope: boolean | null; entity_id: string; id: string; metadata_url: string | null;