rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
3a9a14f
·
1 Parent(s): 565bf31

fix(rag): KI-107 — graceful handling of Chroma get(ids=...) for missing ids

Browse files

C5 port-in persona saw 3× HTTP 500 'Error executing plan: Internal error:
Error finding id'. After KI-102 added per-session profile-chunk lookup,
the collection.get(ids=[f"profile_{sid}"]) call could raise on certain
Chroma sqlite states (transient HNSW compaction locks, legacy rows). The
pre-fix bare `except: pass` masked the failure into the orchestrator's
plan executor, surfacing as the cryptic 500.

Fix:
- New rag/retrieve.py::_safe_collection_get(collection, ids, where,
include) wrapper. Returns None on exception (with WARNING log so the
failure is observable in HF Space logs), returns raw dict on success.
- Profile-boost block in retrieve() routes through the helper; caller
treats None as miss and falls through to normal cosine results.
- backend/profile_rag.py::upsert_profile_chunk() wraps coll.add() in
try/except + WARNING log so profile-write failures no longer crash
the chat reply (next profile change retries).

Regression tests in tests/test_profile_rag_isolation.py:
- test_retrieve_with_never_existed_session_does_not_raise (new session,
no profile chunk yet — must not 500).
- test_retrieve_handles_chroma_get_raising_on_per_session_lookup
(simulates the raise; verifies fallback to main cosine results).
- test_safe_collection_get_returns_none_on_exception (unit test).
- test_safe_collection_get_returns_empty_dict_on_miss (unit test).

Scope: rag/retrieve.py + backend/profile_rag.py + the test file only.
Sibling agents own orchestrator.py (KI-105) and main.py (KI-106).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

backend/profile_rag.py CHANGED
@@ -29,10 +29,13 @@ naturally surface them when scoring policies for the user.
29
  from __future__ import annotations
30
 
31
  import asyncio
 
32
  from typing import Optional
33
 
34
  from backend.config import settings
35
 
 
 
36
 
37
  def profile_to_chunk_text(profile: dict) -> str:
38
  """Render the profile dict as a natural-language paragraph for the LLM.
@@ -140,33 +143,53 @@ async def upsert_profile_chunk(session_id: str, profile_dict: dict) -> None:
140
  # Replace any existing chunk for this session
141
  try:
142
  coll.delete(where={"policy_id": chunk_id})
143
- except Exception:
144
- pass
145
-
146
- coll.add(
147
- ids=[chunk_id],
148
- documents=[text],
149
- embeddings=[vec],
150
- metadatas=[{
151
- "policy_id": chunk_id,
152
- "insurer_slug": "profile",
153
- "policy_name": f"User profile (session {session_id[:8]})",
154
- "doc_type": "profile",
155
- # KI-102 (2026-05-15) — privacy P0. Stamp the owning session_id so
156
- # the retrieve path can hard-exclude any OTHER session's profile
157
- # chunk via where={"session_id": current}. Pre-fix, profile chunks
158
- # had no session_id metadata and the main retrieval pass had no
159
- # doc_type filter, so chunks from sessions smokeA_1, ki100_ve, etc.
160
- # surfaced as cosine matches in session smokeB_B4's context —
161
- # leaking one user's profile facts into another user's reply.
162
- "session_id": session_id,
163
- "source_url": "",
164
- "page_start": 0,
165
- "page_end": 0,
166
- "chunk_idx": 0,
167
- "local_path": "in-memory session profile",
168
- }],
169
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
 
171
 
172
  def remove_profile_chunk(session_id: str) -> None:
 
29
  from __future__ import annotations
30
 
31
  import asyncio
32
+ import logging
33
  from typing import Optional
34
 
35
  from backend.config import settings
36
 
37
+ _log = logging.getLogger(__name__)
38
+
39
 
40
  def profile_to_chunk_text(profile: dict) -> str:
41
  """Render the profile dict as a natural-language paragraph for the LLM.
 
143
  # Replace any existing chunk for this session
144
  try:
145
  coll.delete(where={"policy_id": chunk_id})
