rohitsar567 commited on
Commit
737571a
·
1 Parent(s): e5b5e6c

fix(api): KI-135 — /api/coverage counts from disk same as /api/policies/all

Browse files

Refactor /api/coverage so total_policies counts unique product_keys from
extracted/*.json (KI-133 dedup) + curated_facts pass-2, matching the
marketplace card count exactly. Result: badge = cards = 158 / 19. The
chunks count still comes from Chroma.

NOTE: this is a SURFACE fix only. The underlying issue — that ~15 of those
158 policies have NO Chroma chunks and therefore the bot cannot retrieve
or cite them in chat — is tracked separately as KI-137.

Files changed (1) hide show
  1. backend/main.py +90 -23
backend/main.py CHANGED
@@ -569,27 +569,91 @@ async def coverage():
569
  # policy -> source_url (verified at download time)
570
  policy_urls: dict[tuple[str, str], str] = {}
571
  by_insurer: dict[str, dict] = {}
572
- if total > 0:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
573
  try:
574
- res = coll.get(limit=10000, include=["metadatas"])
575
- for m in res.get("metadatas", []):
576
- slug = m.get("insurer_slug", "unknown")
577
- # KI-129 (2026-05-15) — profile chunks live in the same
578
- # collection as policies (KI-118 design — they get retrieval-
579
- # boosted as USER CONTEXT inline with policy text), but they
580
- # must NEVER count as a user-facing insurer or policy. Skip.
581
- if slug == "profile" or m.get("doc_type") == "profile":
582
- continue
583
- name = m.get("policy_name", "")
584
- url = m.get("source_url", "")
585
- if slug not in by_insurer:
586
- by_insurer[slug] = {"policies": set(), "chunks": 0}
587
- by_insurer[slug]["policies"].add(name)
588
- by_insurer[slug]["chunks"] += 1
589
- if url and (slug, name) not in policy_urls:
590
- policy_urls[(slug, name)] = url
591
  except Exception:
592
- pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
593
 
594
  insurers_out = []
595
  total_policies = 0
@@ -599,19 +663,22 @@ async def coverage():
599
  # and cited in chat answers — they just don't show in the marketplace.
600
  if slug == "regulatory":
601
  continue
602
- policy_names = sorted(info["policies"])
603
- total_policies += len(policy_names)
 
 
 
604
  name, home_url = insurer_meta.get(slug, (slug, ""))
605
  sample_entries = [
606
  PolicyEntry(name=p, source_url=policy_urls.get((slug, p), ""))
607
- for p in policy_names[:8]
608
  ]
609
  insurers_out.append(
610
  InsurerCoverage(
611
  slug=slug,
612
  name=name,
613
  home_url=home_url,
614
- policy_count=len(policy_names),
615
  sample_policies=sample_entries,
616
  )
617
  )
 
569
  # policy -> source_url (verified at download time)
570
  policy_urls: dict[tuple[str, str], str] = {}
571
  by_insurer: dict[str, dict] = {}
572
+
573
+ # KI-135 (2026-05-15) — count policies the SAME way /api/policies/all
574
+ # does (extracted/*.json + curated-facts pass-2) so the marketplace badge
575
+ # ALWAYS matches the marketplace card count. Previously this loop read
576
+ # Chroma metadata, which under-counted by ~20 because ~15 curated-facts
577
+ # policies (Activ One, Optima Secure, Reassure 2/3, Health Guard Gold,
578
+ # etc.) are legitimate distinct products that have no Chroma chunks yet,
579
+ # plus ~5 display-name mismatches collapsed two policies into one. After
580
+ # this refactor: badge = cards = 158 / 19.
581
+ # KI-129 + KI-130 invariants still hold (profile + regulatory excluded).
582
+ import json as _json
583
+ _DOCTYPE_RANK_COV = {"wordings": 0, "prospectus": 1, "cis": 2, "brochure": 3}
584
+ _doctype_of_cov = lambda stem: stem.rsplit("__", 1)[1] if "__" in stem else ""
585
+ _product_key_of_cov = lambda pid: pid.rsplit("__", 1)[0] if "__" in pid else pid
586
+
587
+ curated_facts = _load_curated_facts()
588
+ sorted_files = sorted(
589
+ settings.EXTRACTED_DIR.glob("*.json"),
590
+ key=lambda fp: (_DOCTYPE_RANK_COV.get(_doctype_of_cov(fp.stem), 99), fp.stem),
591
+ )
592
+ seen_product_keys: set[str] = set()
593
+ seen_policy_ids: set[str] = set()
594
+
595
+ # by_insurer entries:
596
+ # products: set of product_keys (matches /api/policies/all card count)
597
+ # names: ordered dict of policy_NAME -> first product_key (for sample display)
598
+ # KI-135 (2026-05-15) — track product_keys (not names) for counting so the
599
+ # ~1 within-insurer policy_name collision (e.g. new-india Floater listed
600
+ # as both extracted + curated_facts) doesn't collapse the count below the
601
+ # marketplace card count. Both representations are still distinct products.
602
+
603
+ # Pass 1: extracted JSONs (KI-133 dedup by product_key — wordings wins)
604
+ for fp in sorted_files:
605
  try:
606
+ data = _json.loads(fp.read_text())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
607
  except Exception:
608
+ continue
609
+ pid = data.get("policy_id", fp.stem)
610
+ seen_policy_ids.add(pid)
611
+ slug = data.get("insurer_slug", "")
612
+ if slug == "regulatory":
613
+ continue
614
+ pkey = _product_key_of_cov(pid)
615
+ if pkey in seen_product_keys:
616
+ continue
617
+ seen_product_keys.add(pkey)
618
+ name = data.get("policy_name", "") or pid
619
+ url = data.get("source_pdf_url", "")
620
+ if slug not in by_insurer:
621
+ by_insurer[slug] = {"products": set(), "names": [], "chunks": 0}
622
+ by_insurer[slug]["products"].add(pkey)
623
+ if name not in by_insurer[slug]["names"]:
624
+ by_insurer[slug]["names"].append(name)
625
+ by_insurer[slug]["chunks"] += 1
626
+ if url and (slug, name) not in policy_urls:
627
+ policy_urls[(slug, name)] = url
628
+
629
+ # Pass 2: curated-facts policies that have no extracted counterpart
630
+ for curated_pid, data in curated_facts.items():
631
+ if curated_pid != data.get("policy_id", curated_pid):
632
+ continue # permutation alias
633
+ if curated_pid in seen_policy_ids:
634
+ continue
635
+ if any(eid.startswith(curated_pid + "__") for eid in seen_policy_ids):
636
+ continue
637
+ seen_policy_ids.add(curated_pid)
638
+ slug = data.get("insurer_slug", "")
639
+ if slug == "regulatory":
640
+ continue
641
+ # Curated entries don't have a __doctype suffix, so use the full
642
+ # policy_id as the product_key.
643
+ pkey = curated_pid
644
+ if pkey in seen_product_keys:
645
+ continue
646
+ seen_product_keys.add(pkey)
647
+ name = data.get("policy_name", "") or curated_pid
648
+ url = data.get("source_pdf_url", "")
649
+ if slug not in by_insurer:
650
+ by_insurer[slug] = {"products": set(), "names": [], "chunks": 0}
651
+ by_insurer[slug]["products"].add(pkey)
652
+ if name not in by_insurer[slug]["names"]:
653
+ by_insurer[slug]["names"].append(name)
654
+ by_insurer[slug]["chunks"] += 1
655
+ if url and (slug, name) not in policy_urls:
656
+ policy_urls[(slug, name)] = url
657
 
658
  insurers_out = []
659
  total_policies = 0
 
663
  # and cited in chat answers — they just don't show in the marketplace.
664
  if slug == "regulatory":
665
  continue
666
+ # KI-135 — count by product_key set (matches /api/policies/all); use
667
+ # the names list for the sample display ordered by first occurrence.
668
+ product_count = len(info["products"])
669
+ sample_names = sorted(info["names"])[:8]
670
+ total_policies += product_count
671
  name, home_url = insurer_meta.get(slug, (slug, ""))
672
  sample_entries = [
673
  PolicyEntry(name=p, source_url=policy_urls.get((slug, p), ""))
674
+ for p in sample_names
675
  ]
676
  insurers_out.append(
677
  InsurerCoverage(
678
  slug=slug,
679
  name=name,
680
  home_url=home_url,
681
+ policy_count=product_count,
682
  sample_policies=sample_entries,
683
  )
684
  )