Skip to content
Draft
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
65 changes: 65 additions & 0 deletions proposals/catalog-snapshot-handoff-2207/PROTOCOL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
# Exact catalog source handoff (2207) — inactive proposal

This extends the existing disabled chat-fence/working-surface boundary. It is not
mutable surface saving, a Context identity grant, a migration, or live storage.
Requires actual 636 and durable-surfaces-2207 proposal definitions. No SQL was run.

The authenticated development producer preserves its original canonical query,
periods, pagination, membership and complete retained observation tuples before
projection. Each source version is the original catalog/ISRC/date/provider/run/hash/
retrieved-at/value tuple, **not** a Context UUID. Null corrections remain null.
The envelope remains server-only durable workflow output, outside schema-v1 Surface.

A default-off API step may hand it to this RPC only after required fenced assistant
persistence and before fence release. Original actor/session/chat/message/epoch/
owner/run, immutable source revision 1, exact source bytes and surface bytes are
bound. Under those locks, the assistant must have a `message_epochs` row matching
its message ID, chat ID and current/captured epoch. Missing, foreign-chat or older
generation anchors fail before the source authorizer and before identical receipt
replay. An exact duplicate insert acknowledged by 636 does not adopt an old anchor
into a newer writer generation. The receipt is source retention, never working
controls saved or approval.
Same writer/exact bytes is idempotent. Different source/surface at the anchor is a
40001 conflict, never an overwrite. Session/chat/fence/message locks serialize
concurrent attempts. Deletes cascade source records with their message anchor;
updates cannot change the source surface after retention.

Current authorization remains a real prerequisite: authorize_catalog_surface_source
ALWAYS denies. Before activation it must be replaced with an independently reviewed
fixed adapter checking actor/workspace/catalog membership AND every original
observation's retained identity/current withdrawal policy in the same transaction.
It cannot trust JSON, fingerprint, a prior workflow check, or today's latest rows.
Missing/mismatched/withdrawn lineage must deny without returning new values. The
existing retained-source family proposals may supply those checks after qualification;
this proposal does not manufacture accepted Context results or weaken them.

No roles receive EXECUTE. No producer registry or enrollment is activated. The
public wrapper is defined solely to freeze the future RPC shape; source tests with
synthetic RPCs are not database mechanics proof. Real PostgreSQL concurrent/stale/
withdrawal/anchor-delete tests and security review remain required before adoption.

Raw legacy history currently lacks current-source checks. This retention slice does
not fix historical disclosure or authorize a new read endpoint. A future working-
surface operation must bind its authority_binding to this exact source record,
reauthorize under the source lock order, and apply existing controls CAS/receipts.
Read/export/model/history integration and scoped UI handoff must be reviewed together.
No auto-retry on transport ambiguity, no latest lookup, no provider recollection,
no private-to-public fallback. Failure after message persistence may leave an
assistant message without a retained-source receipt; that is NOT durable working
state and must never be promoted to saved controls.

## Anchor generation repair validation

`test_source_boundary.py` checks the actual three-part generation guard and its
position before source authorization and replay (five static tests). The guard
regression failed on the original proposal and passes with this repair.