146
+ except Exception as e:
147
+ # Non-fatal: chunk may not exist yet. KI-107 — at least log so
148
+ # silent corruption of the profile store is observable.
149
+ _log.debug(
150
+ "profile_rag.upsert_profile_chunk: delete(where=policy_id=%s) "
151
+ "non-fatal failure: %s: %s",
152
+ chunk_id, type(e).__name__, str(e)[:200],
153
+ )
154
+
155
+ # KI-107 (2026-05-15) — wrap coll.add() in try/except. C5 port-in saw
156
+ # 3× HTTP 500 "Error finding id" cascade; one possible vector is a
157
+ # transient Chroma sqlite lock during HNSW compaction when add()
158
+ # interleaves with the retrieve path's get(). Make upsert non-fatal so
159
+ # the chat reply still returns even if the profile-chunk write fails.
160
+ # On next upsert (next profile field change), the retry will succeed.
161
+ try:
162
+ coll.add(
163
+ ids=[chunk_id],
164
+ documents=[text],
165
+ embeddings=[vec],
166
+ metadatas=[{
167
+ "policy_id": chunk_id,
168
+ "insurer_slug": "profile",
169
+ "policy_name": f"User profile (session {session_id[:8]})",
170
+ "doc_type": "profile",
171
+ # KI-102 (2026-05-15) — privacy P0. Stamp the owning session_id so
172
+ # the retrieve path can hard-exclude any OTHER session's profile
173
+ # chunk via where={"session_id": current}. Pre-fix, profile chunks
174
+ # had no session_id metadata and the main retrieval pass had no
175
+ # doc_type filter, so chunks from sessions smokeA_1, ki100_ve, etc.
176
+ # surfaced as cosine matches in session smokeB_B4's context —
177
+ # leaking one user's profile facts into another user's reply.
178
+ "session_id": session_id,
179
+ "source_url": "",
180
+ "page_start": 0,
181
+ "page_end": 0,
182
+ "chunk_idx": 0,
183
+ "local_path": "in-memory session profile",
184
+ }],
185
+ )
186
+ except Exception as e:
187
+ _log.warning(
188
+ "profile_rag.upsert_profile_chunk: add(id=%s) failed: %s: %s — "
189
+ "user reply will proceed without per-session profile context; "
190
+ "next profile change will retry.",
191
+ chunk_id, type(e).__name__, str(e)[:200],
192
+ )
193
 
194
 
195
  def remove_profile_chunk(session_id: str) -> None:
rag/retrieve.py CHANGED
@@ -10,9 +10,10 @@ Run a quick interactive smoke test from project root:
10
  from __future__ import annotations
11
 
12
  import asyncio
 
13
  import sys
14
  from dataclasses import dataclass
15
- from typing import Optional
16
 
17
  import chromadb
18
  from chromadb.config import Settings as ChromaSettings
@@ -20,6 +21,52 @@ from chromadb.config import Settings as ChromaSettings
20
  from backend.config import settings
21
  from backend.providers.local_embeddings import LocalEmbeddings as VoyageEmbeddings # alias kept
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  @dataclass
25
  class RetrievedChunk:
