rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
10e6843
Β·
1 Parent(s): 2acdc9e

fix(privacy v2): same-turn age contradiction in apply_pending_recall

Browse files

The v1 match-before-merge guard (2acdc9e) only catches contradictions
that already exist on session.profile from PRIOR turns β€” but
_affirm_or_deny + apply_pending_recall fire BEFORE the LLM iteration
that calls save_profile_field. So a reply like "Yes I'm 35" against
a staged Rohit-age-29 slipped through (live.age=None pre-merge β†’ no
guard fire β†’ merge β†’ LLM later overrides age to 35, leaving the
WRONG Rohit's location/dependents/goal stuck on the live profile).

This adds:

- _extract_age_from_text(user_text) β€” best-effort regex parse for
common phrasings ("I'm 29", "29 years old", "age: 42", "aged 27").
Range-gated [18, 99] so a stray "2 kids" can't trip it.
- apply_pending_recall(session, *, confirmed, user_text="") now
also runs the parse against user_text and discards the staged
recall if the user-said age contradicts staged.age. Mis-parses
return None and skip the extra check, costing nothing.
- single_brain.py call sites pass user_text through.

11/11 extractor unit cases pass (including the original screenshot
"No, I am Rohit who is 29 years old"). LLM-driven save_profile_field
remains the canonical extractor for the live profile β€” this is purely
a same-turn safety net.

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

backend/session_state.py CHANGED
@@ -30,6 +30,7 @@ Public API:
30
  from __future__ import annotations
31
 
32
  import logging
 
33
  import time
34
  from dataclasses import dataclass, field
35
  from threading import Lock
@@ -39,6 +40,37 @@ from typing import Any, Dict
39
 
40
  from backend.needs_finder import Profile, record_answer
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  _log = logging.getLogger(__name__)
43
 
44
 
@@ -233,7 +265,12 @@ def rehydrate_by_name(session: SessionState, name: str) -> bool:
233
  return False
234
 
235
 
236
- def apply_pending_recall(session: SessionState, *, confirmed: bool) -> bool:
 
 
 
 
 
237
  """Resolve a staged cross-session profile recall.
238
 
239
  PRIVACY FIX (2026-05-16). The ONLY path that merges a stored, name-keyed
@@ -289,12 +326,35 @@ def apply_pending_recall(session: SessionState, *, confirmed: bool) -> bool:
289
  # Normalise to compare. Int and string forms of age both common.
290
  if str(live_v).strip().lower() != str(staged_v).strip().lower():
291
  _log.info(
292
- "apply_pending_recall: contradiction on %s "
293
  "(live=%r, staged=%r) β€” discarding staged recall, "
294
  "no merge",
295
  fld, live_v, staged_v,
296
  )
297
  return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
  for fld, new in stored_fields.items():
299
  try:
300
  if fld not in Profile.__dataclass_fields__:
 
30
  from __future__ import annotations
31
 
32
  import logging
33
+ import re
34
  import time
35
  from dataclasses import dataclass, field
36
  from threading import Lock
 
40
 
41
  from backend.needs_finder import Profile, record_answer
42
 
43
+
44
+ # 2026-05-27 β€” best-effort age extractor for the same-turn match-before-merge
45
+ # guard inside `apply_pending_recall`. The LLM is the canonical extractor
46
+ # (save_profile_field), but it runs AFTER apply_pending_recall in the turn
47
+ # pipeline β€” so a "Yes I'm 35" reply would otherwise merge the staged
48
+ # profile before the LLM had a chance to capture the contradicting age.
49
+ # Tight pattern: matches "I'm 29", "I am 29", "age 29", "age: 29",
50
+ # "aged 29", "29 years old", "29 yrs", "29 y/o". Range-gated to 18-99.
51
+ _AGE_HINT_RE = re.compile(
52
+ r"\b(?:age\s*[:=]?\s*|i'?m\s+|i\s+am\s+|aged\s+|aged\s*[:=]?\s*)?(\d{2})"
53
+ r"\s*(?:years?\s*old|yrs?|y/?o)?\b",
54
+ re.IGNORECASE,
55
+ )
56
+
57
+
58
+ def _extract_age_from_text(text: str) -> Optional[int]:
59
+ """Best-effort age extraction from a free-form user reply.
60
+ Returns int in [18, 99] or None. Picks the FIRST plausible match β€”
61
+ in practice the user states their age once, near the start.
62
+ """
63
+ if not text:
64
+ return None
65
+ for m in _AGE_HINT_RE.finditer(text):
66
+ try:
67
+ v = int(m.group(1))
68
+ if 18 <= v <= 99:
69
+ return v
70
+ except Exception:
71
+ continue
72
+ return None
73
+
74
  _log = logging.getLogger(__name__)
75
 
76
 
 
265
  return False
266
 
267
 
268
+ def apply_pending_recall(
269
+ session: SessionState,
270
+ *,
271
+ confirmed: bool,
272
+ user_text: str = "",
273
+ ) -> bool:
274
  """Resolve a staged cross-session profile recall.
275
 
276
  PRIVACY FIX (2026-05-16). The ONLY path that merges a stored, name-keyed
 
326
  # Normalise to compare. Int and string forms of age both common.
327
  if str(live_v).strip().lower() != str(staged_v).strip().lower():
328
  _log.info(
329
+ "apply_pending_recall: prior-turn contradiction on %s "
330
  "(live=%r, staged=%r) β€” discarding staged recall, "
331
  "no merge",
332
  fld, live_v, staged_v,
333
  )
334
  return False
335
+ # PRIVACY HARDENING v2 (2026-05-27) β€” same-turn age contradiction.
336
+ # _affirm_or_deny + apply_pending_recall fire BEFORE the LLM iteration
337
+ # that runs save_profile_field, so a user reply like "Yes I'm 35"
338
+ # against a staged Rohit at age=29 would otherwise slip through the
339
+ # prior-turn guard (live.age=None at this point) and merge the wrong
340
+ # profile. Best-effort age parse from user_text closes that gap β€”
341
+ # mis-parses lose nothing (returns None β†’ no extra check fires).
342
+ if user_text:
343
+ user_age = _extract_age_from_text(user_text)
344
+ staged_age = stored_fields.get("age")
345
+ if user_age is not None and staged_age not in (None, "", []):
346
+ try:
347
+ staged_age_int = int(staged_age)
348
+ except Exception:
349
+ staged_age_int = None
350
+ if staged_age_int is not None and staged_age_int != user_age:
351
+ _log.info(
352
+ "apply_pending_recall: same-turn age contradiction "
353
+ "(user_text age=%d, staged.age=%s) β€” discarding "
354
+ "staged recall, no merge",
355
+ user_age, staged_age,
356
+ )
357
+ return False
358
  for fld, new in stored_fields.items():
359
  try:
360
  if fld not in Profile.__dataclass_fields__:
backend/single_brain.py CHANGED
@@ -1965,12 +1965,19 @@ async def handle_turn(
1965
  if _pending_recall:
1966
  _ans = _affirm_or_deny(user_text)
1967
  if _ans is True:
 
 
 
1968
  _did_recall_this_turn = bool(
1969
- apply_pending_recall(session, confirmed=True)
 
 
1970
  )
1971
  _pending_recall = None
1972
  elif _ans is False:
1973
- apply_pending_recall(session, confirmed=False)
 
 
1974
  _pending_recall = None
1975
  # ambiguous β†’ leave staged; the confirm block is re-injected
1976
  # below and the LLM re-asks the "are you <name>?" question.
 
1965
  if _pending_recall:
1966
  _ans = _affirm_or_deny(user_text)
1967
  if _ans is True:
1968
+ # 2026-05-27 β€” user_text plumbed in so the same-turn age
1969
+ # contradiction guard inside apply_pending_recall can
1970
+ # discard a wrong-person "Yes I'm 35" reply before merging.
1971
  _did_recall_this_turn = bool(
1972
+ apply_pending_recall(
1973
+ session, confirmed=True, user_text=user_text,
1974
+ )
1975
  )
1976
  _pending_recall = None
1977
  elif _ans is False:
1978
+ apply_pending_recall(
1979
+ session, confirmed=False, user_text=user_text,
1980
+ )
1981
  _pending_recall = None
1982
  # ambiguous β†’ leave staged; the confirm block is re-injected
1983
  # below and the LLM re-asks the "are you <name>?" question.