From dd96f295fef5d906f389c9f97689aefde8874934 Mon Sep 17 00:00:00 2001 From: Asembris Date: Mon, 23 Nov 2026 15:09:54 +0100 Subject: [PATCH 01/16] test: pin the K251770 two-hop recall case to the shipped graph and cached FDA evidence --- tests/test_two_hop_story.py | 151 ++++++++++++++++++++++++++++++++++++ web/src/story/two-hop.json | 41 ++++++++++ 2 files changed, 192 insertions(+) create mode 100644 tests/test_two_hop_story.py create mode 100644 web/src/story/two-hop.json diff --git a/tests/test_two_hop_story.py b/tests/test_two_hop_story.py new file mode 100644 index 0000000..5b94f90 --- /dev/null +++ b/tests/test_two_hop_story.py @@ -0,0 +1,151 @@ +"""The two-hop showcase (K251770 -> K200480 -> REMstar -> Z-1974-2021) makes claims in the UI and README. +Each must match the shipped Relate store and the cached FDA evidence, and the depth-1 / depth-2 contrast it +demonstrates must stay true: a one-generation lookup finds no design-recall signal, two generations find one.""" +import glob +import json +import re + +import pytest + +from conftest import ROOT + +from forebear.graph import open_graph +from forebear.lineage import assess, provisional + +FACTS = json.loads((ROOT / "web" / "src" / "story" / "two-hop.json").read_text(encoding="utf-8")) +RAW = ROOT / "data" / "raw" +norm = lambda s: re.sub(r"\s+", " ", s or "").strip() # noqa: E731 + + +@pytest.fixture(scope="module") +def runs(tmp_path_factory): + import shutil + from conftest import SHIPPED + if not SHIPPED.exists(): + pytest.skip("shipped store missing; run scripts/build_graph.py") + p = tmp_path_factory.mktemp("two-hop") / "forebear.rl" + shutil.copy(SHIPPED, p) + g = open_graph(p, read_only=True) + k = FACTS["candidate"]["k"] + yield {1: assess(g, k, 1), 2: assess(g, k, 2), 4: assess(g, k, 4)} + g.close() + + +def _anc(a, k): + return next(x for x in a["ancestors"] if x["k"] == k) + + +def test_depth_one_finds_no_design_signal(runs): + a, f = runs[1], FACTS["depth1"] + assert a["depth"] == f["generations"] + assert a["verdict"] == f["verdict"] and provisional(a) is f["provisional"] + assert "shallow_traversal" in a["coverage"]["evidence_reasons"] + assert [x["k"] for x in a["ancestors"]] == [FACTS["predicate"]["k"]] + assert not [s for s in a["signals"] if s["severity"] in ("high", "medium")] + + +@pytest.mark.parametrize("depth", [2, 4]) +def test_depth_two_reveals_the_design_recall(runs, depth): + a = runs[depth] + assert a["verdict"] == FACTS["depth2"]["verdict"] and provisional(a) is FACTS["depth2"]["provisional"] + assert a["coverage"]["evidence"] == "complete" + r = FACTS["recall"] + raised = [s for s in a["signals"] if s["severity"] in ("high", "medium")] + holders = {s["chain"][-1] for s in raised if any(e.get("id") == r["id"] for e in s["evidence"])} + assert holders == set(r["holders"]) + for s in raised: + assert s["gen"] == 2 and s["chain"][:2] == [FACTS["candidate"]["k"], FACTS["predicate"]["k"]] + + +def test_candidate_and_predicate_match_store(runs): + a, c, p = runs[2], FACTS["candidate"], FACTS["predicate"] + d = a["device"] + assert (d["name"], d["applicant"], d["decision_date"]) == (c["name"], c["applicant"], c["decision_date"]) + assert (d["summary_url"], d["summary_sha256"]) == (c["summary_url"], c["summary_sha256"]) + pred = _anc(a, p["k"]) + assert pred["gen"] == 1 and pred["name"].startswith(p["name"]) + assert (pred["applicant"], pred["decision_date"]) == (p["applicant"], p["decision_date"]) + assert len(pred["recalls"]) == p["recalls"] + for gp in FACTS["grand_predicates"]: + x = _anc(a, gp["k"]) + assert x["gen"] == 2 and x["name"] == gp["name"] + assert (x["applicant"], x["decision_date"]) == (gp["applicant"], gp["decision_date"]) + + +def test_hops_match_store_and_cached_pdf_text(runs): + a = runs[2] + urls = {FACTS["candidate"]["k"]: FACTS["candidate"], FACTS["predicate"]["k"]: FACTS["predicate"]} + for h in FACTS["hops"]: + hop = next(x for x in _anc(a, h["dst"])["hops"] if x["src"] == h["src"] and x["dst"] == h["dst"]) + assert hop["page"] == h["page"] and hop["kind"] == "predicate" and hop["trust"] == "extracted" + assert h["quote"] in norm(hop["snippet"]) + assert hop["source_url"] == urls[h["src"]]["summary_url"] + assert hop["source_sha256"] == urls[h["src"]]["summary_sha256"] + # the quote is on the cited page of the cached FDA summary, whose hash is the one the graph records + raw = json.loads((RAW / "summaries" / f"{h['src']}.json").read_text(encoding="utf-8")) + assert raw["sha256"] == hop["source_sha256"] and raw["url"] == hop["source_url"] + assert h["quote"] in norm(raw["pages"][h["page"] - 1]) + + +def test_recall_matches_store(runs): + r, cand = FACTS["recall"], FACTS["candidate"] + for k in r["holders"]: + x = next(rec for rec in _anc(runs[2], k)["recalls"] if rec["id"] == r["id"]) + assert (x["event"], x["classification"], x["root_cause"]) == (r["event"], r["classification"], r["root_cause"]) + assert x["design_related"] and x["initiated"] == r["initiated"] and x["url"] == r["url"] + assert x["reason"].startswith(r["reason"]) + assert FACTS["predicate"]["decision_date"] < r["initiated"] < cand["decision_date"] + + +def test_recall_matches_cached_openfda_records(): + """FDA itself lists the grand-predicates, not the direct predicate, on the recall record: the signal can + only be found by walking a second generation.""" + r, pk = FACTS["recall"], FACTS["predicate"]["k"] + seen, names_pred = [], False + for f in glob.glob(str(RAW / "openfda" / "recall_*.json")): + for rec in json.loads(open(f, encoding="utf-8").read()).get("results", []): + ks = rec.get("k_numbers") or [] + names_pred |= pk in ks + if rec.get("product_res_number") == r["id"]: + seen.append(rec) + assert seen, "recall missing from the cached openFDA records" + for rec in seen: + assert set(r["holders"]) <= set(rec["k_numbers"]) and pk not in rec["k_numbers"] + assert rec["root_cause_description"] == r["root_cause"] and rec["event_date_initiated"] == r["initiated"] + assert not names_pred, f"a cached recall record now names {pk}; the two-hop framing needs revisiting" + + +def test_api_serves_both_depths(real_copy, monkeypatch): + import importlib + from fastapi.testclient import TestClient + monkeypatch.setenv("FOREBEAR_DB", str(real_copy)) + from forebear import api + importlib.reload(api) + k = FACTS["candidate"]["k"] + with TestClient(api.app) as c: + one = c.get(f"/api/assess/{k}", params={"depth": 1}).json() + two = c.get(f"/api/assess/{k}", params={"depth": 2}).json() + assert (one["verdict"], one["depth"]) == (FACTS["depth1"]["verdict"], 1) + assert (two["verdict"], two["depth"]) == (FACTS["depth2"]["verdict"], 2) + + +README_QUERY = """MATCH path = (d:Device {k: $k})-[:CITES*1..%d]->(a:Device) +WHERE all(c IN relationships(path) WHERE c.kind = 'predicate') +MATCH (a)-[:SUBJECT_OF]->(r:Recall) +WHERE r.classification = 'Class I' AND r.root_cause = 'Device Design' + AND r.initiated < d.decision_date +RETURN [n IN nodes(path) | n.k] AS chain, r.id AS recall""" + + +def test_readme_query_depth_one_empty_depth_two_finds_recall(real_copy): + """The simplified Cypher shown in the README returns nothing at depth 1 and the REMstar rows at depth 2.""" + g = open_graph(real_copy, read_only=True) + try: + k = FACTS["candidate"]["k"] + assert g.q(README_QUERY % 1, {"k": k}) == [] + rows = g.q(README_QUERY % 2, {"k": k}) + finally: + g.close() + chains = sorted(tuple(x["chain"]) for x in rows) + assert chains == sorted((k, FACTS["predicate"]["k"], h) for h in FACTS["recall"]["holders"]) + assert {x["recall"] for x in rows} == {FACTS["recall"]["id"]} diff --git a/web/src/story/two-hop.json b/web/src/story/two-hop.json new file mode 100644 index 0000000..adf66c7 --- /dev/null +++ b/web/src/story/two-hop.json @@ -0,0 +1,41 @@ +{ + "_note": "The two-hop discovery: a one-generation lookup finds nothing, the graph finds a Class I design recall two citations back. tests/test_two_hop_story.py checks every value against the shipped Relate store and the cached FDA evidence in data/raw/.", + "candidate": { + "k": "K251770", + "name": "SleepRes PAP System", + "applicant": "Sleepres, Inc.", + "decision_date": "2025-12-15", + "summary_url": "https://www.accessdata.fda.gov/cdrh_docs/pdf25/K251770.pdf", + "summary_sha256": "73647d0b389e327183174ec57cc9a3d79f04f17f06202db8a7bbef99a7a273d1" + }, + "depth1": { "generations": 1, "verdict": "NO_DESIGN_RECALL_SIGNAL", "provisional": true }, + "depth2": { "generations": 2, "verdict": "REVIEW_LINEAGE", "provisional": false }, + "predicate": { + "k": "K200480", + "name": "DreamStation 2 System", + "applicant": "Respironics, Inc.", + "decision_date": "2020-07-10", + "summary_url": "https://www.accessdata.fda.gov/cdrh_docs/pdf20/K200480.pdf", + "summary_sha256": "923bbcfbbaea7deaf5a1b208872bda1afcf8433ff7c413ac5831cdc6c69bd1cb", + "recalls": 0 + }, + "hops": [ + { "src": "K251770", "dst": "K200480", "page": 5, "quote": "Predicate Device: Philips DreamStation 2 - K200480" }, + { "src": "K200480", "dst": "K131982", "page": 4, "quote": "Primary Predicate Device: REMSTAR AUTO A-FLEX HT (K131982)" }, + { "src": "K200480", "dst": "K130077", "page": 4, "quote": "Secondary Predicate Device: REMSTAR SE (K130077)" } + ], + "grand_predicates": [ + { "k": "K131982", "name": "REMSTAR AUTO A-FLEX HT", "applicant": "Respironics, Inc.", "decision_date": "2013-10-18" }, + { "k": "K130077", "name": "REMSTAR SE", "applicant": "Respironics, Inc.", "decision_date": "2013-05-21" } + ], + "recall": { + "id": "Z-1974-2021", + "event": "88058", + "classification": "Class I", + "root_cause": "Device Design", + "initiated": "2021-06-14", + "url": "https://www.accessdata.fda.gov/scripts/cdrh/cfdocs/cfRES/res.cfm?id=187815", + "holders": ["K131982", "K130077"], + "reason": "The polyester-based polyurethane (PE-PUR) foam may degrade into particles" + } +} From ba1d1f2c6afa97eed5ef4c96644a730b0baf3aa9 Mon Sep 17 00:00:00 2001 From: Asembris Date: Mon, 23 Nov 2026 15:10:03 +0100 Subject: [PATCH 02/16] feat: contrast depth-1 and depth-2 verdicts in the investigation when one more hop reveals a recall --- web/src/evidence.js | 8 +++ web/src/styles.css | 39 ++++++++++++ web/src/workspace/DepthContrast.jsx | 97 +++++++++++++++++++++++++++++ web/src/workspace/Investigation.jsx | 15 ++--- web/src/workspace/depth.js | 42 +++++++++++++ 5 files changed, 191 insertions(+), 10 deletions(-) create mode 100644 web/src/workspace/DepthContrast.jsx create mode 100644 web/src/workspace/depth.js diff --git a/web/src/evidence.js b/web/src/evidence.js index 72d136d..be17a7b 100644 --- a/web/src/evidence.js +++ b/web/src/evidence.js @@ -157,6 +157,14 @@ export function spanText(months) { return neg ? `-${s}` : s } +/** The recall a reviewer should read first: the earliest design-related one that began before the clearance. */ +export function keyRecall(recs, clearance) { + const design = recs.filter((r) => r.design_related) + const pool = design.length ? design : recs.filter((r) => r.classification === 'Class I') + const before = pool.filter((r) => r.initiated && clearance && r.initiated < clearance).sort((p, q) => p.initiated.localeCompare(q.initiated)) + return before[0] || [...pool].sort((p, q) => (q.initiated || '').localeCompare(p.initiated || ''))[0] || null +} + /** The PDF link opens the original FDA document at the cited page. */ export const pdfAt = (url, page) => (url ? (page ? `${url}#page=${page}` : url) : null) diff --git a/web/src/styles.css b/web/src/styles.css index d1bd7c1..b55c7d9 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -669,3 +669,42 @@ html[data-film="off"] .handoff { min-height: 60svh; } .film-top.is-solid { backdrop-filter: none; background: rgba(8, 13, 24, 0.92); } .film-hud { transition: opacity .4s var(--ease-out), transform .4s var(--ease-out); } .film-hud.is-away { opacity: 0; transform: translateY(10px); pointer-events: none; } + +/* Depth contrast: the same clearance at one and two predicate generations */ +.depth-contrast { border-color: rgba(231, 169, 72, .28); background: linear-gradient(135deg, rgba(22, 35, 59, .82), rgba(13, 21, 37, .82)); } +.dc-grid { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); gap: 14px; align-items: stretch; } +.dc-col { background: var(--night-2); border: 1px solid var(--rule); border-radius: var(--r-m); padding: 16px; display: grid; gap: 10px; align-content: start; } +.dc-col.is-deep { border-color: rgba(231, 169, 72, .45); box-shadow: inset 0 0 0 1px rgba(231, 169, 72, .08), 0 0 48px -22px rgba(231, 169, 72, .55); } +.dc-col p { margin: 0; font-size: 14px; line-height: 1.55; color: var(--ink-2); } +.dc-col .k { color: var(--blue); } +.dc-col .amber { color: var(--amber); font-weight: 600; } +.dc-depth { font-size: 11px !important; letter-spacing: .12em; text-transform: uppercase; color: var(--ink-3) !important; font-weight: 600; } +.dc-depth b { color: var(--ivory); font-weight: 650; } +.dc-verdict { font-family: var(--serif); font-size: 24px; font-weight: 450; letter-spacing: -0.015em; line-height: 1.1; display: flex; gap: 10px; align-items: center; } +.dc-verdict i { width: 10px; height: 10px; border-radius: 50%; background: currentColor; box-shadow: 0 0 0 4px color-mix(in srgb, currentColor 18%, transparent); flex: none; } +.dc-verdict.tone-amber { color: var(--amber); } +.dc-verdict.tone-alert { color: var(--alert); } +.dc-verdict.tone-calm { color: var(--sage); } +.dc-verdict.tone-muted { color: var(--ink-2); } +.dc-step { display: grid; align-content: center; justify-items: center; position: relative; width: 84px; } +.dc-step::before { content: ""; position: absolute; left: 0; right: 0; top: 50%; border-top: 2px solid var(--amber); opacity: .7; } +.dc-step span { position: relative; background: var(--night-1); border: 1px solid rgba(231, 169, 72, .5); color: var(--amber); border-radius: 999px; padding: 3px 9px; font-size: 11.5px; white-space: nowrap; } +.dc-route { list-style: none; margin: 14px 0 0; padding: 0; display: grid; gap: 0; } +.dc-route li { display: grid; grid-template-columns: 190px minmax(0, 1fr) auto; gap: 6px 14px; align-items: baseline; padding: 10px 2px; border-top: 1px solid var(--rule); font-size: 13px; } +.dc-route .dc-n { color: var(--ivory); font-size: 12.5px; } +.dc-route .dc-q { color: var(--ink-2); font-family: var(--serif); font-size: 14.5px; line-height: 1.4; } +.dc-route .is-recall .dc-n { color: var(--amber); } +.dc-route .is-recall .dc-q { font-family: inherit; font-size: 13px; } +.dc-route .dc-q .k { color: var(--blue); font-size: 12.5px; } +.dc-route .dc-a { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; justify-content: flex-end; } +.dc-route .dc-a a { font-size: 12.5px; white-space: nowrap; } +.dc-foot { margin: 10px 0 0; } +@media (max-width: 860px) { + .dc-grid { grid-template-columns: 1fr; } + .dc-step { width: auto; height: 34px; } + .dc-step::before { left: 50%; right: auto; top: 0; bottom: 0; border-top: 0; border-left: 2px solid var(--amber); } + .dc-route li { grid-template-columns: 1fr; } + .dc-route .dc-a { justify-content: flex-start; } +} +.dc-route .dc-q mark { background: rgba(127, 162, 255, .16); color: var(--ivory); border-radius: 3px; padding: 0 3px; font-family: var(--mono); font-size: .86em; } +.dc-col a.mono { white-space: nowrap; } diff --git a/web/src/workspace/DepthContrast.jsx b/web/src/workspace/DepthContrast.jsx new file mode 100644 index 0000000..2131a8f --- /dev/null +++ b/web/src/workspace/DepthContrast.jsx @@ -0,0 +1,97 @@ +import React, { useEffect, useState } from 'react' +import { api } from '../api.js' +import { fmtDate, pdfAt, verdictView } from '../evidence.js' +import { depthContrast, excerpt, strong } from './depth.js' + +function Verdict({ a }) { + const v = verdictView(a.verdict, a.coverage.evidence) + return