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
42 changes: 33 additions & 9 deletions forebear/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from .ingest import IngestError
from .investigation import runner as inv_runner
from .investigation import store as inv_store
from .lineage import assess, compare
from .lineage import assess, compare, date_relation, recall_attribution, recall_reach

agent.load_env()
use_live_cache() # live ingests never touch the committed data/raw cache
Expand Down Expand Up @@ -155,37 +155,61 @@ async def compare_ep(body: CompareIn):
async def recall_event(event: str, depth: int = 3):
if not all(e.strip().isdigit() for e in event.split(",")) or event.count(",") > 9:
raise HTTPException(400, "Recall event numbers are numeric, e.g. 88058 or 88058,88071")
return await run(lambda g: g.recall_event_reach(event, depth))
return await run(lambda g: recall_reach(g, event, depth))


@app.get("/api/watchlist")
async def watchlist(design_only: bool = True):
"""Clearances decided strictly after a recall began on a direct or 2nd-generation predicate. Dates compared are
the clearance (decision) date and the recall start; the receipt date is returned for reference only, because
it does not establish when a citation was made."""
rows = await run(lambda g: g.cited_after_recall(design_only, limit=5000))
by: dict[str, dict] = {}
for r in rows:
d = by.setdefault(r["k"], {"k": r["k"], "name": r["name"], "applicant": r["applicant"],
"decision_date": r["decision_date"], "received_date": r["received_date"],
"min_gen": r["gen"], "supported_min_gen": None, "recall_count": 0,
"ancestors": set(), "events": set(), "recalls": []})
"ancestors": set(), "supported_ancestors": set(), "events": set(), "recalls": [],
"earliest_recall": None, "earliest_supported_recall": None})
d["min_gen"] = min(d["min_gen"], r["gen"])
d["recall_count"] += 1
if not r["conditional"]: # a route that does not rest on an unresolved citation
d["earliest_recall"] = min(filter(None, (d["earliest_recall"], r["initiated"])))
if r["supported_gen"] is not None: # at least one route that does not rest on an unresolved citation
sg = d["supported_min_gen"]
d["supported_min_gen"] = r["gen"] if sg is None else min(sg, r["gen"])
d["supported_min_gen"] = r["supported_gen"] if sg is None else min(sg, r["supported_gen"])
d["supported_ancestors"].add(r["ancestor"])
d["earliest_supported_recall"] = min(filter(None, (d["earliest_supported_recall"], r["initiated"])))
d["ancestors"].add(r["ancestor"])
d["events"].add(r["event"])
if len(d["recalls"]) < 6:
d["recalls"].append({k: r[k] for k in ("recall_id", "ancestor", "gen", "conditional", "classification",
"root_cause", "initiated", "firm", "url")})
out = sorted(by.values(), key=lambda d: d["decision_date"] or "", reverse=True)
d["recalls"].append({k: r[k] for k in ("recall_id", "ancestor", "gen", "supported_gen", "conditional",
"classification", "root_cause", "initiated", "firm", "url",
"link_name_check", "linked_before_clearance")}
| {"attribution": recall_attribution(r)})
out = sorted(by.values(), key=lambda d: (d["decision_date"] or "", d["k"]), reverse=True)
for d in out:
d["ancestors"] = sorted(d["ancestors"])
d["supported_ancestors"] = sorted(d["supported_ancestors"])
d["events"] = sorted(e for e in d["events"] if e)
# computed over every recall route, not the first six listed: conditional only if none is supported
d["conditional"] = d["supported_min_gen"] is None
basis = d["earliest_recall"] if d["conditional"] else d["earliest_supported_recall"]
d["recall_basis"] = basis # the recall start the clearance date is compared with
d["timing"] = date_relation(d["decision_date"], basis) # always 'after' by the query's strict filter
d["days_after_recall"] = _days(basis, d["decision_date"])
return {"count": len(out), "direct": sum(1 for d in out if d["min_gen"] == 1),
"direct_supported": sum(1 for d in out if d["supported_min_gen"] == 1),
"conditional": sum(1 for d in out if d["conditional"]), "rows": out}
"conditional": sum(1 for d in out if d["conditional"]),
"compared": "clearance (decision) date vs recall start; receipt date is not a citation date",
"rows": out}


def _days(a: str | None, b: str | None) -> int | None:
from datetime import date
try:
return (date.fromisoformat(str(b)[:10]) - date.fromisoformat(str(a)[:10])).days
except (TypeError, ValueError):
return None