`test_anchor_generation.py` adds five deferred disposable-PostgreSQL cases: current
epoch retention plus exact replay, old-epoch reused-message refusal before a denying
authorizer, old-epoch refusal before an existing identical receipt, missing epoch,
and foreign-chat epoch. It reuses the actual 636 fixture and both proposal files;
the synthetic source authorizer is only a mechanics seam, never real source proof.
The cases default to skipped and were not executed for this source-only repair.
Only separately authorized SQL qualification may set
`CATALOG_RETENTION_SQL_QUALIFICATION=1` and run them. No grants or adapter replacement
from that disposable test setup belong in the proposal or an activation plan.
104 changes: 104 additions & 0 deletions proposals/catalog-snapshot-handoff-2207/proposal.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
-- SOURCE-ONLY PROPOSAL. Requires disabled 636 + durable-surfaces-2207 proposals.
-- No migrations, service grants, enrollment, activation or source-authority bypass.
BEGIN;
SET LOCAL ROLE recoup_chat_fence_owner;
CREATE TABLE chat_fence.catalog_surface_sources (
message_id text PRIMARY KEY REFERENCES public.chat_messages(id) ON DELETE CASCADE,
chat_id text NOT NULL REFERENCES chat_fence.state(chat_id),
workspace_id uuid NOT NULL,
source_revision bigint NOT NULL DEFAULT 1 CHECK (source_revision=1),
source_canonical text NOT NULL CHECK (octet_length(source_canonical)<=262144),
surface_canonical text NOT NULL CHECK (octet_length(surface_canonical)<=262144),
source_sha256 text NOT NULL,
surface_sha256 text NOT NULL
);
-- The exact original tuple list is evidence, not authority. Current owning rows
-- and actor/workspace/catalog/source policy must be checked under this transaction.
CREATE FUNCTION chat_fence.authorize_catalog_surface_source(p_account uuid,p_workspace uuid,p_source jsonb)
RETURNS void LANGUAGE plpgsql SET search_path='' AS $$ BEGIN
RAISE EXCEPTION 'catalog snapshot authority adapter unavailable' USING ERRCODE='0A000';
END $$;
RESET ROLE;
CREATE FUNCTION public.retain_catalog_surface_source(
p_chat text,p_account uuid,p_session text,p_epoch bigint,p_owner uuid,p_run text,
p_message text,p_expected_revision bigint,p_source text,p_surface text,
p_source_sha256 text,p_surface_sha256 text)
RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path='' AS $$
DECLARE s chat_fence.state; msg public.chat_messages;
prior chat_fence.catalog_surface_sources; source jsonb; surface jsonb; workspace uuid; part jsonb;
BEGIN
IF current_setting('transaction_isolation')<>'read committed' THEN
RAISE EXCEPTION 'READ COMMITTED required' USING ERRCODE='0A000'; END IF;
IF p_expected_revision IS DISTINCT FROM 0 OR p_source IS NULL OR p_surface IS NULL
OR octet_length(p_source)>262144 OR octet_length(p_surface)>262144
OR p_source_sha256 IS DISTINCT FROM encode(sha256(convert_to(p_source,'UTF8')),'hex')
OR p_surface_sha256 IS DISTINCT FROM encode(sha256(convert_to(p_surface,'UTF8')),'hex') THEN
RAISE EXCEPTION 'invalid snapshot binding' USING ERRCODE='22023'; END IF;
source:=p_source::jsonb; surface:=p_surface::jsonb;
IF source->>'mappingVersion' IS DISTINCT FROM 'catalog-streams-v1'
OR surface->>'schemaVersion' IS DISTINCT FROM '1' OR surface->'revision' IS DISTINCT FROM '1'::jsonb
OR jsonb_typeof(source->'lineage') IS DISTINCT FROM 'array' THEN
RAISE EXCEPTION 'invalid snapshot shape' USING ERRCODE='22023'; END IF;
IF jsonb_array_length(source->'lineage')=0 THEN
RAISE EXCEPTION 'lineage missing' USING ERRCODE='22023'; END IF;
workspace:=(source->>'workspaceId')::uuid;
IF workspace IS NULL OR surface->'context'->>'workspaceId' IS DISTINCT FROM workspace::text
OR surface->'context'->'subject'->>'kind' IS DISTINCT FROM 'catalog'
OR surface->'context'->'subject'->>'id' IS DISTINCT FROM source->'query'->>'catalog_id' THEN
RAISE EXCEPTION 'scope mismatch' USING ERRCODE='22023'; END IF;
-- Same session -> chat -> fence -> message -> source order as owning boundary.
PERFORM 1 FROM public.sessions WHERE id=p_session AND account_id=p_account FOR SHARE;
IF NOT FOUND THEN RAISE EXCEPTION 'unavailable' USING ERRCODE='42501'; END IF;
PERFORM 1 FROM public.chats WHERE id=p_chat AND session_id=p_session FOR UPDATE;
IF NOT FOUND THEN RAISE EXCEPTION 'unavailable' USING ERRCODE='42501'; END IF;
SELECT * INTO s FROM chat_fence.state WHERE chat_id=p_chat FOR UPDATE;
IF NOT FOUND THEN RAISE EXCEPTION 'fence unavailable' USING ERRCODE='55000'; END IF;
IF s.phase<>'running' OR s.epoch IS DISTINCT FROM p_epoch OR s.owner IS DISTINCT FROM p_owner
OR s.run_id IS DISTINCT FROM p_run THEN
RAISE EXCEPTION 'stale writer' USING ERRCODE='40001'; END IF;
SELECT * INTO msg FROM public.chat_messages WHERE id=p_message AND chat_id=p_chat FOR UPDATE;
IF NOT FOUND OR msg.role<>'assistant' THEN RAISE EXCEPTION 'unavailable' USING ERRCODE='P0002'; END IF;
-- A live writer cannot adopt an assistant persisted by an earlier generation.
IF NOT EXISTS(SELECT 1 FROM chat_fence.message_epochs WHERE message_id=msg.id AND chat_id=p_chat AND epoch=s.epoch) THEN RAISE EXCEPTION 'prior message generation' USING ERRCODE='40001'; END IF;
part:=chat_fence.surface_part(msg.parts);
IF part->'data' IS DISTINCT FROM surface THEN
RAISE EXCEPTION 'persisted snapshot differs' USING ERRCODE='40001'; END IF;
PERFORM chat_fence.authorize_catalog_surface_source(p_account,workspace,source);
SELECT * INTO prior FROM chat_fence.catalog_surface_sources WHERE message_id=p_message;
IF FOUND THEN
IF prior.chat_id<>p_chat OR prior.workspace_id<>workspace OR prior.source_canonical<>p_source
OR prior.surface_canonical<>p_surface THEN
RAISE EXCEPTION 'immutable source conflict' USING ERRCODE='40001'; END IF;
ELSE
INSERT INTO chat_fence.catalog_surface_sources(message_id,chat_id,workspace_id,source_canonical,surface_canonical,source_sha256,surface_sha256)
VALUES(p_message,p_chat,workspace,p_source,p_surface,p_source_sha256,p_surface_sha256);
END IF;
RETURN jsonb_build_object('message_id',p_message,'source_revision',1,'source_sha256',p_source_sha256,
'surface_sha256',p_surface_sha256,'retained',true);
END $$;
ALTER FUNCTION public.retain_catalog_surface_source(text,uuid,text,bigint,uuid,text,text,bigint,text,text,text,text) OWNER TO recoup_chat_fence_owner;
SET LOCAL ROLE recoup_chat_fence_owner;
CREATE FUNCTION chat_fence.guard_catalog_surface_source() RETURNS trigger
LANGUAGE plpgsql SET search_path='' AS $$
DECLARE saved chat_fence.catalog_surface_sources; part jsonb;
BEGIN
-- Existing 636 invoker guard owns refusal of direct legacy/service writers on
-- enrolled chats. Do not force unrelated unenrolled writes to read private state.
IF current_user<>'recoup_chat_fence_owner' THEN RETURN NEW; END IF;
SELECT * INTO saved FROM chat_fence.catalog_surface_sources WHERE message_id=OLD.id;
IF FOUND THEN
part:=chat_fence.surface_part(NEW.parts);
IF NEW.chat_id IS DISTINCT FROM saved.chat_id OR NEW.role IS DISTINCT FROM 'assistant'
OR part->'data' IS DISTINCT FROM saved.surface_canonical::jsonb THEN
RAISE EXCEPTION 'retained source is immutable' USING ERRCODE='40001'; END IF;
END IF;
RETURN NEW;
END $$;
RESET ROLE;
CREATE TRIGGER catalog_surface_source BEFORE UPDATE ON public.chat_messages
FOR EACH ROW EXECUTE FUNCTION chat_fence.guard_catalog_surface_source();
REVOKE ALL ON chat_fence.catalog_surface_sources FROM PUBLIC,anon,authenticated,service_role;
REVOKE ALL ON FUNCTION chat_fence.authorize_catalog_surface_source(uuid,uuid,jsonb) FROM PUBLIC,anon,authenticated,service_role;
REVOKE ALL ON FUNCTION chat_fence.guard_catalog_surface_source() FROM PUBLIC,anon,authenticated,service_role;
REVOKE ALL ON FUNCTION public.retain_catalog_surface_source(text,uuid,text,bigint,uuid,text,text,bigint,text,text,text,text) FROM PUBLIC,anon,authenticated,service_role;
COMMIT;
129 changes: 129 additions & 0 deletions proposals/catalog-snapshot-handoff-2207/test_anchor_generation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""Deferred PostgreSQL regression: opt-in disposable fixture, never a remote DSN.