@@ -237,30 +284,39 @@ async def retrieve(
237
  # context block before any policy text. Mirrors the regulatory-boost
238
  # pattern below.
239
  if session_id:
240
- try:
241
- profile_chunk_id = f"profile_{session_id}"
242
- # KI-102 — defence-in-depth. Filter by BOTH id AND session_id
243
- # metadata so any future ID collision (or migration-era chunk
244
- # written under a shared id) still can't leak another user's
245
- # profile into this session's context.
246
- prof_res = collection.get(
247
- ids=[profile_chunk_id],
248
- where={"session_id": session_id},
249
- include=["documents", "metadatas"],
250
- )
251
- if prof_res.get("ids"):
252
- p_doc = prof_res["documents"][0] if prof_res.get("documents") else ""
253
- p_meta = prof_res["metadatas"][0] if prof_res.get("metadatas") else {}
254
- # Triple-check: even if Chroma returns a row, refuse it unless
255
- # metadata.session_id matches. Belt + suspenders + parachute.
256
- if p_doc and p_meta.get("session_id") == session_id:
257
- # Profile gets max score (1.0) so it always tops the context
258
- profile_chunk = _build_chunk(profile_chunk_id, p_doc, p_meta, 1.0)
259
- # Prepend; trim to top_k so we keep budget
260
- out = [profile_chunk] + [c for c in out if c.chunk_id != profile_chunk_id]
261
- out = out[:top_k]
262
- except Exception:
263
- pass
 
 
 
 
 
 
 
 
 
264
 
265
  # Quarantine boost pass — when the orchestrator passes a session_id, also
266
  # query the SEPARATE quarantine collection (user-uploaded PDFs) scoped to
 
10
  from __future__ import annotations
11
 
12
  import asyncio
13
+ import logging
14
  import sys
15
  from dataclasses import dataclass
16
+ from typing import Any, Optional
17
 
18
  import chromadb
19
  from chromadb.config import Settings as ChromaSettings
 
21
  from backend.config import settings
22
  from backend.providers.local_embeddings import LocalEmbeddings as VoyageEmbeddings # alias kept
23
 
24
+ _log = logging.getLogger(__name__)
25
+
26
+
27
+ def _safe_collection_get(
28
+ collection: Any,
29
+ *,
30
+ ids: Optional[list[str]] = None,
31
+ where: Optional[dict] = None,
32
+ include: Optional[list[str]] = None,
33
+ ) -> Optional[dict]:
34
+ """KI-107 (2026-05-15) — defensive wrapper around `collection.get(...)`.
35
+
36
+ C5 port-in persona logged 3× HTTP 500 "Error executing plan: Internal
37
+ error: Error finding id" against the live HF Space. Chroma's
38
+ `collection.get(ids=[...])` is documented to return empty lists when ids
39
+ miss — but the Rust-backed client can still raise on certain edge cases
40
+ (legacy schema rows, where-clause + missing-id combinations, transient
41
+ sqlite lock contention during HNSW compaction). The pre-KI-107 code
42
+ wrapped these calls in bare `except: pass`, which silently masked the
43
+ failure and let downstream callers index into None — producing the
44
+ confusing "Error finding id" plan-executor message instead of a
45
+ coherent retrieval fallback.
46
+
47
+ This helper:
48
+ - Returns None on ANY exception (caller MUST treat None as "miss").
49
+ - Returns the raw dict (may have empty lists) on success.
50
+ - Logs at WARNING level so the failure is observable in HF Space logs
51
+ instead of swallowed silently. Critical for post-mortem of similar
52
+ regressions.
53
+ """
54
+ try:
55
+ kwargs: dict = {}
56
+ if ids is not None:
57
+ kwargs["ids"] = ids
58
+ if where is not None:
59
+ kwargs["where"] = where
60
+ if include is not None:
61
+ kwargs["include"] = include
62
+ return collection.get(**kwargs)
63
+ except Exception as e: # broad: Chroma raises bare RuntimeError, ValueError, sqlite errors
64
+ _log.warning(
65
+ "Chroma get(ids=%r, where=%r) failed: %s: %s",
66
+ ids, where, type(e).__name__, str(e)[:200],
67
+ )
68
+ return None
69
+
70
 
71
  @dataclass
72
  class RetrievedChunk:
 
284
  # context block before any policy text. Mirrors the regulatory-boost
285
  # pattern below.
286
  if session_id:
287
+ profile_chunk_id = f"profile_{session_id}"
288
+ # KI-102 — defence-in-depth. Filter by BOTH id AND session_id
289
+ # metadata so any future ID collision (or migration-era chunk
290
+ # written under a shared id) still can't leak another user's
291
+ # profile into this session's context.
292
+ #
293
+ # KI-107 (2026-05-15) — route through _safe_collection_get because new
294
+ # sessions (no profile saved yet) and certain transient Chroma sqlite
295
+ # states cause collection.get(ids=[missing_id]) to raise instead of
296
+ # returning empty lists. Before this fix the bare `except: pass` here
297
+ # masked the failure, the orchestrator's plan-executor still saw an
298
+ # AttributeError on the swallowed-None path, and the user got HTTP
299
+ # 500 "Error executing plan: Internal error: Error finding id".
300
+ prof_res = _safe_collection_get(
301
+ collection,
302
+ ids=[profile_chunk_id],
303
+ where={"session_id": session_id},
304
+ include=["documents", "metadatas"],
305
+ )
306
+ # prof_res is None on exception, a dict (possibly with empty lists) on success.
307
+ if prof_res and prof_res.get("ids"):
308
+ documents = prof_res.get("documents") or []
309
+ metadatas = prof_res.get("metadatas") or []
310
+ p_doc = documents[0] if documents else ""
311
+ p_meta = metadatas[0] if metadatas else {}
312
+ # Triple-check: even if Chroma returns a row, refuse it unless
313
+ # metadata.session_id matches. Belt + suspenders + parachute.
314
+ if p_doc and p_meta.get("session_id") == session_id:
315
+ # Profile gets max score (1.0) so it always tops the context
316
+ profile_chunk = _build_chunk(profile_chunk_id, p_doc, p_meta, 1.0)
317
+ # Prepend; trim to top_k so we keep budget
318
+ out = [profile_chunk] + [c for c in out if c.chunk_id != profile_chunk_id]
319
+ out = out[:top_k]
320
 
321
  # Quarantine boost pass — when the orchestrator passes a session_id, also
322
  # query the SEPARATE quarantine collection (user-uploaded PDFs) scoped to
tests/test_profile_rag_isolation.py CHANGED
@@ -283,6 +283,158 @@ class TestProfileIsolation(unittest.TestCase):
283
  )