@app.get("/api/assessments")
Expand Down
63 changes: 30 additions & 33 deletions forebear/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,62 +318,59 @@ def out_of_lineage_predicates(self, k: str) -> list[dict]:
return [r for r in rows if r["kind"] == "predicate" and not r["in_lineage"] and r["dst"] not in corrected]

def cited_after_recall(self, design_only: bool = True, limit: int = 200) -> list[dict]:
"""Clearances whose (direct or 2nd-generation) predicate was already under a recall
when the new device was cleared. A row is conditional if every shortest path
to that recall holder contains an unresolved audit link."""
"""Recall routes where a clearance was decided strictly after a recall had begun on its direct or
2nd-generation predicate. The comparison uses the clearance (decision) date only: the application's
receipt date is when the submission arrived, which does not establish when, or whether, a citation
was made with knowledge of the recall. Same-day and undated pairs are not "after" and are excluded.

`gen` is the shortest route over any lineage path; `supported_gen` the shortest over paths with no
unresolved audit link (null if every path to the recall holder rests on one). A row is conditional
when supported_gen is null. `attribution` says how FDA's recall record is tied to the holder."""
flt = "AND x.design_related" if design_only else ""
rows = self.q(
f"""MATCH p = (d:Device)-[:CITES*1..2]->(a:Device)-[:SUBJECT_OF]->(x:Recall)
f"""MATCH p = (d:Device)-[:CITES*1..2]->(a:Device)-[s:SUBJECT_OF]->(x:Recall)
WHERE all(r IN relationships(p) WHERE type(r) = 'SUBJECT_OF' OR ({LINEAGE_EDGE}))
AND d.decision_date IS NOT NULL AND x.initiated IS NOT NULL
AND x.initiated < d.decision_date {flt}
WITH d, a, x, min(length(p)) - 1 AS gen,
min(CASE WHEN all(r IN relationships(p) WHERE NOT ({DISPUTED_EDGE}))
THEN length(p) ELSE null END) AS supported_length
WITH d, a, x, s, min(length(p)) - 1 AS gen,
min(CASE WHEN all(r IN relationships(p) WHERE type(r) = 'SUBJECT_OF' OR NOT ({DISPUTED_EDGE}))
THEN length(p) - 1 ELSE null END) AS supported_gen
RETURN d.k AS k, d.name AS name, d.applicant AS applicant,
toString(d.decision_date) AS decision_date, toString(d.received_date) AS received_date,
a.k AS ancestor, a.name AS ancestor_name, gen,
(supported_length IS NULL OR supported_length > gen + 1) AS conditional,
a.k AS ancestor, a.name AS ancestor_name, gen, supported_gen,
supported_gen IS NULL AS conditional,
s.name_check AS link_name_check, s.before_clearance AS linked_before_clearance,
x.id AS recall_id, x.event AS event, x.classification AS classification,
x.root_cause AS root_cause, toString(x.initiated) AS initiated, x.firm AS firm,
x.reason AS reason, x.url AS url
ORDER BY decision_date DESC, gen LIMIT $n""", {"n": limit})
return rows

def recall_event_reach(self, event: str, depth: int = 3) -> dict:
"""For one recall event (or several, comma-separated): the recalled devices and every
later clearance that descends from them. `after_recall` compares each descendant's
clearance date with the earliest recall start among the recalled devices it actually
descends from. `conditional_via` lists holders reached exclusively through unresolved
audit links."""
"""For one recall event (or several, comma-separated): the clearances FDA lists on it and every
later clearance that descends from them. See lineage.recall_reach for the timing classification."""
events = [e.strip() for e in str(event).split(",") if e.strip()]
devs = self.q("""MATCH (d:Device)-[:SUBJECT_OF]->(x:Recall) WHERE x.event IN $es
RETURN d.k AS k, d.name AS name, min(x.initiated) AS initiated""", {"es": events})
devs = self.q("""MATCH (d:Device)-[s:SUBJECT_OF]->(x:Recall) WHERE x.event IN $es
RETURN d.k AS k, d.name AS name, toString(d.decision_date) AS decision_date,
toString(min(x.initiated)) AS initiated, count(x) AS records,
collect(DISTINCT s.name_check) AS name_checks,
any(b IN collect(s.before_clearance) WHERE b) AS before_clearance
ORDER BY k""", {"es": events})
if not devs:
return {"event": event, "recalled": [], "descendants": []}
start = {d["k"]: d["initiated"] for d in devs}
desc = self.q(
f"""MATCH p = (s:Device)<-[:CITES*1..{max(1, min(depth, 6))}]-(d:Device)
WHERE s.k IN $ks AND NOT d.k IN $ks AND all(r IN relationships(p) WHERE {LINEAGE_EDGE})
WITH d, min(length(p)) AS gen, collect(DISTINCT s.k) AS via,
WITH d, min(length(p)) AS gen,
min(CASE WHEN all(r IN relationships(p) WHERE NOT ({DISPUTED_EDGE})) THEN length(p) ELSE null END)
AS supported_gen,
collect(DISTINCT s.k) AS via,
collect(DISTINCT CASE WHEN all(r IN relationships(p) WHERE NOT ({DISPUTED_EDGE}))
THEN s.k ELSE null END) AS supported_via
RETURN d.k AS k, d.name AS name, d.applicant AS applicant,
d.decision_date AS decided, gen, via, supported_via
ORDER BY d.decision_date DESC""", {"ks": list(start)})
out = []
for r in desc:
first = min((start[v] for v in r["via"] if start.get(v)), default=None)
conditional_via = sorted(set(r["via"]) - set(r["supported_via"]))
out.append({"k": r["k"], "name": r["name"], "applicant": r["applicant"],
"decision_date": str(r["decided"]) if r["decided"] else None, "gen": r["gen"],
"via": r["via"], "conditional_via": conditional_via,
"recall_started": str(first) if first else None,
"after_recall": bool(first and r["decided"] and r["decided"] > first)})
initiated = min((v for v in start.values() if v), default=None)
return {"event": event, "initiated": str(initiated) if initiated else None,
"recalled": [{"k": d["k"], "name": d["name"], "initiated": str(d["initiated"])} for d in devs],
"descendants": out}
toString(d.decision_date) AS decision_date, gen, supported_gen, via, supported_via
ORDER BY d.decision_date DESC, d.k""", {"ks": [d["k"] for d in devs]})
return {"event": event, "recalled": devs, "descendants": desc}

