diff --git a/src/cli/prisma.py b/src/cli/prisma.py index aad8385..84ea3f7 100644 --- a/src/cli/prisma.py +++ b/src/cli/prisma.py @@ -412,15 +412,19 @@ def dedup_cmd( hold: bool = typer.Option(True, "--hold/--no-hold"), ) -> None: """Tag DOI, PMID, and title duplicates. Near-matches stay untagged.""" - from prisma.dedup import mark_duplicates + from prisma.dedup import cluster, load_records, mark_duplicates from zot.db import Db - def _go() -> int: + def _go(): with Db(str(db)) as zdb: - return mark_duplicates(zdb) + tagged = mark_duplicates(zdb) + borderline = cluster(load_records(zdb)).borderline + return tagged, borderline - tagged = _hold(_go, hold=hold) + tagged, borderline = _hold(_go, hold=hold) typer.echo(f" tagged: {tagged}") + for left, right in borderline: + typer.echo(f" borderline: {left.key} {left.title} | {right.key} {right.title}") search_app = typer.Typer(no_args_is_help=True) diff --git a/src/lead/ledger/claims.py b/src/lead/ledger/claims.py index d5df5e3..1ff6d1a 100644 --- a/src/lead/ledger/claims.py +++ b/src/lead/ledger/claims.py @@ -9,6 +9,7 @@ recording the same extraction again inserts nothing. from __future__ import annotations import hashlib +import re from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING @@ -37,6 +38,7 @@ _DOWNGRADE_LABELS = { "risk_of_bias": "risk of bias", "publication_bias": "publication bias", } +_INTERVAL = re.compile(r"\s*(?:,|to)\s*", re.IGNORECASE) def grade(design: str, downgrades: Sequence[str]) -> str: @@ -56,6 +58,26 @@ def _target_id(project: str, extraction: Mapping[str, str]) -> str: return extraction.get("target_id") or extraction.get("outcome_target_id") or "" +def _number(value: str) -> float | None: + text = value.strip() + if not text: + return None + try: + return float(text) + except ValueError: + return None + + +def _interval(value: str) -> tuple[float | None, float | None]: + text = value.strip() + if not text: + return None, None + parts = _INTERVAL.split(text, maxsplit=1) + if len(parts) != 2: + return None, None + return _number(parts[0]), _number(parts[1]) + + def _downgrades(extraction: Mapping[str, str]) -> tuple[str, ...]: labels: list[str] = [] for field in _DOWNGRADE_FIELDS: @@ -110,11 +132,26 @@ def claims_from_extraction( ) if part ) + measured = _number(extraction.get("effect_value", "")) + if measured is not None: + claim["effect_value"] = measured + low, high = _interval(extraction.get("effect_ci", "")) + if low is not None: + claim["effect_ci_low"] = low + if high is not None: + claim["effect_ci_high"] = high + if "subject" not in claim: + subject = ( + extraction.get("factor_definition", "").strip() + or extraction.get("statement", "").strip() + ) + if subject: + claim["subject"] = subject return (claim,) def precursor_catalog(con: duckdb.DuckDBPyConnection) -> list[Mapping[str, object]]: - """One row per target: precursor lead time, grain, certainty, and any limit.""" + """One row per precursor claim, plus that target's first limit claim.""" rows = con.execute( """ SELECT id, kind, target_id, lead_time, grain, certainty @@ -122,27 +159,21 @@ def precursor_catalog(con: duckdb.DuckDBPyConnection) -> list[Mapping[str, objec ORDER BY target_id, id """ ).fetchall() - grouped: dict[str, dict[str, object]] = {} + limits: dict[str, str] = {} + precursors: list[dict[str, object]] = [] for claim_id, kind, target_id, lead_time, grain, certainty in rows: - entry = grouped.setdefault( - target_id, - { - "target_id": target_id, - "lead_time": "", - "grain": "", - "certainty": "", - "limit_claim_id": None, - "_precursor": False, - }, - ) - if kind == "precursor" and not entry["_precursor"]: - entry["lead_time"] = lead_time or "" - entry["grain"] = grain or "" - entry["certainty"] = certainty or "" - entry["_precursor"] = True - if kind == "limit" and entry["limit_claim_id"] is None: - entry["limit_claim_id"] = claim_id + if kind == "limit" and target_id not in limits: + limits[target_id] = claim_id + elif kind == "precursor": + precursors.append( + { + "target_id": target_id, + "lead_time": lead_time or "", + "grain": grain or "", + "certainty": certainty or "", + } + ) return [ - {key: value for key, value in entry.items() if key != "_precursor"} - for entry in grouped.values() + {**entry, "limit_claim_id": limits.get(str(entry["target_id"]))} + for entry in precursors ] diff --git a/src/lead/ledger/export.py b/src/lead/ledger/export.py index 0a40d09..86aa7fc 100644 --- a/src/lead/ledger/export.py +++ b/src/lead/ledger/export.py @@ -1,17 +1,22 @@ """Export one Zotero project's review rows into the evidence ledger. -Anchors tagged ``module:prisma`` are not records. Claims are not written -here. A second export of the same item key and extraction version inserts -nothing, because that pair is in the content hash. +Anchors tagged ``module:prisma`` are not records. An included extraction +also appends one claim from the note fields. A second export of the same +item key and extraction version inserts nothing, because that pair is in +the content hash. """ from __future__ import annotations import hashlib +import html +import json import re from typing import TYPE_CHECKING +from lead.ledger.claims import claims_from_extraction from lead.ledger.store import append +from lead.targets import by_id if TYPE_CHECKING: import duckdb @@ -19,7 +24,9 @@ if TYPE_CHECKING: from zot.db import Db _DECISIONS = frozenset({"include", "exclude", "uncertain"}) -_TARGET = re.compile(r"target_id:\s*(\S+)") +_PRE = re.compile(r"
(.*?)
", re.DOTALL) +_TAG = re.compile(r"<[^>]+>") +_FIELD = re.compile(r"(? str: @@ -54,6 +61,32 @@ def _note_body(zdb: Db, item_id: int) -> str: return "\n".join(row[0] or "" for row in rows) +def _fields_from_note(body: str) -> dict[str, str]: + """JSON inside ``
`` wins. A plain line must not capture a tag."""
+    match = _PRE.search(body)
+    if match:
+        try:
+            payload = json.loads(html.unescape(match.group(1)).strip())
+        except json.JSONDecodeError:
+            payload = None
+        if isinstance(payload, dict):
+            return {
+                str(key): "" if value is None else str(value)
+                for key, value in payload.items()
+            }
+    text = _TAG.sub(" ", html.unescape(body))
+    found: dict[str, str] = {}
+    for key, value in _FIELD.findall(text):
+        if value.startswith(("<", "&")):
+            continue
+        found.setdefault(key, value)
+    return found
+
+
+def _target(fields: dict[str, str]) -> str:
+    return (fields.get("outcome_target_id") or fields.get("target_id") or "").strip()
+
+
 def export_project(
     zdb: Db,
     con: duckdb.DuckDBPyConnection,
@@ -62,10 +95,20 @@ def export_project(
     extraction_version: str,
     actor: str,
 ) -> dict[str, int]:
-    """Insert source, decision, and extraction rows. Returns how many landed."""
+    """Insert source, decision, and extraction rows.
+
+    A note that names a known target also appends one claim. The returned
+    counts are the three review tables.
+    """
     inserted = {"source": 0, "decision": 0, "extraction": 0}
     for item_id, key in _project_items(zdb, project):
         tags = zdb.get_tags(item_id)
+        included = "stage:4-included" in tags
+        body = _note_body(zdb, item_id) if included else ""
+        fields = _fields_from_note(body) if included else {}
+        target = _target(fields)
+        if target:
+            by_id(target)
         databases = sorted(
             tag.removeprefix("found-in:") for tag in tags if tag.startswith("found-in:")
         )
@@ -118,9 +161,8 @@ def export_project(
             if append(con, "decision", row):
                 inserted["decision"] += 1
 
-        if "stage:4-included" not in tags:
+        if not included:
             continue
-        body = _note_body(zdb, item_id)
         extraction: dict[str, object] = {
             "project": project,
             "zotero_key": key,
@@ -129,9 +171,16 @@ def export_project(
             "actor": actor,
             "content_hash": _hash("extraction", key, extraction_version, project),
         }
-        found = _TARGET.search(body)
-        if found:
-            extraction["target_id"] = found.group(1)
+        if target:
+            extraction["target_id"] = target
         if append(con, "extraction", extraction):
             inserted["extraction"] += 1
+        if target:
+            claim_fields = dict(fields)
+            claim_fields["zotero_key"] = key
+            claim_fields["extraction_version"] = extraction_version
+            claim = claims_from_extraction(claim_fields, project=project, actor=actor)[
+                0
+            ]
+            append(con, "claim", dict(claim))
     return inserted
diff --git a/src/prisma/search/base.py b/src/prisma/search/base.py
index c57d609..f5db393 100644
--- a/src/prisma/search/base.py
+++ b/src/prisma/search/base.py
@@ -101,44 +101,55 @@ def seed_recall(retrieved: set[str], seeds: set[str]) -> float:
     return len(retrieved & seeds) / len(seeds)
 
 
-def record(con, result: SearchResult, *, actor: str) -> bool:
-    """Append one search row. The same export on a later day is a new row."""
+def record(con, result: SearchResult, *, actor: str, project: str = "") -> bool:
+    """Append one search row. The same export on a later day is a new row.
+
+    A nonempty ``project`` is stored and hashed, so two projects on the
+    same day stay two rows and a search logged today clears ``due``.
+    """
     log = result.log
-    raw = "\n".join(
-        [
-            log.database,
-            log.interface,
-            log.searched_on,
-            log.query,
-            log.filters,
-            str(log.hit_count),
-            log.export_sha256,
-            actor,
-        ]
-    )
-    return append(
-        con,
-        "search",
-        {
-            "database": log.database,
-            "interface": log.interface,
-            "searched_on": log.searched_on,
-            "query": log.query,
-            "filters": log.filters,
-            "hit_count": log.hit_count,
-            "export_sha256": log.export_sha256,
-            "content_hash": hashlib.sha256(raw.encode()).hexdigest(),
-            "actor": actor,
-        },
-    )
+    parts = [
+        log.database,
+        log.interface,
+        log.searched_on,
+        log.query,
+        log.filters,
+        str(log.hit_count),
+        log.export_sha256,
+        actor,
+    ]
+    if project:
+        parts.append(project)
+    row: dict[str, object] = {
+        "database": log.database,
+        "interface": log.interface,
+        "searched_on": log.searched_on,
+        "query": log.query,
+        "filters": log.filters,
+        "hit_count": log.hit_count,
+        "export_sha256": log.export_sha256,
+        "content_hash": hashlib.sha256("\n".join(parts).encode()).hexdigest(),
+        "actor": actor,
+    }
+    if project:
+        row["project"] = project
+    return append(con, "search", row)
 
 
 def import_hits(zdb: Db, project: str, result: SearchResult) -> int:
-    """Create one Zotero item per new DOI. Return how many were new."""
+    """Create one Zotero item per new DOI. Return how many were new.
+
+    A DOI already in the library is not inserted again. The existing item
+    gains this project's tag and this database's ``found-in`` tag.
+    """
     inserted = 0
     for hit in result.hits:
-        if hit.doi and _doi_exists(zdb, hit.doi):
-            continue
+        if hit.doi:
+            existing = _doi_item_id(zdb, hit.doi)
+            if existing is not None:
+                zdb.tag_item(existing, f"project:{project}")
+                zdb.tag_item(existing, f"found-in:{hit.database}")
+                continue
         item_id = zdb.create_item(TYPE_MAP["journalArticle"])
         fields = {"title": hit.title, "DOI": hit.doi, "PMID": hit.pmid}
         if hit.year is not None:
@@ -153,10 +164,10 @@ def import_hits(zdb: Db, project: str, result: SearchResult) -> int:
     return inserted
 
 
-def _doi_exists(zdb: Db, doi: str) -> bool:
+def _doi_item_id(zdb: Db, doi: str) -> int | None:
     row = zdb.con.execute(
         """
-        SELECT 1
+        SELECT id.itemID
         FROM itemData id
         JOIN itemDataValues idv ON id.valueID = idv.valueID
         WHERE id.fieldID = ? AND lower(idv.value) = lower(?)
@@ -164,4 +175,6 @@ def _doi_exists(zdb: Db, doi: str) -> bool:
         """,
         (FIELD_MAP["DOI"], doi.strip()),
     ).fetchone()
-    return row is not None
+    if row is None:
+        return None
+    return int(row[0])
diff --git a/src/prisma/search/due.py b/src/prisma/search/due.py
index 6ae4b31..800bd74 100644
--- a/src/prisma/search/due.py
+++ b/src/prisma/search/due.py
@@ -1,10 +1,12 @@
 """Whether a project's searches are due. This does not run a search.
 
-Dates are ``YYYY-MM-DD`` strings, compared as text. Nightly means the
-latest ``searched_on`` for the project is missing or earlier than today.
-The other reasons are a contradiction of moderate or high certainty, a
-strand-5 event on a target this project has a claim about, and a CMS
-source dated after that latest search.
+Dates are compared by the ``YYYY-MM-DD`` prefix, so an ISO timestamp and a
+date on the same day are the same day. Nightly means the latest
+``searched_on`` for the project is missing or earlier than today.
+Contradiction and exogenous fire only when their day is after that latest
+search. A project with no search row reports nightly only. CMS matches
+when ``cms`` is one comma-separated database token and the source day is
+after that latest search.
 """
 
 from __future__ import annotations
@@ -29,26 +31,32 @@ def _latest(con: duckdb.DuckDBPyConnection, project: str) -> str | None:
     return str(row[0])
 
 
-def _contradiction(con: duckdb.DuckDBPyConnection, project: str) -> bool:
-    row = con.execute(
+def _day(value: object) -> str:
+    if value is None:
+        return ""
+    return str(value)[:10]
+
+
+def _contradiction(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
+    rows = con.execute(
         """
-        SELECT 1
+        SELECT f.created_at
         FROM lead_evidence.finding AS f
         JOIN lead_evidence.claim AS c ON c.id = f.claim_id
         WHERE c.project = ?
           AND f.relation = 'contradicts'
           AND c.certainty IN ('moderate', 'high')
-        LIMIT 1
         """,
         [project],
-    ).fetchone()
-    return row is not None
+    ).fetchall()
+    latest_day = _day(latest)
+    return any(_day(created_at) > latest_day for (created_at,) in rows)
 
 
-def _exogenous(con: duckdb.DuckDBPyConnection, project: str) -> bool:
-    row = con.execute(
+def _exogenous(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
+    rows = con.execute(
         """
-        SELECT 1
+        SELECT e.event_on
         FROM lead_evidence.exogenous AS e
         WHERE EXISTS (
             SELECT 1
@@ -56,37 +64,41 @@ def _exogenous(con: duckdb.DuckDBPyConnection, project: str) -> bool:
             WHERE c.project = ?
               AND c.target_id = e.target_id
         )
-        LIMIT 1
         """,
         [project],
-    ).fetchone()
-    return row is not None
+    ).fetchall()
+    latest_day = _day(latest)
+    return any(_day(event_on) > latest_day for (event_on,) in rows)
 
 
 def _cms(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
-    row = con.execute(
+    rows = con.execute(
         """
-        SELECT 1
+        SELECT database, created_at
         FROM lead_evidence.source
         WHERE project = ?
-          AND database = 'cms'
-          AND created_at > ?
-        LIMIT 1
         """,
-        [project, latest],
-    ).fetchone()
-    return row is not None
+        [project],
+    ).fetchall()
+    latest_day = _day(latest)
+    for database, created_at in rows:
+        tokens = [
+            part.strip() for part in str(database or "").split(",") if part.strip()
+        ]
+        if "cms" in tokens and _day(created_at) > latest_day:
+            return True
+    return False
 
 
 def due(con: duckdb.DuckDBPyConnection, *, project: str, now: str) -> tuple[str, ...]:
     """Reasons a search should run, in a fixed order."""
     reasons: list[str] = []
     latest = _latest(con, project)
-    if latest is None or latest < now:
+    if latest is None or _day(latest) < _day(now):
         reasons.append("nightly")
-    if _contradiction(con, project):
+    if latest is not None and _contradiction(con, project, latest):
         reasons.append("contradiction")
-    if _exogenous(con, project):
+    if latest is not None and _exogenous(con, project, latest):
         reasons.append("exogenous")
     if latest is not None and _cms(con, project, latest):
         reasons.append("cms")
diff --git a/tests/lead/test_ledger_claims.py b/tests/lead/test_ledger_claims.py
index aecbb42..b1a4b75 100644
--- a/tests/lead/test_ledger_claims.py
+++ b/tests/lead/test_ledger_claims.py
@@ -100,6 +100,82 @@ def test_same_extraction_inserts_one_claim_and_the_catalog_reads_it(tmp_path):
         con.close()
 
 
+def test_claim_keeps_effect_value_interval_and_subject():
+    claim = claims_from_extraction(
+        {
+            "target_id": "Q.ACR",
+            "effect_measure": "OR",
+            "effect_value": "1.2",
+            "effect_ci": "1.1, 1.4",
+            "factor_definition": "frailty status",
+            "design": "cohort",
+        },
+        project="lead-limits",
+        actor="tester",
+    )[0]
+    assert claim["effect_measure"] == "OR"
+    assert claim["effect_value"] == 1.2
+    assert claim["effect_ci_low"] == 1.1
+    assert claim["effect_ci_high"] == 1.4
+    assert claim["subject"] == "frailty status"
+
+    stated = claims_from_extraction(
+        {
+            "target_id": "Q.ACR",
+            "effect_ci": "1.1 to 1.4",
+            "statement": "care changes the status",
+        },
+        project="lead-limits",
+        actor="tester",
+    )[0]
+    assert stated["effect_ci_low"] == 1.1
+    assert stated["effect_ci_high"] == 1.4
+    assert stated["subject"] == "care changes the status"
+
+
+def test_catalog_lists_each_precursor_claim(tmp_path):
+    first = claims_from_extraction(
+        {
+            "zotero_key": "ABCD2345",
+            "extraction_version": "v1",
+            "outcome_target_id": "Q.ACR",
+            "grain": "beneficiary",
+            "lead_time": "12 months",
+            "design": "cohort",
+        },
+        project="lead-precursors",
+        actor="tester",
+    )[0]
+    second = claims_from_extraction(
+        {
+            "zotero_key": "IJKM2345",
+            "extraction_version": "v1",
+            "outcome_target_id": "Q.ACR",
+            "grain": "beneficiary",
+            "lead_time": "6 months",
+            "design": "cohort",
+        },
+        project="lead-precursors",
+        actor="tester",
+    )[0]
+    limit = claims_from_extraction(
+        {"target_id": "Q.ACR", "grain": "ACO", "zotero_key": "EFGH5678"},
+        project="lead-limits",
+        actor="tester",
+    )[0]
+    con = open_ledger(str(tmp_path / "ledger.duckdb"))
+    try:
+        assert append(con, "claim", first) is True
+        assert append(con, "claim", second) is True
+        assert append(con, "claim", limit) is True
+        rows = [item for item in precursor_catalog(con) if item["target_id"] == "Q.ACR"]
+        assert len(rows) == 2
+        assert {row["lead_time"] for row in rows} == {"12 months", "6 months"}
+        assert {row["limit_claim_id"] for row in rows} == {limit["content_hash"]}
+    finally:
+        con.close()
+
+
 def test_unknown_target_raises_key_error():
     with pytest.raises(KeyError):
         claims_from_extraction(
diff --git a/tests/lead/test_ledger_export.py b/tests/lead/test_ledger_export.py
index 4f3647b..04be6bf 100644
--- a/tests/lead/test_ledger_export.py
+++ b/tests/lead/test_ledger_export.py
@@ -2,11 +2,13 @@
 
 from __future__ import annotations
 
+import pytest
 from typer.testing import CliRunner
 
 from cli import app
 from lead.ledger.export import export_project
 from lead.ledger.store import open_ledger
+from prisma.ingest import apply_extraction
 from zot.db import TYPE_MAP, Db
 from zot.schema import create_db
 
@@ -97,3 +99,136 @@ def test_export_is_idempotent_until_the_extraction_version_changes(tmp_path):
 def test_ledger_export_command_is_registered():
     result = runner.invoke(app, ["lead", "ledger", "export", "--help"])
     assert result.exit_code == 0
+
+
+def test_html_extraction_note_stores_the_target_and_a_claim(tmp_path):
+    zpath = str(tmp_path / "z.sqlite")
+    con = create_db(zpath)
+    con.close()
+    with Db(zpath) as zdb:
+        item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345")
+        zdb.set_fields(item_id, {"title": "All-cause readmission"})
+        zdb.tag_item(item_id, "stage:4-included")
+        apply_extraction(
+            zdb,
+            item_id,
+            "lead-precursors",
+            {
+                "outcome_target_id": "Q.ACR",
+                "effect_measure": "OR",
+                "effect_value": "1.2",
+                "effect_ci": "1.1, 1.4",
+                "factor_definition": "frailty",
+                "design": "cohort",
+            },
+        )
+        zdb.commit()
+        ledger = open_ledger(str(tmp_path / "ledger.duckdb"))
+        try:
+            export_project(
+                zdb,
+                ledger,
+                "lead-precursors",
+                extraction_version="v1",
+                actor="tester",
+            )
+            target = ledger.execute(
+                "select target_id from lead_evidence.extraction"
+            ).fetchone()[0]
+            assert target == "Q.ACR"
+            row = ledger.execute(
+                """
+                select effect_value, effect_ci_low, effect_ci_high, subject
+                from lead_evidence.claim
+                """
+            ).fetchone()
+            assert row == (1.2, 1.1, 1.4, "frailty")
+        finally:
+            ledger.close()
+
+
+def test_html_target_label_is_not_stored_as_a_tag(tmp_path):
+    zpath = str(tmp_path / "z.sqlite")
+    con = create_db(zpath)
+    con.close()
+    with Db(zpath) as zdb:
+        item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345")
+        zdb.tag_item(item_id, "project:lead-precursors")
+        zdb.tag_item(item_id, "stage:4-included")
+        zdb.add_note(item_id, "
  • outcome_target_id: Q.ACR
  • ") + zdb.commit() + ledger = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + export_project( + zdb, + ledger, + "lead-precursors", + extraction_version="v1", + actor="tester", + ) + target = ledger.execute( + "select target_id from lead_evidence.extraction" + ).fetchone()[0] + assert target == "Q.ACR" + finally: + ledger.close() + + +def test_unknown_target_in_a_note_is_not_stored(tmp_path): + zpath = str(tmp_path / "z.sqlite") + con = create_db(zpath) + con.close() + with Db(zpath) as zdb: + item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345") + zdb.tag_item(item_id, "project:lead-limits") + zdb.tag_item(item_id, "stage:4-included") + zdb.add_note(item_id, "target_id: nope") + zdb.commit() + ledger = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + with pytest.raises(KeyError): + export_project( + zdb, + ledger, + "lead-limits", + extraction_version="v1", + actor="tester", + ) + count = ledger.execute( + "select count(*) from lead_evidence.extraction" + ).fetchone()[0] + assert count == 0 + finally: + ledger.close() + + +def test_extraction_without_a_target_stores_the_row_and_skips_the_claim(tmp_path): + zpath = str(tmp_path / "z.sqlite") + con = create_db(zpath) + con.close() + with Db(zpath) as zdb: + item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345") + zdb.tag_item(item_id, "project:lead-limits") + zdb.tag_item(item_id, "stage:4-included") + zdb.add_note(item_id, "Included with no target.") + zdb.commit() + ledger = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + counts = export_project( + zdb, + ledger, + "lead-limits", + extraction_version="v1", + actor="tester", + ) + assert counts["extraction"] == 1 + target = ledger.execute( + "select target_id from lead_evidence.extraction" + ).fetchone()[0] + assert target is None + claims = ledger.execute( + "select count(*) from lead_evidence.claim" + ).fetchone()[0] + assert claims == 0 + finally: + ledger.close() diff --git a/tests/prisma/test_dedup.py b/tests/prisma/test_dedup.py index 67083ee..f9bc886 100644 --- a/tests/prisma/test_dedup.py +++ b/tests/prisma/test_dedup.py @@ -152,3 +152,32 @@ def test_borderline_items_are_not_tagged(tmp_path): def test_dedup_command_is_registered(): result = runner.invoke(app, ["dedup", "--help"]) assert result.exit_code == 0 + + +def test_dedup_command_prints_borderline_keys_and_titles(tmp_path): + path = _db(tmp_path) + with Db(path) as db: + _add( + db, + key="ABCD2345", + doi="", + title="High needs frailty index", + year=2024, + author="Kim", + ) + _add( + db, + key="EFGH5678", + doi="", + title="High-need frailty index", + year=2024, + author="Lee", + ) + result = runner.invoke(app, ["dedup", "--db", path, "--no-hold"]) + assert result.exit_code == 0 + assert "ABCD2345" in result.stdout + assert "EFGH5678" in result.stdout + assert "High needs frailty index" in result.stdout + assert "High-need frailty index" in result.stdout + with Db(path) as db: + assert _dup_count(db) == 0 diff --git a/tests/prisma/test_search_due.py b/tests/prisma/test_search_due.py index a15858a..d79c83c 100644 --- a/tests/prisma/test_search_due.py +++ b/tests/prisma/test_search_due.py @@ -56,18 +56,17 @@ def _claim(con, *, certainty: str, suffix: str, target_id: str = "Q.ACR") -> Non ) -def _finding(con, *, claim_id: str, suffix: str) -> None: - assert append( - con, - "finding", - { - "claim_id": claim_id, - "relation": "contradicts", - "grain": "beneficiary", - "actor": "tester", - "content_hash": f"finding-{suffix}", - }, - ) +def _finding(con, *, claim_id: str, suffix: str, created_at: str | None = None) -> None: + row: dict[str, object] = { + "claim_id": claim_id, + "relation": "contradicts", + "grain": "beneficiary", + "actor": "tester", + "content_hash": f"finding-{suffix}", + } + if created_at is not None: + row["created_at"] = created_at + assert append(con, "finding", row) def test_missing_or_stale_search_is_nightly(tmp_path): @@ -107,12 +106,38 @@ def test_contradiction_respects_certainty(tmp_path, certainty, expected): try: _search(con, searched_on=NOW) _claim(con, certainty=certainty, suffix=certainty) - _finding(con, claim_id=certainty, suffix=certainty) + _finding(con, claim_id=certainty, suffix=certainty, created_at="2026-11-01") assert due(con, project=PROJECT, now=NOW) == expected finally: con.close() +def test_contradiction_on_the_search_day_does_not_refire(tmp_path): + con = _ledger(tmp_path) + try: + _search(con, searched_on=NOW) + _claim(con, certainty="moderate", suffix="same-day") + _finding( + con, + claim_id="same-day", + suffix="same-day", + created_at="2026-10-31T10:00:00Z", + ) + assert due(con, project=PROJECT, now=NOW) == () + finally: + con.close() + + +def test_contradiction_without_a_search_stays_nightly(tmp_path): + con = _ledger(tmp_path) + try: + _claim(con, certainty="high", suffix="nosearch") + _finding(con, claim_id="nosearch", suffix="nosearch", created_at="2026-11-01") + assert due(con, project=PROJECT, now=NOW) == ("nightly",) + finally: + con.close() + + def test_exogenous_event_on_a_claimed_target(tmp_path): con = _ledger(tmp_path) try: @@ -124,7 +149,7 @@ def test_exogenous_event_on_a_claimed_target(tmp_path): "project": PROJECT, "target_id": "Q.ACR", "series_or_event": "cms guidance", - "event_on": NOW, + "event_on": "2026-11-01", "citation": "cms", "actor": "tester", "content_hash": "exo-1", @@ -137,6 +162,49 @@ def test_exogenous_event_on_a_claimed_target(tmp_path): con.close() +def test_exogenous_on_the_search_day_does_not_refire(tmp_path): + con = _ledger(tmp_path) + try: + _search(con, searched_on=NOW) + _claim(con, certainty="low", suffix="same-day") + assert append( + con, + "exogenous", + { + "project": PROJECT, + "target_id": "Q.ACR", + "series_or_event": "cms guidance", + "event_on": NOW, + "citation": "cms", + "actor": "tester", + "content_hash": "exo-same-day", + }, + ) + assert due(con, project=PROJECT, now=NOW) == () + finally: + con.close() + + +def test_exogenous_without_a_search_stays_nightly(tmp_path): + con = _ledger(tmp_path) + try: + _claim(con, certainty="low", suffix="nosearch") + assert append( + con, + "exogenous", + { + "target_id": "Q.ACR", + "series_or_event": "cms guidance", + "event_on": "2026-11-01", + "actor": "tester", + "content_hash": "exo-nosearch", + }, + ) + assert due(con, project=PROJECT, now=NOW) == ("nightly",) + finally: + con.close() + + def test_cms_source_newer_than_the_search(tmp_path): con = _ledger(tmp_path) try: @@ -171,12 +239,75 @@ def test_cms_source_newer_than_the_search(tmp_path): con.close() +def test_cms_iso_timestamp_on_the_search_day_does_not_fire(tmp_path): + con = _ledger(tmp_path) + try: + _search(con, searched_on=NOW) + assert append( + con, + "source", + { + "project": PROJECT, + "database": "cms", + "zotero_key": "ABCD2345", + "created_at": "2026-10-31T10:00:00Z", + "actor": "tester", + "content_hash": "src-iso-same", + }, + ) + assert due(con, project=PROJECT, now=NOW) == () + finally: + con.close() + + +def test_joined_cms_on_the_search_day_does_not_fire(tmp_path): + con = _ledger(tmp_path) + try: + _search(con, searched_on=NOW) + assert append( + con, + "source", + { + "project": PROJECT, + "database": "citation,cms", + "zotero_key": "IJKM2345", + "created_at": "2026-10-31T10:00:00Z", + "actor": "tester", + "content_hash": "src-joined-same", + }, + ) + assert due(con, project=PROJECT, now=NOW) == () + finally: + con.close() + + +def test_cms_token_in_a_joined_database_fires_after_the_search_day(tmp_path): + con = _ledger(tmp_path) + try: + _search(con, searched_on=NOW) + assert append( + con, + "source", + { + "project": PROJECT, + "database": "citation,cms", + "zotero_key": "EFGH5678", + "created_at": "2026-11-01T00:00:00Z", + "actor": "tester", + "content_hash": "src-iso-later", + }, + ) + assert due(con, project=PROJECT, now=NOW) == ("cms",) + finally: + con.close() + + def test_reasons_stay_in_order(tmp_path): con = _ledger(tmp_path) try: _search(con, searched_on=YESTERDAY, suffix="old") _claim(con, certainty="high", suffix="high") - _finding(con, claim_id="high", suffix="high") + _finding(con, claim_id="high", suffix="high", created_at="2026-11-01") assert append( con, "exogenous", diff --git a/tests/prisma/test_search_pubmed.py b/tests/prisma/test_search_pubmed.py index 778fa0b..040bb92 100644 --- a/tests/prisma/test_search_pubmed.py +++ b/tests/prisma/test_search_pubmed.py @@ -17,6 +17,7 @@ from prisma.search.base import ( record, seed_recall, ) +from prisma.search.due import due from prisma.search.protocols import PROTOCOLS from prisma.search.pubmed import parse_pubmed_xml from zot.db import TYPE_MAP, Db @@ -93,6 +94,21 @@ def test_same_xml_on_two_days_appends_two_search_rows(tmp_path): con.close() +def test_record_with_project_clears_due_and_keeps_projects_apart(tmp_path): + con = open_ledger(str(tmp_path / "ledger.duckdb")) + try: + result = parse_pubmed_xml(_XML, query="frailty", searched_on="2026-10-31") + assert record(con, result, actor="tester", project="lead-precursors") is True + assert record(con, result, actor="tester", project="lead-precursors") is False + assert due(con, project="lead-precursors", now="2026-10-31") == () + assert record(con, result, actor="tester", project="lead-history") is True + count = con.execute("select count(*) from lead_evidence.search").fetchone()[0] + assert count == 2 + assert due(con, project="lead-history", now="2026-10-31") == () + finally: + con.close() + + def test_import_hits_is_idempotent_on_doi(tmp_path): path = str(tmp_path / "z.sqlite") con = create_db(path) @@ -138,6 +154,74 @@ def test_import_hits_is_idempotent_on_doi(tmp_path): assert articles == 1 +def test_import_hits_tags_an_existing_doi_for_a_later_strand(tmp_path): + path = str(tmp_path / "z.sqlite") + con = create_db(path) + con.close() + hit = SearchHit( + title="Alpha frailty", + year=2020, + doi="10.1/alpha", + pmid="111", + first_author="Kim", + database="pubmed", + ) + log = SearchLog( + database="pubmed", + interface="eutils", + searched_on="2026-10-31", + query="frailty", + filters="", + hit_count=1, + export_sha256="abc", + ) + first = SearchResult(hits=(hit,), log=log) + second = SearchResult( + hits=( + SearchHit( + title="Alpha frailty", + year=2020, + doi="10.1/alpha", + pmid="111", + first_author="Kim", + database="openalex", + ), + ), + log=SearchLog( + database="openalex", + interface="openalex", + searched_on="2026-10-31", + query="frailty", + filters="", + hit_count=1, + export_sha256="def", + ), + ) + with Db(path) as db: + assert import_hits(db, "lead-precursors", first) == 1 + assert import_hits(db, "lead-limits", second) == 0 + articles = db.con.execute( + "select count(*) from items where itemTypeID = ?", + (TYPE_MAP["journalArticle"],), + ).fetchone()[0] + assert articles == 1 + names = { + row[0] + for row in db.con.execute( + """ + SELECT t.name FROM tags t + JOIN itemTags it ON it.tagID = t.tagID + """ + ) + } + assert names >= { + "project:lead-precursors", + "project:lead-limits", + "found-in:pubmed", + "found-in:openalex", + } + + def test_protocols_cover_the_five_projects(): assert set(PROTOCOLS) == { "lead-history",