From eec407850e57ba8b6ce89bb2fe5598d16772b17c Mon Sep 17 00:00:00 2001 From: twoimo Date: Sun, 25 Oct 2026 00:49:35 +0900 Subject: [PATCH] fix(mcp): cancel scoped knowledge reads on global abort --- .../knowledge-mcp-abort-20261025.md | 78 +++++++++++++ scripts/alden_collection.py | 32 +++++ scripts/alden_knowledge_mcp.py | 57 +++++---- scripts/alden_status_mcp.py | 7 +- tests/test_alden_knowledge_abort.py | 109 ++++++++++++++++++ 5 files changed, 259 insertions(+), 24 deletions(-) create mode 100644 docs/evaluation/knowledge-mcp-abort-20261025.md create mode 100644 tests/test_alden_knowledge_abort.py diff --git a/docs/evaluation/knowledge-mcp-abort-20261025.md b/docs/evaluation/knowledge-mcp-abort-20261025.md new file mode 100644 index 00000000..96433ebf --- /dev/null +++ b/docs/evaluation/knowledge-mcp-abort-20261025.md @@ -0,0 +1,78 @@ +# Cancellation of scoped knowledge reads + +The installed baseline returned graph and history payloads from a synthetic +collection while its global abort was latched. `CallToken` existed, but only search +received its callback; graph/history never checked it. Source authority and the +transport deadline are separate guards and did not close that gap. + +`KnowledgeServer` now checks the client control and global abort token before +source guards, before backend entry, on backend failure, and after backend return. +Abort/resume changes the epoch, so an older request stays cancelled. A recognized +global cancellation becomes the fixed MCP tool error `alden_global_abort`. +Unrecognized exceptions still become `metadata_unavailable`; neither exception +text, request reasons nor private source content is included. Metadata-only status +remains available for diagnosis. Client control/deadline handling stays with the +existing stdio transport. + +Graph/history pass a request cancellation callback through `read_action`. That +boundary owns a `ContextVar` scope, composes nested callbacks, and restores its +predecessor on success or failure. Nested read-only `CollectionStore.database` +connections inherit it and use the existing SQLite progress/cancellation handler. +Explicit connection callbacks compose with the inherited callback. Other workers +and later requests do not inherit a cancelled worker's scope. Writer connections +retain their existing explicit cancellation/publication contract. + +```mermaid +stateDiagram-v2 + [*] --> ValidatedScope + ValidatedScope --> Rejected: abort already latched or token invalid + ValidatedScope --> SourceGuards: token current + SourceGuards --> Backend: control and token rechecked + Backend --> ReadConnections: graph or history + ReadConnections --> Interrupted: callback stops SQLite progress + Backend --> Interrupted: search cancellation + Backend --> Rejected: abort or epoch change before returning result + ReadConnections --> CandidateResult: bounded read completes + CandidateResult --> Rejected: abort or epoch change at post-read check + CandidateResult --> PreparedResponse: control and token current + Interrupted --> FixedAbortError: global epoch cancelled + Interrupted --> ClientStop: client cancellation or deadline + PreparedResponse --> [*] + FixedAbortError --> [*] + Rejected --> FixedAbortError +``` + +This chart maps application checkpoints, not an atomic operation spanning the +SQLite read and stdout delivery. A cancellation arriving after the final check +can race with response serialization/delivery; this change does not prove an +all-process publication theorem or revoke bytes already delivered. SQLite checks +occur at the existing256-VM-instruction progress interval. Filesystem reads, +SQLite lock waits and pure Python work are not instantly preempted. No whole-app +latency, fairness or liveness result follows from these bounded tests. + +The new regressions cover pre-latched stop of all three backends before per-call +source guards, abort/resume during each backend, unchanged client-control behavior, +a real recursive SQLite query interrupted before it completes, worker/next-call +scope isolation, and exception privacy. They use temporary synthetic stores and +fake backend callbacks; no real user abort file, source DB or model is modified. +The actual installed baseline also returned graph/history data in a separate +synthetic public-protocol probe. Broad affected tests include collection reads, +source authority, retrieval, snapshots, entity overlays, details and the existing +MCP transport deadlines/EOF/cancel contracts. + +```sh +python3 -B -m unittest tests.test_alden_knowledge_abort tests.test_alden_knowledge_mcp tests.test_alden_status_mcp -v +``` + +The task-only integration decision remains separate. Installed Codex protocol +schemas expose no MCP/config setting on `thread/settings/update`; `thread/resume` +has a config field, and `config/mcpServer/reload` is a configuration-wide reload. +No resume, global config write or shared-server reload was attempted against the +active owner. Existing owned stdio reads remain authorized; persistent tool +registration limited to this live chat is unverified. The official App Server +documentation is https://learn.chatgpt.com/docs/app-server . + +Source binding, original negative/positive logs, installed stdio checks and +recovery evidence belong in the task output `task-scoped-mcp-20261025`. +Current-source external Pro/Gemini/reverse review remains incomplete under the +preserved upload gate. These tests and the statechart do not replace that review. diff --git a/scripts/alden_collection.py b/scripts/alden_collection.py index 6a5eb2a0..8c88162f 100644 --- a/scripts/alden_collection.py +++ b/scripts/alden_collection.py @@ -6,6 +6,7 @@ from __future__ import annotations from contextlib import contextmanager, nullcontext +from contextvars import ContextVar from alden_abort import AldenCancelled import fcntl import hashlib @@ -30,6 +31,25 @@ MAX_BATCH_RECORDS = 2000 BODY_NORMALIZATION_VERSION = "body-nfc-lines-v2" STAGES = {"discovered", "parsed", "validated", "stored", "published", "indexed", "failed", "paused"} +_READ_CANCELLATION = ContextVar('alden_collection_read_cancellation', default=None) + + +@contextmanager +def _read_cancellation(cancelled): + """Keep one request's cancellation on its nested read-only connections.""" + if cancelled is not None and not callable(cancelled): + raise ValueError('collection_cancellation_invalid') + outer = _READ_CANCELLATION.get() + current = outer if cancelled is None else cancelled if outer is None or outer is cancelled else lambda: outer() or cancelled() + token = _READ_CANCELLATION.set(current) + try: + if current is not None and current(): + raise AldenCancelled('collection_cancelled') + yield + if current is not None and current(): + raise AldenCancelled('collection_cancelled') + finally: + _READ_CANCELLATION.reset(token) def digest(value: bytes) -> str: @@ -617,6 +637,10 @@ def verify(): @contextmanager def database(self, *, publication_guard=None, cancelled=None): + if self.read_only: + inherited = _READ_CANCELLATION.get() + explicit = cancelled + cancelled = inherited if explicit is None else explicit if inherited is None or inherited is explicit else lambda: inherited() or explicit() require_collection_source_root(self.path.parents[2], self.source_access, self.source_revision) db = sqlite3.connect(self.path.as_uri() + "?mode=ro", uri=True, timeout=.15) if self.read_only else sqlite3.connect(self.path, timeout=.15) db.row_factory = sqlite3.Row @@ -1893,6 +1917,14 @@ def activity_page(self, *, projects: list[str], after=None, stream_id=None, limi def read_action(state_root: Path, action: str, query: str | None = None, *, + source_access=None, source_revision=None, cancelled=None) -> dict: + """Own cancellation across every nested read, including SQLite progress.""" + with _read_cancellation(cancelled): + return _read_action(state_root, action, query, + source_access=source_access, source_revision=source_revision) + + +def _read_action(state_root: Path, action: str, query: str | None = None, *, source_access=None, source_revision=None) -> dict: """Bounded read-only application boundary; never creates a store on lookup.""" if action not in {"collection-projects", "collection-history", "collection-graph"}: diff --git a/scripts/alden_knowledge_mcp.py b/scripts/alden_knowledge_mcp.py index 2e9b02a5..33fcedba 100644 --- a/scripts/alden_knowledge_mcp.py +++ b/scripts/alden_knowledge_mcp.py @@ -5,7 +5,7 @@ import sys import time -from alden_abort import ABORT_STATE_NAME, AbortToken +from alden_abort import ABORT_STATE_NAME, AbortToken, AldenCancelled from alden_collection import CollectionStore, read_action, require_collection_source_root from alden_collection_retrieval import retrieve from alden_status_mcp import StdioServer, _check @@ -113,31 +113,44 @@ def call_tool(self, params, control): _check(control) args, name = params['arguments'], params['name'] token = CallToken(self.root / ABORT_STATE_NAME, control) + def check(): + # Keep client cancellation/deadline distinct from the global epoch. + _check(control) + token.raise_if_cancelled() + check() cancelled = lambda: token.is_cancelled() or control is not None and control.stopped.is_set() guards = self._source_guards(cancelled) - if name.endswith('search'): - import auto_reply_knowledge_graph as kg - with kg.embedding_abort_scope(token): - result = retrieve(self.root, args['query'], projects=args['projects'], - max_entities=args.get('limit', 6), cancelled=cancelled, - **guards, search_strategy=self.search_strategy) - else: - action = 'collection-graph' if name.endswith('graph') else 'collection-history' - options = {'projects': args['projects'], 'limit': args.get('limit', 50)} - if 'after' in args: - options['after'] = args['after'] - if 'focus' in args: - options['focus'], options['hops'] = args['focus'], 1 - result = read_action(self.root, action, json.dumps(options), - source_access=guards['source_access'], source_revision=guards['source_revision']) - if action == 'collection-history': - # The UI catalog is global; MCP exposes only this request's projects. - requested = frozenset(args['projects']) - result = {**result, 'projects': [project for project in result['projects'] - if project['project'] in requested]} - _check(control) + check() + try: + if name.endswith('search'): + import auto_reply_knowledge_graph as kg + with kg.embedding_abort_scope(token): + result = retrieve(self.root, args['query'], projects=args['projects'], + max_entities=args.get('limit', 6), cancelled=cancelled, + **guards, search_strategy=self.search_strategy) + else: + action = 'collection-graph' if name.endswith('graph') else 'collection-history' + options = {'projects': args['projects'], 'limit': args.get('limit', 50)} + if 'after' in args: + options['after'] = args['after'] + if 'focus' in args: + options['focus'], options['hops'] = args['focus'], 1 + result = read_action(self.root, action, json.dumps(options), cancelled=cancelled, + source_access=guards['source_access'], source_revision=guards['source_revision']) + if action == 'collection-history': + # The UI catalog is global; MCP exposes only this request's projects. + requested = frozenset(args['projects']) + result = {**result, 'projects': [project for project in result['projects'] + if project['project'] in requested]} + except Exception: + check() + raise + check() return result + def tool_failure_code(self, error): + return 'alden_global_abort' if isinstance(error, AldenCancelled) else super().tool_failure_code(error) + def main(): parser = argparse.ArgumentParser(description=__doc__) diff --git a/scripts/alden_status_mcp.py b/scripts/alden_status_mcp.py index e6436714..8e58a16d 100644 --- a/scripts/alden_status_mcp.py +++ b/scripts/alden_status_mcp.py @@ -272,6 +272,9 @@ def valid_call(self, params): def call_tool(self, params, control): return self.collector.collect(control=control) if control is not None else self.collector.collect() + def tool_failure_code(self, error): + return 'metadata_unavailable' + def dispatch(self, request, control=None, *, validate_only=False): if not isinstance(request, dict) or request.get("jsonrpc") != "2.0": return _error(None, -32600, "Invalid request") @@ -312,10 +315,10 @@ def dispatch(self, request, control=None, *, validate_only=False): _check(control) except CallStopped: raise - except Exception: + except Exception as error: # A collector bug must never export raw exception text or paths. return {"jsonrpc": "2.0", "id": identifier, - "result": {"content": [{"type": "text", "text": "metadata_unavailable"}], "isError": True}} + "result": {"content": [{"type": "text", "text": self.tool_failure_code(error)}], "isError": True}} result = {"content": [{"type": "text", "text": json.dumps(content, separators=(",", ":"), allow_nan=False)}], "isError": False} else: return _error(identifier, -32601, "Method not found") diff --git a/tests/test_alden_knowledge_abort.py b/tests/test_alden_knowledge_abort.py new file mode 100644 index 00000000..2d9bd18c --- /dev/null +++ b/tests/test_alden_knowledge_abort.py @@ -0,0 +1,109 @@ +"""Synthetic-only cancellation of scoped MCP reads, including SQLite work.""" +from concurrent.futures import ThreadPoolExecutor +import json +from pathlib import Path +import sys +from tempfile import TemporaryDirectory +import unittest +from unittest.mock import patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'scripts')) +from alden_abort import AbortController +from alden_collection import CollectionStore, read_action +import alden_knowledge_mcp as knowledge +from alden_status_mcp import CallControl, CallStopped + + +class KnowledgeAbortTests(unittest.TestCase): + def setUp(self): + temp = TemporaryDirectory(prefix='alden-mcp-abort-') + self.addCleanup(temp.cleanup) + self.root = Path(temp.name).resolve() + self.store = CollectionStore(self.root) + target = self.store.register(platform='graph', original_id='synthetic', kind='source', + label='Synthetic source', projects=['qa']) + self.store.ingest(target, [{'original_id':'canary', 'label':'Synthetic item', + 'text':'PRIVATE_CANCEL_CANARY'}]) + self.server = knowledge.KnowledgeServer(self.root, ['qa']) + self.server.dispatch({'jsonrpc':'2.0', 'id':1, 'method':'initialize', 'params':{ + 'protocolVersion':'2025-11-25', 'capabilities':{}, 'clientInfo':{}}}) + self.server.dispatch({'jsonrpc':'2.0', 'method':'notifications/initialized'}) + self.abort = AbortController(self.root) + + def request(self, tool): + args = {'projects':['qa'], 'limit':2} + if tool == 'search': args['query'] = 'canary' + return {'jsonrpc':'2.0', 'id':2, 'method':'tools/call', 'params':{ + 'name':'alden_knowledge_' + tool, 'arguments':args}} + + def assert_aborted(self, result): + self.assertTrue(result['result']['isError'], result) + self.assertEqual(result['result']['content'], [{'type':'text', 'text':'alden_global_abort'}]) + self.assertNotIn('PRIVATE_CANCEL_CANARY', json.dumps(result)) + + def test_latched_abort_stops_all_backends_before_source_guard_or_read(self): + self.abort.abort('PRIVATE_CANCEL_CANARY') + with patch.object(knowledge, 'read_action') as read, patch.object(knowledge, 'retrieve') as retrieve, \ + patch.object(self.server, '_source_guards', wraps=self.server._source_guards) as guards: + for tool in ['graph', 'history', 'search']: + with self.subTest(tool=tool): + self.assert_aborted(self.server.dispatch(self.request(tool))) + read.assert_not_called(); retrieve.assert_not_called(); guards.assert_not_called() + + def test_abort_and_resume_during_any_backend_cannot_publish_its_old_result(self): + def late(*args, **kwargs): + self.abort.abort('PRIVATE_CANCEL_CANARY') + self.abort.resume_after_human_action() + return {'nodes':['PRIVATE_CANCEL_CANARY'], 'items':['PRIVATE_CANCEL_CANARY']} + with patch.object(knowledge, 'read_action', side_effect=late), patch.object(knowledge, 'retrieve', side_effect=late): + for tool in ['graph', 'history', 'search']: + with self.subTest(tool=tool): + self.assert_aborted(self.server.dispatch(self.request(tool))) + self.assertIn('result', self.server.dispatch({'jsonrpc':'2.0','id':3,'method':'ping'})) + + def test_client_control_stop_retains_its_existing_transport_contract(self): + control = CallControl(10) + def late(*args, **kwargs): + control.stop() + return {'nodes':['PRIVATE_CANCEL_CANARY']} + with patch.object(knowledge, 'read_action', side_effect=late): + with self.assertRaises(CallStopped): + self.server.dispatch(self.request('graph'), control) + + def test_nested_read_connection_interrupts_sqlite_before_query_finishes(self): + polls = []; finished = [] + def cancelled(): + polls.append(None) + return len(polls) >= 80 + def expensive(store, **kwargs): + with store.database() as db: + db.execute('''WITH RECURSIVE n(x) AS (VALUES(0) UNION ALL + SELECT x+1 FROM n WHERE x<1000000) SELECT sum(x) FROM n''').fetchone() + finished.append(True) + return {'nodes':[], 'edges':[]} + with patch.object(CollectionStore, 'graph_page', expensive): + with self.assertRaisesRegex(RuntimeError, 'collection_cancelled'): + read_action(self.root, 'collection-graph', '{"projects":["qa"]}', cancelled=cancelled) + self.assertFalse(finished, 'post-return cancellation alone would let the SQL finish') + self.assertGreaterEqual(len(polls), 80) + self.assertTrue(read_action(self.root, 'collection-graph', '{"projects":["qa"]}')['nodes']) + + def test_cancel_scope_does_not_leak_to_another_worker_or_next_call(self): + def aborted(): + with self.assertRaisesRegex(RuntimeError, 'collection_cancelled'): + read_action(self.root, 'collection-history', '{"projects":["qa"]}', cancelled=lambda:True) + return read_action(self.root, 'collection-history', '{"projects":["qa"]}') + with ThreadPoolExecutor(max_workers=2) as workers: + first = workers.submit(aborted) + second = workers.submit(read_action, self.root, 'collection-graph', '{"projects":["qa"]}') + self.assertTrue(first.result()['items']) + self.assertTrue(second.result()['nodes']) + + def test_unknown_backend_error_still_cannot_export_its_message(self): + with patch.object(knowledge, 'read_action', side_effect=RuntimeError('PRIVATE_CANCEL_CANARY')): + result = self.server.dispatch(self.request('graph')) + self.assertTrue(result['result']['isError']) + self.assertEqual(result['result']['content'], [{'type':'text','text':'metadata_unavailable'}]) + + +if __name__ == '__main__': unittest.main()