Skip to content
Merged
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
5 changes: 0 additions & 5 deletions fastinsight/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
41 changes: 18 additions & 23 deletions scripts/auto_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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]
Expand Down Expand Up @@ -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):
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions scripts/publish_receipt.py
Original file line number Diff line number Diff line change
@@ -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
6 changes: 5 additions & 1 deletion scripts/publish_to_research.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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__":
Expand Down
115 changes: 115 additions & 0 deletions tests/http_world.py
Original file line number Diff line number Diff line change
@@ -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'<html><head><meta name="citation_title" content="{world.title}">'
'<meta name="citation_doi" content="10.9999/unrelated">'
'<meta name="description" content="Unrelated page abstract">'
'</head></html>')
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", '<feed xmlns="http://www.w3.org/2005/Atom"/>'
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()
71 changes: 71 additions & 0 deletions tests/test_delivery.py
Original file line number Diff line number Diff line change
@@ -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"])
17 changes: 17 additions & 0 deletions tests/transport/http_transport.py
Original file line number Diff line number Diff line change
@@ -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
10 changes: 10 additions & 0 deletions tests/transport/sitecustomize.py
Original file line number Diff line number Diff line change
@@ -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"]
)
Loading