284
 
285
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
286
  # ---------------------------------------------------------------------------
287
  # Standalone upsert metadata test — no Chroma client; just verify the
288
  # upsert builds metadata containing session_id.
 
283
  )
284
 
285
 
286
+ # ---------------------------------------------------------------------------
287
+ # KI-107 (2026-05-15) — graceful handling of Chroma get(ids=[missing]).
288
+ # C5 port-in persona saw 3× HTTP 500 "Error executing plan: Internal error:
289
+ # Error finding id". After KI-102 added the per-session profile-chunk
290
+ # lookup, retrieve() runs collection.get(ids=[f"profile_{sid}"]) on EVERY
291
+ # query — and for new sessions (no profile saved yet) and certain Chroma
292
+ # sqlite states, that call can raise. The bare `except: pass` in the
293
+ # pre-KI-107 code masked the failure into the orchestrator's plan executor.
294
+ # These tests pin the contract: retrieve() with a never-existed session_id
295
+ # must NEVER raise and must NEVER return a profile chunk.
296
+ # ---------------------------------------------------------------------------
297
+
298
+
299
+ class TestRetrieveSurvivesMissingProfileId(unittest.TestCase):
300
+ """KI-107 — retrieve(session_id=...) must be exception-safe across:
301
+ (1) brand-new sessions with no profile chunk yet,
302
+ (2) Chroma.get raising on the per-session lookup,
303
+ (3) Chroma.get returning empty lists for missing ids."""
304
+
305
+ def setUp(self):
306
+ self.coll = _make_ephemeral_collection()
307
+
308
+ def _seed_one_policy(self):
309
+ """Seed a single policy chunk so the main cosine pass returns something."""
310
+ vec = asyncio.run(_StubEmbedder().embed(["Standard policy text."]))[0]
311
+ self.coll.add(
312
+ ids=["policy_seed_1"],
313
+ documents=["Standard policy text about waiting periods."],
314
+ embeddings=[vec],
315
+ metadatas=[{
316
+ "policy_id": "policy_seed_1",
317
+ "insurer_slug": "test-insurer",
318
+ "policy_name": "Test Policy",
319
+ "doc_type": "policy",
320
+ "source_url": "",
321
+ "page_start": 1,
322
+ "page_end": 1,
323
+ "chunk_idx": 0,
324
+ }],
325
+ )
326
+
327
+ def _run_retrieve(self, query: str, session_id: str, top_k: int = 5):
328
+ from rag import retrieve as retrieve_mod
329
+ retrieve_mod._RETRIEVAL_CACHE.clear()
330
+ with mock.patch.object(retrieve_mod, "get_collection", return_value=self.coll):
331
+ return asyncio.run(retrieve_mod.retrieve(
332
+ query=query,
333
+ top_k=top_k,
334
+ embedder=_StubEmbedder(),
335
+ session_id=session_id,
336
+ ))
337
+
338
+ def test_retrieve_with_never_existed_session_does_not_raise(self):
339
+ """New session, no profile saved yet — must return policy chunks
340
+ without raising. Pre-KI-107 this surfaced as HTTP 500 "Error
341
+ finding id" because get(ids=[missing]) raised + bare except: pass
342
+ let downstream code index into a None result."""
343
+ self._seed_one_policy()
344
+
345
+ # Should not raise
346
+ chunks = self._run_retrieve(
347
+ query="what is the waiting period for cataract",
348
+ session_id="never_existed_session_xyz",
349
+ )
350
+
351
+ # No profile chunk should appear (none was ever written)
352
+ profile_chunks = [c for c in chunks if c.doc_type == "profile"]
353
+ self.assertEqual(
354
+ profile_chunks, [],
355
+ f"never-existed session should not produce profile chunks. "
356
+ f"Got: {[(c.chunk_id, c.doc_type) for c in chunks]}",
357
+ )
358
+ # But main cosine retrieval must still work
359
+ self.assertGreater(
360
+ len(chunks), 0,
361
+ "main cosine pass should still return the seeded policy chunk.",
362
+ )
363
+
364
+ def test_retrieve_handles_chroma_get_raising_on_per_session_lookup(self):
365
+ """Simulate the worst case: Chroma raises on the per-session
366
+ profile lookup (e.g. transient sqlite lock during compaction).
367
+ retrieve() must still return main cosine results, not 500."""
368
+ self._seed_one_policy()
369
+
370
+ # Wrap the real collection so .get() raises but .query() works
371
+ real_coll = self.coll
372
+
373
+ class _RaisingGetWrapper:
374
+ def __init__(self, inner):
375
+ self._inner = inner
376
+
377
+ def query(self, *args, **kwargs):
378
+ return self._inner.query(*args, **kwargs)
379
+
380
+ def get(self, *args, **kwargs):
381
+ raise RuntimeError("Error finding id: simulated chroma failure")
382
+
383
+ wrapped = _RaisingGetWrapper(real_coll)
384
+
385
+ from rag import retrieve as retrieve_mod
386
+ retrieve_mod._RETRIEVAL_CACHE.clear()
387
+ with mock.patch.object(retrieve_mod, "get_collection", return_value=wrapped):
388
+ # Must NOT raise — _safe_collection_get swallows + logs
389
+ chunks = asyncio.run(retrieve_mod.retrieve(
390
+ query="what is the waiting period",
391
+ top_k=5,
392
+ embedder=_StubEmbedder(),
393
+ session_id="some_session_id",
394
+ ))
395
+
396
+ # Main cosine still works → at least the seeded policy chunk returns
397
+ self.assertGreater(
398
+ len(chunks), 0,
399
+ "retrieve() should fall back to main cosine results when "
400
+ "the per-session profile lookup raises.",
401
+ )
402
+ # No profile chunk surfaced
403
+ self.assertEqual(
404
+ [c for c in chunks if c.doc_type == "profile"], [],
405
+ "raising get() must NOT produce a profile chunk in the result.",
406
+ )
407
+
408
+ def test_safe_collection_get_returns_none_on_exception(self):
409
+ """Unit-test the _safe_collection_get helper directly."""
410
+ from rag.retrieve import _safe_collection_get
411
+
412
+ class _Raiser:
413
+ def get(self, **kw):
414
+ raise RuntimeError("Error finding id")
415
+
416
+ result = _safe_collection_get(_Raiser(), ids=["x"], include=["documents"])
417
+ self.assertIsNone(
418
+ result,
419
+ "_safe_collection_get must return None on exception, not re-raise.",
420
+ )
421
+
422
+ def test_safe_collection_get_returns_empty_dict_on_miss(self):
423
+ """When ids miss but Chroma returns empty lists (the normal case),
424
+ _safe_collection_get returns the raw dict — caller decides what to
425
+ do with empty lists (the truthiness check filters them out)."""
426
+ from rag.retrieve import _safe_collection_get
427
+
428
+ result = _safe_collection_get(
429
+ self.coll,
430
+ ids=["definitely_does_not_exist"],
431
+ include=["documents", "metadatas"],
432
+ )
433
+ # Should return a dict (not None), with empty ids list
434
+ self.assertIsNotNone(result, "missing-id get must not return None")
435
+ self.assertEqual(result.get("ids"), [], "missing id should yield empty ids list")
436
+
437
+
438
  # ---------------------------------------------------------------------------
439
  # Standalone upsert metadata test — no Chroma client; just verify the
440
  # upsert builds metadata containing session_id.