def assessments(self, k: str | None = None, limit: int = 20) -> list[dict]:
"""Saved assessments, each with a `stale` flag: after it was saved, a citation somewhere in
Expand Down
12 changes: 7 additions & 5 deletions forebear/investigation/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

from .. import summaries
from ..graph import LINEAGE_EDGE, Graph
from ..lineage import EVIDENCE_WINDOW, assess, compare, doubt
from ..lineage import EVIDENCE_WINDOW, assess, compare, doubt, recall_reach

K_RE = re.compile(r"^K\d{6}$")
RECALL_RE = re.compile(r"^Z-\d{4}-\d{4}$")
Expand Down Expand Up @@ -300,22 +300,24 @@ def t_get_recall(g: Graph, args: dict, ctx: RunContext) -> dict:
"initiated": x.get("initiated"), "status": x.get("status"), "firm": x.get("firm"), "url": x.get("url"),
"untrusted_reason": untrusted(x.get("reason"), 400), "untrusted_product": untrusted(x.get("product"), 300),
"linked_devices": devs[:20], "linked_devices_total": len(devs),
"note": "Device links are FDA's own k_numbers on the recall record; link_name_check says whether the "
"product text names the device."}
"note": "Device links are FDA's own k_numbers on the recall record: an association, not verified model "
"identity. link_name_check is a fuzzy heuristic (one distinctive word of the FDA device name found "
"in the recall text), not proof the recall names that exact model."}


def t_recall_reach(g: Graph, args: dict, ctx: RunContext) -> dict:
ev = str(args.get("event") or "").strip()
if not EVENT_RE.match(ev):
raise ToolError("event must be a numeric FDA recall event number, e.g. 88071")
r = g.recall_event_reach(ev, 3)
r = recall_reach(g, ev, 3)
if not r["recalled"]:
raise ToolError(f"no recalled device for event {ev} in the graph")
desc = r["descendants"]
return {"event": ev, "initiated": r.get("initiated"), "recalled": r["recalled"][:20],
"descendants_total": len(desc), "descendants_cleared_after_recall": sum(d["after_recall"] for d in desc),
"timing_counts": r["counts"],
"descendants": [{k: d[k] for k in ("k", "name", "decision_date", "gen", "via", "conditional_via",
"after_recall")}
"evidence", "timing", "after_recall")}
for d in desc][:25]}


Expand Down
Loading
Loading