From 318f60f0f6ee64cf8ee09f0818521f640e7d0707 Mon Sep 17 00:00:00 2001 From: Hsukqi Lee Date: Tue, 17 Nov 2026 10:21:23 +0800 Subject: [PATCH] fix: preserve paper identity and validate delivery receipts --- fastinsight/pipeline.py | 5 -- scripts/auto_pipeline.py | 41 +++++------ scripts/publish_receipt.py | 12 ++++ scripts/publish_to_research.py | 6 +- tests/http_world.py | 115 ++++++++++++++++++++++++++++++ tests/test_delivery.py | 71 ++++++++++++++++++ tests/transport/http_transport.py | 17 +++++ tests/transport/sitecustomize.py | 10 +++ 8 files changed, 248 insertions(+), 29 deletions(-) create mode 100644 scripts/publish_receipt.py create mode 100644 tests/http_world.py create mode 100644 tests/test_delivery.py create mode 100644 tests/transport/http_transport.py create mode 100644 tests/transport/sitecustomize.py diff --git a/fastinsight/pipeline.py b/fastinsight/pipeline.py index b14c97e..3757b89 100644 --- a/fastinsight/pipeline.py +++ b/fastinsight/pipeline.py @@ -309,11 +309,6 @@ def confirmation_text(result: Dict[str, Any]) -> str: direction = " / ".join(direction_names) or str(route.get("matched_direction") or "").strip() or "未分类" delivered = result.get("delivered") or [] names: List[str] = [] - for owner in route.get("owners") or []: - if isinstance(owner, dict) and owner.get("name"): - name = str(owner["name"]).strip() - if name and name not in names: - names.append(name) for item in delivered: if not isinstance(item, dict): continue diff --git a/scripts/auto_pipeline.py b/scripts/auto_pipeline.py index 7f6d507..16bc524 100644 --- a/scripts/auto_pipeline.py +++ b/scripts/auto_pipeline.py @@ -22,6 +22,7 @@ sys.path.insert(0, str(ROOT)) from text_clip import compose_research_summary, prefer_abstract from service_auth import service_configuration, service_token +from publish_receipt import validate_publish_receipt ROSTER_DEFAULT = ROOT.parent / "assets" / "colleagues.yaml" @@ -54,30 +55,28 @@ def _verification_query(paper, title): return " ".join(piece for piece in pieces if piece) -def _merge_web_fallback(existing, fallback): - """Keep screenshot/link metadata and enrich gaps from a web-search hit.""" - merged = dict(existing) - existing_url = _text(merged.get("url")) - score = fallback.get("match_score") +def _accepted_candidate(candidate): + if candidate.get("exact"): + return True try: - strong_match = float(score or 0) >= 0.6 + return 0.6 <= float(candidate.get("match_score") or 0) <= 1.0 except (TypeError, ValueError): - strong_match = False + return False + + +def _merge_web_fallback(existing, fallback): + """Fetching a candidate does not grant it authority over the supplied paper.""" + merged = dict(existing) + if not _accepted_candidate(fallback): + merged["verification_note"] = "unconfirmed search candidate; supplied paper metadata retained" + return merged page_fetched = bool(fallback.get("page_fetched")) - for key in ("url", "url_kind"): - value = fallback.get(key) - if value is None or value == "": - continue - if not existing_url or strong_match or page_fetched: - merged[key] = value - for key in ("provider", "match_score", "web_search_result"): + for key in ("url", "url_kind", "provider", "match_score", "web_search_result"): value = fallback.get(key) if value is not None and value != "": merged[key] = value if page_fetched: - # A successfully fetched page is the source of truth for metadata: - # use the title/authors/venue/year found on the page. Abstracts still - # prefer an official paper abstract over a search snippet. + # Only an accepted candidate may replace supplied metadata. for key in ("title", "authors", "year", "venue", "doi", "arxiv_id"): if _text(fallback.get(key)): merged[key] = fallback[key] @@ -144,7 +143,7 @@ def _publish(endpoint, ingest_key, person, paper, trends, direction, *, cas_conf method="POST", ) with urllib.request.urlopen(request, timeout=20) as response: - return json.loads(response.read().decode("utf-8")) + return validate_publish_receipt(json.loads(response.read().decode("utf-8"))) def _normalize_paper(paper): @@ -163,13 +162,9 @@ def _apply_verification(paper, verified): if not isinstance(verified, dict) or not isinstance(verified.get("best"), dict): return paper best = verified["best"] - try: - score = float(best.get("match_score") or 0) - except (TypeError, ValueError): - score = 0.0 academic_confirmed = bool( verified.get("verified_by_academic_sources") - and (best.get("exact") or score >= 0.6) + and _accepted_candidate(best) ) if academic_confirmed: return best diff --git a/scripts/publish_receipt.py b/scripts/publish_receipt.py new file mode 100644 index 0000000..e439973 --- /dev/null +++ b/scripts/publish_receipt.py @@ -0,0 +1,12 @@ +"""The FastResearch publish response contract shared by both publishing entries.""" + + +def validate_publish_receipt(receipt): + if not isinstance(receipt, dict) or receipt.get("ok") is not True: + raise ValueError("FastResearch publish receipt must be an object with ok=true") + names = receipt.get("deliveredTo") + if not isinstance(names, list) or not names or any( + not isinstance(name, str) or not name.strip() for name in names + ): + raise ValueError("FastResearch publish receipt requires a nonempty deliveredTo list of names") + return receipt diff --git a/scripts/publish_to_research.py b/scripts/publish_to_research.py index 8cf0440..ba9b9fa 100644 --- a/scripts/publish_to_research.py +++ b/scripts/publish_to_research.py @@ -11,6 +11,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from text_clip import compose_research_summary, normalize_ws from service_auth import service_configuration, service_token +from publish_receipt import validate_publish_receipt def normalize(value): @@ -106,11 +107,14 @@ def main(): ) try: with urllib.request.urlopen(request, timeout=15) as response: - print(response.read().decode("utf-8", "replace")) + receipt = validate_publish_receipt(json.loads(response.read().decode("utf-8"))) + print(json.dumps(receipt, ensure_ascii=False)) except urllib.error.HTTPError as error: raise SystemExit( f"FastResearch 发布失败 ({error.code}): {error.read().decode('utf-8', 'replace')}" ) + except ValueError as error: + raise SystemExit(f"FastResearch 发布失败:{error}") if __name__ == "__main__": diff --git a/tests/http_world.py b/tests/http_world.py new file mode 100644 index 0000000..7d29b03 --- /dev/null +++ b/tests/http_world.py @@ -0,0 +1,115 @@ +import json +import os +import tempfile +import threading +import urllib.parse +import urllib.request +from contextlib import ExitStack +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from unittest.mock import patch + +from tests.transport.http_transport import route_urlopen + + +class HTTPWorld: + """External academic/search/model/Research protocols; production internals stay real.""" + def __init__(self): + self.title = "Unrelated astronomy observations" + self.receipts = {} + self.published = [] + self.requests = [] + self.model_entered = threading.Event() + self.model_release = threading.Event() + self.model_release.set() + world = self + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *args): + pass + + def do_GET(self): + self.respond() + + def do_POST(self): + self.respond() + + def respond(self): + target = self.headers.get("X-Fixture-Url", self.path) + path = urllib.parse.urlsplit(target).path + body = self.rfile.read(int(self.headers.get("Content-Length", "0"))) + world.requests.append(target) + status, content_type = 200, "application/json" + if path.endswith("/chat/completions"): + world.model_entered.set() + if not world.model_release.wait(10): + status, value = 500, {"error": "fixture model was not released"} + else: + value = {"choices": [{"message": {"content": "A fixture trend summary."}}]} + elif path == "/api/insight/publish": + payload = json.loads(body) + world.published.append(payload) + value = world.receipts.get(payload.get("person"), { + "ok": True, "deliveredTo": [payload.get("person", "A")], + }) + elif "serpapi.com" in target: + value = {"organic_results": [{"title": world.title, + "link": "https://papers.example/discovered", "snippet": "Search abstract"}]} + elif "papers.example" in target: + content_type = "text/html" + value = (f'' + '' + '' + '') + elif "api.crossref.org" in target: + value = {"message": {"items": []}} + elif "api.openalex.org" in target: + value = {"results": []} + elif "semanticscholar.org" in target: + value = {"data": []} + elif "arxiv.org" in target: + content_type, value = "application/atom+xml", '' + else: + status, value = 404, {"error": "unrecorded external URL"} + encoded = (json.dumps(value) if content_type == "application/json" else value).encode() + self.send_response(status) + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(encoded))) + self.end_headers() + self.wfile.write(encoded) + + self.server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + self.origin = f"http://127.0.0.1:{self.server.server_port}" + + def __enter__(self): + self.stack = ExitStack() + directory = self.stack.enter_context(tempfile.TemporaryDirectory(prefix="insight-http-")) + self.root = Path(directory) + self.roster = self.root / "roster.yaml" + self.roster.write_text('directions:\n - name: "Firmware"\n keywords: ["firmware"]\n' + ' owners:\n - name: "A"\n - name: "B"\n' + 'default_owner:\n name: "A"\n', encoding="utf-8") + transport = str(Path(__file__).parent / "transport") + self.stack.enter_context(patch.dict(os.environ, { + "FASTINSIGHT_FIXTURE_ORIGIN": self.origin, + "PYTHONPATH": transport + os.pathsep + os.environ.get("PYTHONPATH", ""), + "FASTINSIGHT_ROSTER": str(self.roster), "FASTRESEARCH_URL": self.origin, + "FASTINSIGHT_INGEST_KEY": "fixture-key", "FASTINSIGHT_ALLOW_LEGACY_INGEST_KEY": "true", + "FASTINSIGHT_FASTCAS_ISSUER": "", "FASTINSIGHT_FASTCAS_CLIENT_ID": "", + "FASTINSIGHT_FASTCAS_CLIENT_SECRET": "", "OPENAI_API_KEY": "fixture-key", + "OPENAI_BASE_URL": self.origin, "SERPAPI_API_KEY": "fixture-key", + "BING_SEARCH_API_KEY": "", "GOOGLE_SEARCH_API_KEY": "", + "PYTHONUTF8": "1", "FEISHU_APP_ID": "fixture-app", "FEISHU_APP_SECRET": "fixture-secret", + "FEISHU_BOT_OPEN_ID": "ou_fixture", "FASTINSIGHT_STATE_DIR": str(self.root), + })) + self.stack.enter_context(patch("urllib.request.urlopen", route_urlopen(urllib.request.urlopen, self.origin))) + self.thread = threading.Thread(target=self.server.serve_forever, daemon=True) + self.thread.start() + return self + + def __exit__(self, *args): + self.model_release.set() + self.server.shutdown() + self.thread.join() + self.server.server_close() + self.stack.close() diff --git a/tests/test_delivery.py b/tests/test_delivery.py new file mode 100644 index 0000000..d785275 --- /dev/null +++ b/tests/test_delivery.py @@ -0,0 +1,71 @@ +import json +import subprocess +import sys +import unittest +from pathlib import Path + +from fastinsight.pipeline import confirmation_text, process_paper +from tests.http_world import HTTPWorld + + +PAPER = {"title": "Known firmware paper", "url": "https://doi.org/10.1000/known", + "doi": "10.1000/known", "abstract": "Original firmware abstract"} + + +class DeliveryScenarios(unittest.TestCase): + def test_unrelated_fetched_page_preserves_supplied_paper_through_publication(self): + with HTTPWorld() as world: + result = process_paper(PAPER) + self.assertTrue(any("papers.example" in url for url in world.requests)) + self.assertEqual(result["paper"]["title"], PAPER["title"]) + self.assertEqual(result["paper"]["doi"], PAPER["doi"]) + self.assertEqual(result["paper"]["abstract"], PAPER["abstract"]) + self.assertEqual(len(world.published), 2) + for item in world.published: + self.assertEqual(item["item"]["url"], PAPER["url"]) + self.assertEqual(item["item"]["title"], PAPER["title"]) + + def test_accepted_page_can_still_enrich_a_paper(self): + with HTTPWorld() as world: + world.title = PAPER["title"] + result = process_paper({"title": PAPER["title"]}) + self.assertEqual(result["paper"]["url"], "https://papers.example/discovered") + self.assertEqual(len(result["delivered"]), 2) + + def test_partial_success_names_only_confirmed_receivers(self): + with HTTPWorld() as world: + world.receipts["B"] = {"ok": False, "deliveredTo": []} + result = process_paper(PAPER) + self.assertEqual(len(result["delivered"]), 1) + self.assertEqual(len(result["errors"]), 1) + text = confirmation_text(result) + self.assertIn("@A", text) + self.assertNotIn("@B", text) + + def test_malformed_2xx_receipts_do_not_count_as_success(self): + bad = [[], None, {"ok": False, "deliveredTo": ["A"]}, + {"ok": 1, "deliveredTo": ["A"]}, {"ok": True}, + {"ok": True, "deliveredTo": []}, {"ok": True, "deliveredTo": "A"}, + {"ok": True, "deliveredTo": [""]}, {"ok": True, "deliveredTo": [{}]}] + with HTTPWorld() as world: + for receipt in bad: + with self.subTest(receipt=receipt): + world.receipts = {"A": receipt, "B": receipt} + result = process_paper(PAPER) + self.assertEqual(result["delivered"], []) + self.assertEqual(len(result["errors"]), 2) + self.assertNotIn("✅", confirmation_text(result)) + + def test_cli_uses_same_receipt_contract(self): + with HTTPWorld() as world: + paper = world.root / "paper.json" + paper.write_text(json.dumps(PAPER), encoding="utf-8") + command = [sys.executable, str(Path(__file__).resolve().parents[1] / "scripts" / "publish_to_research.py"), + "--paper", str(paper), "--person", "A", "--trend-text", "A fixture trend."] + world.receipts["A"] = {"ok": False, "deliveredTo": []} + rejected = subprocess.run(command, capture_output=True, text=True, timeout=10) + self.assertNotEqual(rejected.returncode, 0) + world.receipts["A"] = {"ok": True, "deliveredTo": ["A"]} + accepted = subprocess.run(command, capture_output=True, text=True, timeout=10) + self.assertEqual(accepted.returncode, 0, accepted.stderr) + self.assertEqual(json.loads(accepted.stdout)["deliveredTo"], ["A"]) diff --git a/tests/transport/http_transport.py b/tests/transport/http_transport.py new file mode 100644 index 0000000..24ba563 --- /dev/null +++ b/tests/transport/http_transport.py @@ -0,0 +1,17 @@ +"""Route the urllib HTTP boundary to a local protocol fixture, including children.""" +import urllib.request + + +def route_urlopen(original, origin): + def open_local(request, *args, **kwargs): + if isinstance(request, str): + request = urllib.request.Request(request) + if not request.full_url.startswith(origin + "/"): + request = urllib.request.Request( + origin + "/external", + data=request.data, + headers={**dict(request.header_items()), "X-Fixture-Url": request.full_url}, + method=request.get_method(), + ) + return original(request, *args, **kwargs) + return open_local diff --git a/tests/transport/sitecustomize.py b/tests/transport/sitecustomize.py new file mode 100644 index 0000000..94dbf38 --- /dev/null +++ b/tests/transport/sitecustomize.py @@ -0,0 +1,10 @@ +"""Install only the external HTTP fixture in scenario-owned Python children.""" +import os +import urllib.request + +from http_transport import route_urlopen + +if os.environ.get("FASTINSIGHT_FIXTURE_ORIGIN"): + urllib.request.urlopen = route_urlopen( + urllib.request.urlopen, os.environ["FASTINSIGHT_FIXTURE_ORIGIN"] + )