Not run as part of the source-only repair. Requires separate SQL qualification
approval and CATALOG_RETENTION_SQL_QUALIFICATION=1. The proposal stays unchanged;
a synthetic authorizer exists only inside the disposable fixture.
"""
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import unittest

HERE = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location(
'catalog_fence_fixture', HERE.parent / 'chat-writer-fencing-636/test_protocol.py')
fence = importlib.util.module_from_spec(spec)
spec.loader.exec_module(fence)


@unittest.skipUnless(os.environ.get('CATALOG_RETENTION_SQL_QUALIFICATION') == '1',
'SQL qualification not enabled; source-only repair')
class AnchorGeneration(fence.Protocol):
@classmethod
def setUpClass(cls):
super().setUpClass()
cls.sql((HERE.parent / 'durable-surfaces-2207/proposal.sql').read_text())
cls.sql((HERE / 'proposal.sql').read_text())
# Verify the actual default-deny adapter before installing a synthetic seam.
try:
cls.sql(f"SET ROLE recoup_chat_fence_owner; SELECT chat_fence.authorize_catalog_surface_source('{fence.ACCOUNT}','{fence.ACCOUNT}','{{}}')")
except AssertionError as error:
if 'adapter unavailable' not in str(error):
raise
else:
raise AssertionError('default authorizer unexpectedly permitted')
cls.sql("""SET ROLE recoup_chat_fence_owner;
CREATE OR REPLACE FUNCTION chat_fence.authorize_catalog_surface_source(
p_account uuid,p_workspace uuid,p_source jsonb) RETURNS void
LANGUAGE plpgsql SET search_path='' AS $$ BEGIN
IF p_source->>'fixtureAuthorization' IS DISTINCT FROM 'allow' THEN
RAISE EXCEPTION 'fixture authority denied' USING ERRCODE='42501';
END IF;
END $$;
GRANT EXECUTE ON FUNCTION public.retain_catalog_surface_source(text,uuid,text,bigint,uuid,text,text,bigint,text,text,text,text) TO service_role;
""")

def setUp(self):
super().setUp()
self.token = self.bind(self.admit())
self.message_id = self.chat + 'message'
self.surface = {'schemaVersion': 1, 'id': 'synthetic-surface', 'revision': 1,
'context': {'workspaceId': fence.ACCOUNT,
'subject': {'kind': 'catalog', 'id': fence.OTHER}}}
self.part = {'type': 'data-intelligent-ui-snapshot',
'id': self.surface['id'], 'data': self.surface}
self.write(self.token, parts=[self.part])
self.source = {'mappingVersion': 'catalog-streams-v1',
'workspaceId': fence.ACCOUNT,
'query': {'catalog_id': fence.OTHER},
'lineage': [{'fixture': 'original-observation'}],
'fixtureAuthorization': 'allow'}

def retain(self, source=None):
source_bytes = json.dumps(self.source if source is None else source)
surface_bytes = json.dumps(self.surface)
digest = lambda value: hashlib.sha256(value.encode()).hexdigest()
args = [self.chat, fence.ACCOUNT, self.chat, self.token['epoch'],
self.token['owner'], self.token['run_id'], self.message_id, 0,
source_bytes, surface_bytes, digest(source_bytes), digest(surface_bytes)]
sql = 'SET ROLE service_role; SELECT public.retain_catalog_surface_source(' + ','.join(fence.quote(x) for x in args) + ')'
return json.loads(self.sql(sql))

def count_sources(self):
return self.sql('SELECT count(*) FROM chat_fence.catalog_surface_sources WHERE message_id=' + fence.quote(self.message_id))

def next_writer(self):
self.release(self.token)
self.token = self.bind(self.admit(self.token['epoch']), run='next-run')

def test_catalog_current_epoch_exact_replay(self):
receipt = self.retain()
self.assertEqual(receipt['message_id'], self.message_id)
self.assertEqual(receipt['source_revision'], 1)
self.assertTrue(receipt['retained'])
self.assertEqual(self.retain(), receipt)
self.assertEqual(self.count_sources(), '1')

def test_catalog_prior_epoch_reused_message_refused_before_authorizer(self):
self.next_writer()
# 636 insert mode can acknowledge identical bytes without adopting epoch.
self.write(self.token, parts=[self.part], mode='insert')
with self.assertRaisesRegex(AssertionError, 'prior message generation'):
self.retain({**self.source, 'fixtureAuthorization': 'deny'})
self.assertEqual(self.count_sources(), '0')

def test_catalog_prior_epoch_refused_before_identical_receipt_replay(self):
self.retain()
self.next_writer()
with self.assertRaisesRegex(AssertionError, 'prior message generation'):
self.retain()
self.assertEqual(self.count_sources(), '1')

def test_catalog_missing_generation_refused(self):
self.sql('DELETE FROM chat_fence.message_epochs WHERE message_id=' + fence.quote(self.message_id))
with self.assertRaisesRegex(AssertionError, 'prior message generation'):
self.retain()
self.assertEqual(self.count_sources(), '0')

def test_catalog_foreign_chat_generation_refused(self):
original_chat = self.chat
# Create another real fence row; corrupt only the fixture's anchor binding.
super().setUp()
self.sql('UPDATE chat_fence.message_epochs SET chat_id=' + fence.quote(self.chat) + ' WHERE message_id=' + fence.quote(self.message_id))
self.chat = original_chat
with self.assertRaisesRegex(AssertionError, 'prior message generation'):
self.retain()
self.assertEqual(self.count_sources(), '0')


def load_tests(loader, tests, pattern):
# Reuse fixture helpers without rerunning its unrelated inherited test suite.
return unittest.TestSuite(AnchorGeneration(name) for name in
loader.getTestCaseNames(AnchorGeneration)
if name.startswith('test_catalog_'))


if __name__ == '__main__':
unittest.main()
29 changes: 29 additions & 0 deletions proposals/catalog-snapshot-handoff-2207/test_source_boundary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Source guardrails only; does not execute SQL or qualify database behavior."""
import pathlib
import re
import unittest
SQL = pathlib.Path(__file__).with_name('proposal.sql').read_text()
class Boundary(unittest.TestCase):
def test_authorizer_denies_and_no_grants(self):
self.assertIn("adapter unavailable' USING ERRCODE='0A000'", SQL)
self.assertNotIn('GRANT EXECUTE', SQL)
self.assertIn('FROM PUBLIC,anon,authenticated,service_role', SQL)
def test_exact_fence_and_original_bytes(self):
for term in ['s.epoch IS DISTINCT FROM p_epoch', 's.owner IS DISTINCT FROM p_owner', 's.run_id IS DISTINCT FROM p_run', "s.phase<>'running'", 'prior.source_canonical<>p_source', 'prior.surface_canonical<>p_surface', "USING ERRCODE='40001'", 'part->\'data\' IS DISTINCT FROM surface']:
self.assertIn(term, SQL)
def test_lock_order(self):
terms=['FROM public.sessions WHERE', 'FROM public.chats WHERE', 'FROM chat_fence.state WHERE', 'FROM public.chat_messages WHERE', 'PERFORM chat_fence.authorize_catalog_surface_source']
self.assertEqual(sorted(SQL.index(t) for t in terms), [SQL.index(t) for t in terms])
def test_anchor_generation_before_authorization_and_replay(self):
guard = re.search(r"IF NOT EXISTS\(SELECT 1 FROM chat_fence\.message_epochs WHERE (.*?)\) THEN RAISE EXCEPTION 'prior message generation' USING ERRCODE='40001'; END IF;", SQL, re.S)
self.assertIsNotNone(guard, 'retention must reject an absent or foreign-generation anchor')
self.assertEqual(guard.group(1).split(), 'message_id=msg.id AND chat_id=p_chat AND epoch=s.epoch'.split())
self.assertLess(SQL.index('SELECT * INTO msg'), guard.start())
self.assertLess(guard.end(), SQL.index('PERFORM chat_fence.authorize_catalog_surface_source'))
self.assertLess(guard.end(), SQL.index('SELECT * INTO prior'))

def test_anchor_lifecycle(self):
self.assertIn('REFERENCES public.chat_messages(id) ON DELETE CASCADE', SQL)
self.assertIn('catalog_surface_source BEFORE UPDATE ON public.chat_messages', SQL)
self.assertIn("IF current_user<>'recoup_chat_fence_owner' THEN RETURN NEW", SQL)
if __name__ == '__main__': unittest.main()
Loading