rag_server: read_publication finds the shipped originals, falls back to honest chunk reassembly; get_dataset_code resolves notebooks under the published layout (WP3)
#1
by kuivi - opened
- scripts/marine_rag/rag_server.py +177 -9
scripts/marine_rag/rag_server.py
CHANGED
|
@@ -855,13 +855,96 @@ def get_dataset_publications(dataset_or_product_id: str, top_k: int = 15) -> dic
|
|
| 855 |
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 856 |
|
| 857 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 858 |
@mcp.tool()
|
| 859 |
def read_publication(doi_or_paper_id: str, offset: int = 0,
|
| 860 |
max_chars: int = READ_DEFAULT) -> dict:
|
| 861 |
-
"""Pull the
|
| 862 |
-
|
| 863 |
-
|
| 864 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 865 |
|
| 866 |
Args:
|
| 867 |
doi_or_paper_id: canonical DOI ("10.x/...") or underscored paper_id.
|
|
@@ -871,12 +954,32 @@ def read_publication(doi_or_paper_id: str, offset: int = 0,
|
|
| 871 |
try:
|
| 872 |
key = doi_or_paper_id.strip()
|
| 873 |
paper = _papers_by_id().get(key) or _papers_by_id().get(key.lower())
|
| 874 |
-
|
| 875 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 876 |
offset = max(0, int(offset))
|
| 877 |
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 878 |
page = text[offset:offset + max_chars]
|
| 879 |
-
out = {"ok": True, "
|
|
|
|
| 880 |
"journal": paper.get("journal"), "year": paper.get("year"),
|
| 881 |
"total_chars": len(text), "offset": offset,
|
| 882 |
"returned_chars": len(page),
|
|
@@ -890,11 +993,61 @@ def read_publication(doi_or_paper_id: str, offset: int = 0,
|
|
| 890 |
pos += len(line)
|
| 891 |
out["outline"] = outline[:60]
|
| 892 |
return out
|
| 893 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 894 |
low = key.lower()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 895 |
rec = next((r for r in _registry() if r["doi"].lower() == low), None)
|
| 896 |
if rec:
|
| 897 |
-
return {"ok": True, "full_text": False,
|
| 898 |
"reason": f"not parsed yet (pdf_status: {rec.get('pdf_status')})",
|
| 899 |
"doi": rec["doi"], "title": rec.get("title"),
|
| 900 |
"journal": rec.get("journal"), "year": rec.get("year"),
|
|
@@ -1002,6 +1155,21 @@ def get_dataset_code(dataset_id: str, notebook_id: str | None = None,
|
|
| 1002 |
return _err(f"unknown notebook_id: {notebook_id}",
|
| 1003 |
hint="call get_dataset_code(dataset_id) to list attached notebooks")
|
| 1004 |
path = ROOT.parent / rec["md_path"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1005 |
if not path.exists():
|
| 1006 |
return _err(f"notebook file missing on disk: {path.name}")
|
| 1007 |
text = path.read_text(encoding="utf-8", errors="replace")
|
|
|
|
| 855 |
return _err(f"lookup failed: {repr(e)[:200]}")
|
| 856 |
|
| 857 |
|
| 858 |
+
_CHUNK_CAP = 4000 # far above the corpus maximum of 670 chunks in one paper; a guard, not a policy
|
| 859 |
+
_ORDER_UNKNOWN = 1 << 30 # sorts after every real index: an unordered chunk goes to the end, visibly
|
| 860 |
+
|
| 861 |
+
|
| 862 |
+
def _chunk_order(chunk: dict) -> int:
|
| 863 |
+
"""The chunk's position in its paper.
|
| 864 |
+
|
| 865 |
+
An explicit `chunk_index` payload field wins when present (the newer chunkers — chunk_papers_lib.py —
|
| 866 |
+
emit content-hash chunk ids and keep the order there). Failing that, the numeric tail of `chunk_id`
|
| 867 |
+
(`<paper_id>__<idx:03d>`, chunk_pubs.py — the scheme of the currently served corpus). A chunk with
|
| 868 |
+
neither sorts to the END rather than silently to the front: a reassembly that cannot order its pieces
|
| 869 |
+
must not present them as the document's order.
|
| 870 |
+
"""
|
| 871 |
+
ci = chunk.get("chunk_index")
|
| 872 |
+
if isinstance(ci, int) and not isinstance(ci, bool):
|
| 873 |
+
return ci
|
| 874 |
+
if isinstance(ci, str) and ci.isdigit():
|
| 875 |
+
return int(ci)
|
| 876 |
+
cid = str(chunk.get("chunk_id") or "")
|
| 877 |
+
tail = cid.rsplit("__", 1)[-1]
|
| 878 |
+
return int(tail) if tail.isdigit() else _ORDER_UNKNOWN
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
_PUB_CHUNK_CACHE: dict[str, tuple[list[dict], bool]] = {}
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def _publication_chunks(key: str) -> tuple[list[dict], bool, str | None]:
|
| 885 |
+
"""Every chunk of one publication, in document order, by an exact payload filter — no query, no ranking,
|
| 886 |
+
no embedding. Returns (chunks, truncated, error).
|
| 887 |
+
|
| 888 |
+
`error` is non-None when the store could not be read: an infrastructure failure must stay
|
| 889 |
+
distinguishable from "this paper has no chunks", or a transient Qdrant outage silently reads as
|
| 890 |
+
"not parsed yet" (review finding). Results are cached per paper, because read_publication is paginated
|
| 891 |
+
and re-scrolling ~1.7 MB for every 20 kB page would move the whole paper once per page.
|
| 892 |
+
|
| 893 |
+
Server only: in embedded mode this collection is the one measured at over 24 GB resident without
|
| 894 |
+
answering inside 14 minutes, and reading a paper must not cost that.
|
| 895 |
+
"""
|
| 896 |
+
if key in _PUB_CHUNK_CACHE:
|
| 897 |
+
chunks, truncated = _PUB_CHUNK_CACHE[key]
|
| 898 |
+
return chunks, truncated, None
|
| 899 |
+
try:
|
| 900 |
+
client = _via_server(PUBS_COLLECTION)
|
| 901 |
+
if client is None:
|
| 902 |
+
return [], False, None # no server configured: an honest miss, not an error
|
| 903 |
+
out, offset = [], None
|
| 904 |
+
while True:
|
| 905 |
+
points, offset = client.scroll(
|
| 906 |
+
PUBS_COLLECTION, limit=256, offset=offset, with_payload=True,
|
| 907 |
+
scroll_filter=models.Filter(should=[
|
| 908 |
+
models.FieldCondition(key="doi", match=models.MatchValue(value=key)),
|
| 909 |
+
models.FieldCondition(key="paper_id", match=models.MatchValue(value=key))]))
|
| 910 |
+
out += [dict(p.payload or {}) for p in points]
|
| 911 |
+
if offset is None:
|
| 912 |
+
break
|
| 913 |
+
if len(out) >= 4 * _CHUNK_CAP:
|
| 914 |
+
break # runaway guard only; the real cap is applied AFTER sorting
|
| 915 |
+
except Exception as e:
|
| 916 |
+
_log(f"publication chunk scroll failed for {key}: {repr(e)[:120]}")
|
| 917 |
+
return [], False, f"publications store unreadable while collecting chunks: {repr(e)[:120]}"
|
| 918 |
+
if out:
|
| 919 |
+
# one paper only: the should-filter would merge chunks of paper A (matched by doi) with paper B
|
| 920 |
+
# (matched by paper_id) if a key ever named both — keep the paper the first chunk belongs to
|
| 921 |
+
own = out[0].get("paper_id")
|
| 922 |
+
if own:
|
| 923 |
+
out = [c for c in out if c.get("paper_id") == own]
|
| 924 |
+
out = sorted(out, key=_chunk_order)
|
| 925 |
+
truncated = len(out) > _CHUNK_CAP
|
| 926 |
+
if truncated:
|
| 927 |
+
out = out[:_CHUNK_CAP] # after sorting: a truncated TAIL, never holes in the middle
|
| 928 |
+
if len(_PUB_CHUNK_CACHE) >= 8:
|
| 929 |
+
_PUB_CHUNK_CACHE.pop(next(iter(_PUB_CHUNK_CACHE)))
|
| 930 |
+
_PUB_CHUNK_CACHE[key] = (out, truncated)
|
| 931 |
+
return out, truncated, None
|
| 932 |
+
|
| 933 |
+
|
| 934 |
@mcp.tool()
|
| 935 |
def read_publication(doi_or_paper_id: str, offset: int = 0,
|
| 936 |
max_chars: int = READ_DEFAULT) -> dict:
|
| 937 |
+
"""Pull the text of one publication, paginated (same contract as
|
| 938 |
+
read_document: page 0 includes a heading outline). Three outcomes, told
|
| 939 |
+
apart by `text_fidelity`:
|
| 940 |
+
• "verbatim" — the parsed markdown original (full_text=true).
|
| 941 |
+
• "reconstructed-lossy" — no original on disk; the text is reassembled
|
| 942 |
+
from the publication's indexed chunks (full_text=FALSE: stored chunks
|
| 943 |
+
are capped at 2500 chars — cuts are marked in the text — references,
|
| 944 |
+
acknowledgements and similar sections were dropped at chunking, and
|
| 945 |
+
chunk overlap may repeat a sentence at seams).
|
| 946 |
+
• "metadata-only" — nothing parsed and nothing indexed: registry
|
| 947 |
+
metadata + abstract.
|
| 948 |
|
| 949 |
Args:
|
| 950 |
doi_or_paper_id: canonical DOI ("10.x/...") or underscored paper_id.
|
|
|
|
| 954 |
try:
|
| 955 |
key = doi_or_paper_id.strip()
|
| 956 |
paper = _papers_by_id().get(key) or _papers_by_id().get(key.lower())
|
| 957 |
+
md_path = None
|
| 958 |
+
if paper and paper.get("md_path"):
|
| 959 |
+
md_path = Path(paper["md_path"])
|
| 960 |
+
if not md_path.exists() and paper.get("paper_id"):
|
| 961 |
+
# papers.jsonl records absolute paths from the build machine; the SAME files ship in the
|
| 962 |
+
# published dataset (publications_md.tar.gz -> parsed_md/<paper_id>/vlm/<paper_id>.md).
|
| 963 |
+
# Same registry-vs-published-layout mismatch, same fix, as the notebooks below — without
|
| 964 |
+
# this, every deployment but the build machine got the lossy reconstruction for all
|
| 965 |
+
# 12,411 papers, verbatim originals for 11,209 of them sitting unread on disk (review).
|
| 966 |
+
pid = paper["paper_id"]
|
| 967 |
+
roots = ([Path(os.environ["PUBS_MD_ROOT"])] if os.environ.get("PUBS_MD_ROOT") else []) + [
|
| 968 |
+
ROOT.parent.parent / "originals_md" / "publications_md",
|
| 969 |
+
ROOT.parent.parent / "originals_md", # publications_md.tar.gz untarred in place
|
| 970 |
+
ROOT.parent.parent / "publications_md"]
|
| 971 |
+
for root in roots:
|
| 972 |
+
cand = root / "parsed_md" / pid / "vlm" / f"{pid}.md"
|
| 973 |
+
if cand.exists():
|
| 974 |
+
md_path = cand
|
| 975 |
+
break
|
| 976 |
+
if md_path is not None and md_path.exists():
|
| 977 |
+
text = md_path.read_text(encoding="utf-8", errors="replace")
|
| 978 |
offset = max(0, int(offset))
|
| 979 |
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 980 |
page = text[offset:offset + max_chars]
|
| 981 |
+
out = {"ok": True, "full_text": True, "reconstructed": False, "text_fidelity": "verbatim",
|
| 982 |
+
"doi": paper.get("doi"), "title": paper.get("title"),
|
| 983 |
"journal": paper.get("journal"), "year": paper.get("year"),
|
| 984 |
"total_chars": len(text), "offset": offset,
|
| 985 |
"returned_chars": len(page),
|
|
|
|
| 993 |
pos += len(line)
|
| 994 |
out["outline"] = outline[:60]
|
| 995 |
return out
|
| 996 |
+
# No parsed markdown anywhere on disk for this paper. Its text is also in the publications
|
| 997 |
+
# collection as chunks, so reassemble it from there when a Qdrant server is available. Lossy by
|
| 998 |
+
# construction — the loader caps a stored chunk at 2500 characters, the chunker drops references
|
| 999 |
+
# and similar sections and overlaps seams — so the reply says `full_text: false` and marks every
|
| 1000 |
+
# cap-cut in the text itself. A store failure is reported as one, never as "not parsed" (review).
|
| 1001 |
low = key.lower()
|
| 1002 |
+
chunks, truncated, store_error = _publication_chunks(low)
|
| 1003 |
+
if store_error:
|
| 1004 |
+
return _err(f"cannot read this publication right now: {store_error}",
|
| 1005 |
+
hint="the publications index did not answer; retry, or check the Qdrant server")
|
| 1006 |
+
kept = [c for c in chunks if c.get("text_raw")]
|
| 1007 |
+
if kept:
|
| 1008 |
+
offset = max(0, int(offset))
|
| 1009 |
+
max_chars = max(1000, min(int(max_chars), 60_000))
|
| 1010 |
+
cap_mark = "[… text missing here: the stored chunk is capped at 2500 characters …]"
|
| 1011 |
+
parts, outline, pos, last_section = [], [], 0, None
|
| 1012 |
+
for c in kept:
|
| 1013 |
+
t = c["text_raw"]
|
| 1014 |
+
sec = str(c.get("section") or "")
|
| 1015 |
+
if sec and sec != last_section:
|
| 1016 |
+
outline.append({"heading": sec[:120], "offset": pos})
|
| 1017 |
+
last_section = sec
|
| 1018 |
+
parts.append(t)
|
| 1019 |
+
pos += len(t) + 2
|
| 1020 |
+
if len(t) >= 2500: # the loader's cap: the cut is real and it is marked in-line
|
| 1021 |
+
parts.append(cap_mark)
|
| 1022 |
+
pos += len(cap_mark) + 2
|
| 1023 |
+
text = "\n\n".join(parts)
|
| 1024 |
+
page = text[offset:offset + max_chars]
|
| 1025 |
+
first = kept[0]
|
| 1026 |
+
reg = next((r for r in _registry() if (r.get("doi") or "").lower() == low), None) or {}
|
| 1027 |
+
unordered = sum(1 for c in kept if _chunk_order(c) == _ORDER_UNKNOWN)
|
| 1028 |
+
out = {"ok": True, "full_text": False, "reconstructed": True,
|
| 1029 |
+
"text_fidelity": "reconstructed-lossy", "truncated": truncated,
|
| 1030 |
+
"source": "reassembled from publication chunks (lossy: stored chunk text is capped — "
|
| 1031 |
+
"cuts are marked in-line — references/boilerplate are dropped at chunking, "
|
| 1032 |
+
"and seams may repeat a sentence)",
|
| 1033 |
+
"outline": outline[:60],
|
| 1034 |
+
"doi": first.get("doi") or reg.get("doi") or key, "title": first.get("title"),
|
| 1035 |
+
"journal": first.get("journal"), "year": first.get("year"),
|
| 1036 |
+
"authors": reg.get("authors"), "abstract": reg.get("abstract"),
|
| 1037 |
+
"pdf_status": reg.get("pdf_status"),
|
| 1038 |
+
"linked_products": (first.get("linked_products") or reg.get("linked_products") or [])[:15],
|
| 1039 |
+
"n_chunks": len(kept), "total_chars": len(text), "offset": offset,
|
| 1040 |
+
"returned_chars": len(page),
|
| 1041 |
+
"next_offset": offset + len(page) if offset + len(page) < len(text) else None,
|
| 1042 |
+
"text": page}
|
| 1043 |
+
if unordered:
|
| 1044 |
+
out["order_uncertain"] = (f"{unordered} of {len(kept)} chunks carry no usable order key "
|
| 1045 |
+
f"and were appended at the end in storage order")
|
| 1046 |
+
return out
|
| 1047 |
+
# nothing parsed and nothing indexed — fall back to registry metadata
|
| 1048 |
rec = next((r for r in _registry() if r["doi"].lower() == low), None)
|
| 1049 |
if rec:
|
| 1050 |
+
return {"ok": True, "full_text": False, "text_fidelity": "metadata-only",
|
| 1051 |
"reason": f"not parsed yet (pdf_status: {rec.get('pdf_status')})",
|
| 1052 |
"doi": rec["doi"], "title": rec.get("title"),
|
| 1053 |
"journal": rec.get("journal"), "year": rec.get("year"),
|
|
|
|
| 1155 |
return _err(f"unknown notebook_id: {notebook_id}",
|
| 1156 |
hint="call get_dataset_code(dataset_id) to list attached notebooks")
|
| 1157 |
path = ROOT.parent / rec["md_path"]
|
| 1158 |
+
if not path.exists():
|
| 1159 |
+
# When the parsed trees named in md_path are not present (they are absent from the published
|
| 1160 |
+
# dataset), look for the same file under the published layout: notebook_harvest/parsed/…
|
| 1161 |
+
# lives under originals_md/notebooks/harvest/ and eqc_qa/notebooks_code/… under
|
| 1162 |
+
# originals_md/notebooks/eqc/. The family md_path implies is searched FIRST, so a basename
|
| 1163 |
+
# that ever repeats across families resolves to its own copy, not alphabetically (review).
|
| 1164 |
+
base = ROOT.parent.parent / "originals_md" / "notebooks"
|
| 1165 |
+
mdp = str(rec.get("md_path") or "")
|
| 1166 |
+
fam = "eqc" if mdp.startswith("eqc_qa/") else \
|
| 1167 |
+
"harvest" if mdp.startswith("notebook_harvest/") else None
|
| 1168 |
+
alt = sorted((base / fam).rglob(f"{notebook_id}.md")) if fam else []
|
| 1169 |
+
if not alt:
|
| 1170 |
+
alt = sorted(base.rglob(f"{notebook_id}.md"))
|
| 1171 |
+
if alt:
|
| 1172 |
+
path = alt[0]
|
| 1173 |
if not path.exists():
|
| 1174 |
return _err(f"notebook file missing on disk: {path.name}")
|
| 1175 |
text = path.read_text(encoding="utf-8", errors="replace")
|