+
    .pÐjn  ã                  óØ   € R t ^ RIHt ^ RIt^ RIt^ RIt^ RIt^ RIHt ^ RI	H
t
HtHtHt ^ RIHt ]
'       d   ^ RIHt ]P$                  ! R4      t]! 4       tRtR	 R
 lt ! R R4      tR# )a  SessionStore storage plumbing: per-profile SessionDB handle resolution and the routing-index
load/save paths (state.db gateway_routing primary, sessions.json legacy mirror). Mixin split out of
``gateway/session.py``; bound onto ``SessionStore`` via the MRO.)ÚannotationsN)ÚPath)ÚTYPE_CHECKINGÚAnyÚDictÚOptional)Úatomic_json_write©ÚSessionEntryzgateway.sessiona©  LEGACY MIRROR of the gateway routing index (the primary copy lives in the gateway_routing table in ~/.hermes/state.db). Maps messaging session keys (agent:main:<platform>:...) to active session IDs. This is NOT the session list. ALL sessions (CLI, TUI, and gateway) live in ~/.hermes/state.db and are shown by `hermes sessions list` and `/sessions`. Disable this file with `gateway.write_sessions_json: false` in config.yaml.c               ó    € V ^8„  d   QhRRRR/# )é   ÚexcÚBaseExceptionÚreturnÚbool© )Úformats   "Ú*/opt/hermes/gateway/session_persistence.pyÚ__annotate__r   #   s   € ÷ Mñ M˜}ð M°ñ Mó    c                óN   € \        V \        4      ;'       d    R\        V 4      9   # )zCTest-isolation guard: must stay a loud failure and is never cached.zlive-system guard)Ú
isinstanceÚRuntimeErrorÚstr)r   s   &r   Ú_is_live_system_guardr   #   s!   € ä�cœ<Ó(×LÐLÐ-@ÄCÈÃHÑ-LÐLr   c                  ó¼  € ] tR t^(tRtR@R R lltR t]R 4       t]P                  R R l4       t]R	 4       t
R
 R ltR R ltR R ltR R ltR R ltR R ltR R ltR R ltR R ltR R ltR R lt]R  R! l4       tR" R# ltR$ R% ltR& R' ltR( R) ltR* R+ ltR, R- ltR. R/ ltR0 R1 ltR2 R3 lt R4 R5 lt!R6 R7 lt"R8 R9 lt#R:RR;R</R= R> llt$R?t%R# )AÚSessionPersistenceMixinzWSessionStore storage plumbing: SessionDB handle resolution and routing-index load/save.Nc               ó   € V ^8„  d   QhRR/# )r   Údb_pathúOptional[Path]r   )r   s   "r   r   Ú$SessionPersistenceMixin.__annotate__+   s   € ÷ [ñ [¸ñ [r   c                ó®   aa€ ^ RI Hp ^ RIHo Ve   \	        V4      M\	        V! 4       4      oVV3R lpV P
                  P                  SV\        R7      # )aù  SessionDB for the active profile scope. ``db_path`` pins the store; otherwise
``_default_db_path()`` follows the context-local HERMES_HOME (resolved per call so
multiplexed profiles reach their own store). Handles are cached per path; failed opens enter
a bounded backoff during which callers keep using the JSONL fallback.

Resolving here rather than once in ``__init__`` is the whole fix for #88532: it lets the scoping
that the multiplexed inbound path already performs actually reach session storage.
)Ú_default_db_path)Úacquirec                 ó|   <€  S! S4      #   \          d&   p \        T 4      '       g   \        R T  24       h Rp ? ii ; i)zL[gateway] Warning: SQLite session store unavailable, falling back to JSONL: N)Ú	Exceptionr   Úprint)Úer#   Úpaths    €€r   Ú_openÚHSessionPersistenceMixin._open_session_db_for_active_scope.<locals>._open9   sB   ø€ ðÙ˜t“}Ð$øÜô Ü,¨Q×/Ò/ÜÐhÐijÐhkÐlÔmØûðús   ƒ ‹;– 6¶;)Únon_cacheable)Úhermes_stater"   Úhermes_state_registryr#   r   Ú_db_handle_cacheÚgetr   )Úselfr   r"   r)   r#   r(   s   &&  @@r   Ú!_open_session_db_for_active_scopeÚ9SessionPersistenceMixin._open_session_db_for_active_scope+   sJ   ù€ õ 	2Ý1à 'Ò 3Œt�GŒ}¼Ñ>NÓ>PÓ9Qˆö	ð ×$Ñ$×(Ñ(¨¨uÔDYÐ(ÓZÐZr   c                ó$   € \        V R\        4      # )zKReturn the explicitly pinned DB (``store._db = x``), else ``_DB_UNPINNED``.Ú
_db_pinned)ÚgetattrÚ_DB_UNPINNED©r0   s   &r   Ú
_pinned_dbÚ"SessionPersistenceMixin._pinned_dbC   s   € ä�t˜\¬<Ó8Ð8r   c                óZ   € V P                  4       pV\        J d   V P                  4       # T# )a%  The SessionDB for the active profile scope, or a pinned override. Assigning ``store._db``
pins that value for every subsequent read (tests install a fake or disable the DB with
``store._db = None``); unpinned, each read resolves the scope so a multiplexed profile's
writes reach its own store.)r8   r6   r1   )r0   Úpinneds   & r   Ú_dbÚSessionPersistenceMixin._dbG   s,   € ð —‘Ó"ˆØ;AÄ\Ó;Qˆt×5Ñ5Ó7Ð]ÐW]Ð]r   c               ó   € V ^8„  d   QhRR/# ©r   r   ÚNoner   )r   s   "r   r   r    Q   s   € ÷  ñ  ˜Dñ  r   c                	ó   € Wn         R # ©N)r4   )r0   Úvalues   &&r   r<   r=   P   s   € àŽr   c                óÌ   € V P                  4       pV\        Jd   V# \        V RR4      p Vf   V P                  # V P	                  VR,          R7      #   \
         d     R# i ; i)u	  The one store that owns the routing index, whatever scope is active. ``_entries`` is one
flat dict holding every profile's keys, so it must persist to ONE file (``_routing_home``),
not whichever profile is scoped â€” otherwise a mid-turn rewrite and the unscoped startup
load see different copies and crash markers under a secondary profile go unrecovered. A
pinned handle still wins; bare test instances lacking the handle cache report no DB.

Reading it through ``_db`` made that file whichever profile happened to be scoped at the time: a
whole-index rewrite during one profile's turn copied every other profile's routing rows into that
profile's store, and startup â€” which runs unscoped â€” then loaded a different copy than the one the
last writer produced. See #66887.
Ú_routing_homeNústate.db©r   )r8   r6   r5   r<   r1   r%   )r0   r;   Úhomes   &  r   Ú_routing_dbÚ#SessionPersistenceMixin._routing_dbT   si   € ð —‘Ó"ˆØœÓ%ØˆMÜ�t˜_¨dÓ3ˆð	ØŠ|Ø—x‘x�Ø×9Ñ9À$ÈÕBSÐ9ÓTÐTøÜô 	Úð	ús   «A »A ÁA#Á"A#c               ó    € V ^8„  d   QhRRRR/# )r   Úsession_keyúOptional[str]r   r   )r   s   "r   r   r    l   s   € ÷ Hñ H°-ð HÀMñ Hr   c                óˆ   € \        V P                  RR4      '       g   R# V P                  V4      pV'       d   VR8X  d   R# T# )u  The non-default profile that owns *session_key*, or None (ambient store is authoritative:
multiplexing off, or legacy ``agent:main``). Deliberately does NOT cover "that profile has
no directory" â€” ownership and resolvability are separate questions for ``_db_for_key``.Úmultiplex_profilesFNÚdefault)r5   ÚconfigÚ_profile_from_session_key)r0   rL   Úprofiles   && r   Ú_named_profile_for_keyÚ.SessionPersistenceMixin._named_profile_for_keyl   s?   € ô �t—{‘{Ð$8¸%×@Ò@ÙØ×0Ñ0°Ó=ˆß" g°Ô&:ˆtÐGÀÐGr   c               ó    € V ^8„  d   QhRRRR/# )r   rL   rM   r   r   r   )r   s   "r   r   r    u   s   € ÷ ñ °ð À>ñ r   c                ó,  € V P                  V4      pVf   R# V P                  pW#9   d	   W2,          # Rp ^ RIHpHp V! V4      '       d   \        V! V4      4      pTe   YCT&   T#   \         d#   p\        P                  RY4       Rp Rp?L2Rp?ii ; i)zZHERMES_HOME of the profile owning *session_key*, or None (no named owner or
unresolvable).N)Úget_profile_dirÚprofile_existsz)Could not resolve profile home for %r: %s)	rT   Ú_profile_home_cacheÚhermes_cli.profilesrX   rY   r   r%   ÚloggerÚdebug)r0   rL   rS   ÚcacherH   rX   rY   r   s   &&      r   Ú_profile_home_for_keyÚ-SessionPersistenceMixin._profile_home_for_keyu   s–   € ð ×-Ñ-¨kÓ:ˆØŠ?ÙØ×(Ñ(ˆØÔØ•>Ð!Ø#ˆð	ßKÙ˜g×&Ò&Ü™O¨GÓ4Ó5�ð ÒØ!�'‰NØˆøô ô 	Ü�L‰LÐDÀkÔWØ�Dûð	ús   µA& ÁA& Á&BÁ1BÂBc               ó   € V ^8„  d   QhRR/# )r   rL   rM   r   )r   s   "r   r   r    Œ   s   € ÷ &ñ & }ñ &r   c                óâ  € V P                  4       pV\        Jd   V# V P                  V4      pVfU   \        V RR4      pVe   \        V P                  RR4      '       g   V P
                  #  V P                  VR,          R7      # V P                  V4      pVf   \        P                  RW14       R#  V P                  VR,          R7      #   \         d     R# i ; i  \         d     R# i ; i)u(  The SessionDB holding *session_key*'s rows, whatever scope is active (the owning profile
is encoded in the key). ``_db`` follows the ambient HERMES_HOME that only the inbound message
path installs; unscoped background work (expiry watcher) would otherwise write profile rows
into the ROOT store until the stale-route self-heal drops a live conversation.

Background work runs unscoped while operating on every profile's keys out of the single process-wide
``_entries`` dict â€” ``_session_housekeeping_watcher`` is the clearest case â€” so it reads and writes the
ROOT store for rows that actually live under ``profiles/<name>/state.db``. The two writers then
drift apart on the same logical session until the routing index disagrees with the row and the
#54878 self-heal drops a live conversation (#66887).
NrE   rO   FrF   rG   zggateway.session: profile %r has no resolvable home (key %r); refusing to fall back to the ambient store)r8   r6   rT   r5   rQ   r<   r1   r%   r_   r\   Úwarning)r0   rL   r;   rS   Úrouting_homerH   s   &&    r   Ú_db_for_keyÚ#SessionPersistenceMixin._db_for_keyŒ   sü   € ð —‘Ó"ˆØœÓ%ØˆMØ×-Ñ-¨kÓ:ˆØŠ?ô # 4¨¸$Ó?ˆLØÒ#¬7°4·;±;Ð@TÐV[×+\Ò+\Ø—x‘x�ðØ×=Ñ=ÀlÐU_ÕF_Ð=Ó`Ð`ð ×)Ñ)¨+Ó6ˆØŠ<ô �N‰Nð,Ø-4ôCñ ð	Ø×9Ñ9À$ÈÕBSÐ9ÓTÐTøô ô Úðûô ô 	Úð	ús$   Á-C Â4C ÃCÃCÃC.Ã-C.c               ó    € V ^8„  d   QhRRRR/# )r   Ú
session_idrM   r   r   )r   s   "r   r   r    ´   s   € ÷ Sñ S°Mð SÀmñ Sr   c                ó  € V'       g   R#  \        V P                  P                  4       4       F"  pVP                  V8X  g   K  VP                  u # 	  \        V RR4      ;'       g    / P                  V4      #   \
         d     L3i ; i)zúThe routing key that owns *session_id*, or None. The published index is authoritative;
``_session_owner_hints`` covers the window where ownership is proven but routing not yet
published. Deliberately lock-free: several callers already hold ``_lock``.NÚ_session_owner_hints)ÚlistÚ_entriesÚvaluesrh   rL   r%   r5   r/   )r0   rh   Úentrys   && r   Ú_owner_key_for_session_idÚ1SessionPersistenceMixin._owner_key_for_session_id´   s~   € ÷ Ùð	Ü˜dŸm™m×2Ñ2Ó4Ö5�Ø×#Ñ# zÖ1Ø ×,Ñ,Ò,ñ 6ô
 ˜Ð4°dÓ;×AÐA¸r×FÑFÀzÓRÐRøô ô 	Ùð	ús   Œ4A; ÁA; ÁA; Á;B	ÂB	c               ó   € V ^8„  d   QhRR/# )r   rh   rM   r   )r   s   "r   r   r    Â   s   € ÷ Lñ L¨]ñ Lr   c                ój   € V'       g   V P                   # V P                  V P                  V4      4      # )z„The SessionDB holding *session_id*'s row (owner from the index or a pre-published hint;
unknown ids fall back to the ambient store).)r<   re   ro   )r0   rh   s   &&r   Ú_db_for_session_idÚ*SessionPersistenceMixin._db_for_session_idÂ   s,   € ÷ Ø—8‘8ˆOØ×Ñ × >Ñ >¸zÓ JÓKÐKr   c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    É   s   € ÷ 0ñ 0 dñ 0r   c                óH   € R R lpV P                   P                  V4       R# )a
  Close every SessionDB handle this store opened (one per path). Closing only ``store._db``
would strand secondary profiles' handles with their WAL lock held ('database is locked' on
restart). Drained under the lock, closed outside it; a pinned handle is the pinner's.c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   ÚBSessionPersistenceMixin.close_all_db_handles.<locals>.__annotate__Í   s   € ÷ 	Sñ 	S˜$ñ 	Sr   c                ó‚   € ^ RI Hp  V! V 4       R#   \         d"   p\        P	                  RT4        Rp?R# Rp?ii ; i)é    )Úrelease_or_closez-SessionDB close error during handle sweep: %sN)r-   r{   r%   r\   r]   )Údbr{   r   s   &  r   Ú_closeÚ<SessionPersistenceMixin.close_all_db_handles.<locals>._closeÍ   s7   € Ý>ðSÙ  Ö$øÜô SÜ—‘ÐLÈc×RÒRûðSús   ˆ ’>�9¹>N)r.   Ú	close_all)r0   r}   s   & r   Úclose_all_db_handlesÚ,SessionPersistenceMixin.close_all_db_handlesÉ   s   € õ	Sð 	×Ñ×'Ñ'¨Ö/r   c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    Ö   s   € ÷ )ñ ) ñ )r   c                óˆ   € V P                   ;_uu_ 4        V P                  4        RRR4       R#   + '       g   i     R# ; i)z4Load sessions index from disk if not already loaded.N)Ú_lockÚ_ensure_loaded_lockedr7   s   &r   Ú_ensure_loadedÚ&SessionPersistenceMixin._ensure_loadedÖ   s#   € à�Z�Z‹ZØ×&Ñ&Ô(÷ �Z�ZŠZús	   •0°A	c               ó    € V ^8„  d   QhRRRR/# )r   rL   r   r   úOptional[SessionEntry]r   )r   s   "r   r   r    Û   s   € ÷ .ñ .¨ð .Ð1Gñ .r   c                óX   € V P                  4        V P                  P                  V4      # )zALoad the index and return the entry for *session_key*. Lock held.)r…   rl   r/   )r0   rL   s   &&r   Ú_entry_lockedÚ%SessionPersistenceMixin._entry_lockedÛ   s#   € à×"Ñ"Ô$Ø�}‰}× Ñ  Ó-Ð-r   c               ó   € V ^8„  d   QhRR/# )r   r   r   r   )r   s   "r   r   r    à   s   € ÷ *ñ * ñ *r   c                ó¨   €  \        \        V P                  4      P                  4       4      #   \         d    \        T P                  4      u # i ; i)z~Namespace for this store's gateway_routing rows: the resolved sessions_dir, so stores
with different dirs never share entries.)r   r   Úsessions_dirÚresolver%   r7   s   &r   Ú_routing_scopeÚ&SessionPersistenceMixin._routing_scopeà   sF   € ð	*Ü”t˜D×-Ñ-Ó.×6Ñ6Ó8Ó9Ð9øÜô 	*Ü�t×(Ñ(Ó)Ò)ð	*ús   ‚+. ® AÁAc               ó   € V ^8„  d   QhRR/# )r   Únamer   r   )r   s   "r   r   r    è   s   € ÷ 4ñ 4 sñ 4r   c                ón   € \        V P                  ;'       g    RVR4      p\        V4      '       d   V# R# )zHBound ``_routing_db.<name>`` if the handle exists and has it, else None.N)r5   rI   Úcallable)r0   r”   Úmethods   && r   Ú_routing_db_methodÚ*SessionPersistenceMixin._routing_db_methodè   s3   € ä˜×)Ñ)×1Ð1¨T°4¸Ó>ˆÜ! &×)Ò)ˆvÐ3¨tÐ3r   c               ó   € V ^8„  d   QhRR/# )r   r   r   r   )r   s   "r   r   r    í   s   € ÷ ñ ¨4ñ r   c                ó:  € V P                  R4      pVf   R#  V! V P                  4       R7      P                  4        F*  w  r#V P                  W#4      pVf   K  W@P                  V&   K,  	  R#   \
         d"   p\        P                  RT4        Rp?R# Rp?ii ; i)zvLoad state.db routing entries into ``_entries``; False when there is no loader or the
load failed (warned). Lock held.Úload_gateway_routing_entriesNF©ÚscopeTz1gateway.session: state.db routing load failed: %s)r˜   r‘   ÚitemsÚ_routing_entry_from_jsonrl   r%   r\   rc   )r0   ÚloaderÚkeyÚ
entry_jsonrn   r'   s   &     r   Ú_load_routing_rows_lockedÚ1SessionPersistenceMixin._load_routing_rows_lockedí   s�   € ð ×(Ñ(Ð)GÓHˆØŠ>Ùð	Ù#)°×0CÑ0CÓ0EÔ#F×#LÑ#LÖ#N‘�Ø×5Ñ5°cÓF�ØÔ$Ø).—M‘M #Ó&ñ $Oñ øÜô 	Ü�N‰NÐNÐPQÔRÝûð	ús   ™<A. ÁA. Á.BÁ9BÂBc               ó$   € V ^8„  d   QhRRRRRR/# )r   r¢   r   r£   r   r‰   r   )r   s   "r   r   r    þ   s"   € ÷ 	ñ 	 cð 	°sð 	Ð?Uñ 	r   c                ó  € ^ RI Hp  \        P                  ! V4      p\	        V\
        4      '       d   VP                  ! V4      #  R#   \        \        \        3 d"   p\        P                  RY4        Rp?R# Rp?ii ; i)zBParse one gateway_routing row; None (with a warning) when invalid.r	   z%Skipping invalid routing entry %r: %sN)Úgateway.sessionr
   ÚjsonÚloadsr   ÚdictÚ	from_dictÚ
ValueErrorÚKeyErrorÚ	TypeErrorr\   rc   )r¢   r£   r
   Ú
entry_datar'   s   &&   r   r    Ú0SessionPersistenceMixin._routing_entry_from_jsoný   ss   € õ 	1ð	LÜŸš JÓ/ˆJÜ˜*¤d×+Ò+Ø#×-Ò-¨jÓ9Ð9ð ,ñ øô œH¤iÐ0ô 	LÜ�N‰NÐBÀC×KÐKÙûð	Lús   ˆ=A	 Á	B ÁA;Á;B c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    	  s   € ÷ ,ñ , tñ ,r   c                ó€  € V P                   '       d   V P                  4        R# V P                  P                  RRR7       V P	                  4       pT;'       d    \        V P                  4      pV P                  V4       RV n         Wn        V'       d   RMV P                  4       V n
        V P                  4        R# )a®  Load the routing index (lock held). state.db ``gateway_routing`` is primary;
sessions.json is the legacy import for keys the DB lacks (persisted on the next _save).

Read order (#9006 follow-up): the ``gateway_routing`` table in state.db is the primary source;
sessions.json is the legacy import path for pre-migration installs (its entries are folded in for
keys the DB doesn't have, then persisted to the DB on the next _save).
NT)ÚparentsÚexist_ok)Ú_loadedÚ#_reconcile_recovered_routing_lockedr�   Úmkdirr¤   r   rl   Ú_import_legacy_sessions_jsonÚ_routing_db_loadedÚ_entries_as_dictsÚ_routing_fallback_baselineÚ_prune_stale_sessions_locked)r0   Údb_load_succeededÚdb_had_entriess   &  r   r…   Ú-SessionPersistenceMixin._ensure_loaded_locked	  s–   € ð �<�<ˆ<Ø×4Ñ4Ô6ÙØ×Ñ×Ñ¨°tÐÔ<Ø ×:Ñ:Ó<ÐØ*×BÐB¬t°D·M±MÓ/BˆØ×)Ñ)¨.Ô9ØˆŒØ"3Ôß2C©$È×I_ÑI_ÓIaˆÔ'à×)Ñ)Ö+r   c               ó    € V ^8„  d   QhRRRR/# )r   r¿   r   r   r@   r   )r   s   "r   r   r      s   € ÷ Fñ F¸4ð FÀDñ Fr   c                ó‚  € ^ RI Hp V P                  R,          pVP                  4       '       g   R#  \	        VRRR7      ;_uu_ 4       p\
        P                  ! V4      pRRR4       ^ pXP                  4        F™  w  rxVP                  R4      '       g   WpP                  9   d   K.  \        V\        4      '       g-   \        P                  RV\        V4      P                  4       Kp   VP                   ! V4      V P                  V&   V^,          pK›  	  V'       d,   V'       d"   \        P)                  R
Yf^8X  d   RMR4       R# R# R#   + '       g   i     Lô; i  \"        \$        \&        3 d#   p	\        P                  R	Yy4        Rp	?	EK  Rp	?	ii ; i  \*         d   p	\-        RT	 24        Rp	?	R# Rp	?	ii ; i)zELegacy import: sessions.json fills only keys the DB lacks. Lock held.r	   úsessions.jsonNÚrz	utf-8-sig)ÚencodingÚ_z8Skipping invalid session entry %r: expected dict, got %sz%Skipping invalid session entry %r: %sz\gateway.session: imported %d legacy sessions.json entr%s missing from state.db routing tableÚyÚiesz,[gateway] Warning: Failed to load sessions: )r¨   r
   r�   ÚexistsÚopenr©   ÚloadrŸ   Ú
startswithrl   r   r«   r\   rc   ÚtypeÚ__name__r¬   r­   r®   r¯   Úinfor%   r&   )
r0   r¿   r
   Úsessions_fileÚfÚdataÚimportedr¢   r°   r'   s
   &&        r   r¹   Ú4SessionPersistenceMixin._import_legacy_sessions_json  se  € å0Ø×)Ñ)¨OÕ;ˆØ×#Ñ#×%Ò%Ùð	FÜ�m S°;×?Õ?À1Ü—y’y “|�÷ @àˆHØ#'§:¡:¦<‘�à—>‘> #×&Ò&¨#·±Ô*>ÙÜ! *¬d×3Ò3Ü—N‘NØRÐTWÜ˜ZÓ(×1Ñ1ô3ñ ðTØ)5×)?Ò)?À
Ó)K�D—M‘M #Ñ&Ø •M’Hñ $0÷ ŸNÜ—‘ð-Ø.6È1¼}¹ÐRWöYñ +‰x÷# @×?ûô #¤H¬iÐ8ô TÜ—N‘NÐ#JÈC×SÓSûðTûô ô 	FÜÐ@ÀÀÐD×EÒEûð	Fúsf   ³F Á	EÁ B
F Ã+(EÄF ÄF Ä'F ÅE	ÅF ÅFÅ5FÆF ÆFÆF ÆF>Æ%F9Æ9F>c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    =  s   € ÷ ñ ¨dñ r   c                ót  € V P                   '       g   R# . p^ p V P                   P                  4        F™  w  r4V P                  V4      pVf   K  VP                  VP                  4      pVe   VP                  R4      f   KP  V P                  W4V4      pVR8X  d   VP                  V4       K|  Vf   K‚  WpP                   V&   V^,          pK›  	  T F  pT P                   T K  	  T'       g	   T'       d   T P                  4        R# R#   \         d"   p\        P                  RT4        Rp?R# Rp?ii ; i)zÑRemove routing entries whose session has ended in state.db (startup, lock held). Stale ==
``end_reason IS NOT NULL``; rows absent from the DB are kept; a ``None`` DB handle is a
no-op; DB errors are non-fatal.NÚ
end_reasonÚprunez@gateway.session: stale-entry pruning skipped due to DB error: %s)rl   rŸ   re   Úget_sessionrh   r/   Ú_stale_entry_verdictÚappendr%   r\   rc   Ú_save)	r0   Ú
stale_keysÚrecovered_keysr¢   rn   r|   ÚrowÚverdictr   s	   &        r   r½   Ú4SessionPersistenceMixin._prune_stale_sessions_locked=  s  € ð �}�}ˆ}ÙØˆ
Øˆð	Ø"Ÿm™m×1Ñ1Ö3‘
�ð ×%Ñ% cÓ*�Ø’:ÙØ—n‘n U×%5Ñ%5Ó6�Ø’; #§'¡'¨,Ó"7Ò"?ÙØ×3Ñ3°CÀÓD�Ø˜gÔ%Ø×%Ñ% cÖ*ØÔ(Ø)0—M‘M #Ñ&Ø" aÕ'’Nñ 4ó$ ˆCØ—‘˜cÒ"ñ çŸØ�J‰JŽLñ (øô ô 	Ü�N‰NÐ]Ð_bÔcÝûð	ús   šBD Â6D ÄD7ÄD2Ä2D7c               ó   € V ^8„  d   QhRR/# )r   r¢   r   r   )r   s   "r   r   r    ]  s   € ÷ *ñ *¨ñ *r   c                óÜ  € ^ RI Hp RpVP                  e%    V P                  WP                  V! 4       RR7      pVež   VP                  VP                  8w  dƒ   \
        P                  RWP                  VR,          VP                  4       VP                  '       d<   V P                  VP                  4      VP                  8X  d   VP                  Vn	        V# Ve+   \
        P                  RVP                  WR,          4       R# \
        P                  R	WP                  VR,          4       R
#   \         d-   p\
        P                  RYP                  T4        Rp?R# Rp?ii ; i)zjFor a routing entry whose row has ended: ``"prune"``, a replacement entry (repoint), or
None (keep as-is).)Ú_nowNT)rL   ÚsourceÚnowÚraise_on_lookup_errorzRgateway.session: recovery lookup failed for stale sessions.json entry %r -> %s: %szfgateway.session: repointing stale sessions.json entry %r from ended %s (end_reason=%r) to recovered %sr×   zdgateway.session: reopened ended session %s for sessions.json entry %r (end_reason=%r); keeping routezfgateway.session: pruning stale sessions.json entry %r -> %s (end_reason=%r); left by a crashed gatewayrØ   )Úgateway.session_lifecyclerä   ÚoriginÚ_recover_session_from_dbr%   r\   r]   rh   rc   Ú
prompt_pinÚ_compression_tip_for_session_idrÏ   )r0   r¢   rn   rß   rä   Úrecovered_entryr   s   &&&&   r   rÚ   Ú,SessionPersistenceMixin._stale_entry_verdict]  sR  € õ 	3ØˆØ�<‰<Ò#ðØ"&×"?Ñ"?Ø #¯L©L¹d»fÐ\`ð #@ó #b�ð Ò&¨?×+EÑ+EÈ×IYÑIYÔ+YÜ�N‰Nð2Ø36×8HÑ8HÈ#ÈlÕJ[Ø×*Ñ*ô,ð ××ÐØ×4Ñ4°U×5EÑ5EÓFÈ/×JdÑJdÔdð .3×-=Ñ-=�Ô*Ø"Ð"ð Ò&Ü�K‰Kð1Ø27×2BÑ2BÀCÈ\ÕIZô\ñ Ü�‰ð Ø!$×&6Ñ&6¸¸LÕ8Iô	Kñ øôC ô ä—‘ðØ!×#3Ñ#3°Sô:õ ûðús   ˜#D4 Ä4E+Ä?!E&Å&E+c               ó   € V ^8„  d   QhRR/# )r   r   údict[str, Any]r   )r   s   "r   r   r    ‰  s   € ÷ Nñ N >ñ Nr   c                ó†   € V P                   P                  4        UUu/ uF  w  rWP                  4       bK  	  upp# u uppi )z1Serializable snapshot of ``_entries``. Lock held.)rl   rŸ   Úto_dict)r0   r¢   rn   s   &  r   r»   Ú)SessionPersistenceMixin._entries_as_dicts‰  s4   € à7;·}±}×7JÑ7JÔ7LÔMÑ7L©¨�—]‘]“_Ò$Ñ7LÒMÐMùÓMs   ž=c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    �  s   € ÷ Eñ E�tñ Er   c                óB   € V P                   ! V P                  4       !   R# )z;Persist the routing index while the caller holds ``_lock``.N)Ú_persist_routing_dataÚ_snapshot_routing_lockedr7   s   &r   rÜ   ÚSessionPersistenceMixin._save�  s   € à×"Ò" D×$AÑ$AÓ$CÔDr   c               ó   € V ^8„  d   QhRR/# )r   r   Úintr   )r   s   "r   r   r    ‘  s   € ÷ (ñ (°ñ (r   c                óL   € \        V R^ 4      ^,           V n        V P                  # )zëBump and return the shared routing counter (lock held). Full snapshots AND single-entry
fast saves MUST allocate from this one counter: the stale-write protection is a total order
over serialization times and silently breaks otherwise.Ú_routing_generation)r5   rü   r7   s   &r   Ú_next_routing_generation_lockedÚ7SessionPersistenceMixin._next_routing_generation_locked‘  s'   € ô $+¨4Ð1FÈÓ#JÈQÕ#NˆÔ Ø×'Ñ'Ð'r   c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    ˜  s   € ÷ /ñ /°Tñ /r   c                óF  € \        V RR4      p\        V RR4      '       g   Vf   R# V P                  R4      pVf   R#  V! V P                  4       R7      pT P                  4       pTP                  4        Fj  w  rgT P                  Yg4      pTf   K  Ya9  d   T P                  P                  Yh4       K?  Ye9  d   KG  YV,          Y,          8X  g   K\  Y€P                  T&   Kl  	  RT n        RT n        R#   \         d"   p\        P                  RT4        Rp?R# Rp?ii ; i)	z<Merge authoritative rows after a fallback-only startup load.r¼   Nrº   Frœ   r�   z;gateway.session: recovered state.db routing load failed: %sT)r5   r˜   r‘   r%   r\   rc   r»   rŸ   r    rl   Ú
setdefaultrº   r¼   )	r0   Úbaseliner¡   Údurabler   Úcurrentr¢   r£   Údurable_entrys	   &        r   r·   Ú;SessionPersistenceMixin._reconcile_recovered_routing_locked˜  s  € ä˜4Ð!=¸tÓDˆÜ�4Ð-¨u×5Ò5¸Ò9IÙØ×(Ñ(Ð)GÓHˆØŠ>Ùð	Ù 4×#6Ñ#6Ó#8Ô9ˆGð ×(Ñ(Ó*ˆØ&Ÿ}™}ž‰OˆCØ ×9Ñ9¸#ÓJˆMØÒ$ÙØÔ"ð —‘×(Ñ(¨Ö<ØÔ#ÙØ• ¥Ö.Ø%2—‘˜cÓ"ñ  /ð #'ˆÔØ*.ˆÖ'øô# ô 	Ü�N‰NÐXÐZ]Ô^Ýûð	ús   ¿C4 Ã4D Ã?DÄD c               ó   € V ^8„  d   QhRR/# )r   r   ztuple[dict[str, Any], int]r   )r   s   "r   r   r    µ  s   € ÷ Pñ PÐ*Dñ Pr   c                ób   € V P                  4        V P                  4       V P                  4       3# )z:Capture immutable routing data and a monotonic generation.)r·   r»   rý   r7   s   &r   r÷   Ú0SessionPersistenceMixin._snapshot_routing_lockedµ  s+   € à×0Ñ0Ô2Ø×%Ñ%Ó'¨×)MÑ)MÓ)OÐOÐOr   c               ó$   € V ^8„  d   QhRRRRRR/# )r   rÒ   rð   Ú
generationrú   r   r@   r   )r   s   "r   r   r    º  s!   € ÷ $,ñ $,¨.ð $,Àcð $,Èdñ $,r   c                ó  € V P                  R\        P                  4      ;_uu_ 4        V\        V R^ 4      8:  d    RRR4       R# \        V RR4      pV'       d=   VP	                  4        F(  w  pw  rVWR8”  g   K  \
        P                  ! V4      W&   K*  	  RpV P                  R4      pVeS    T! VP	                  4        U	U
u/ uF  w  ršV	\
        P                  ! V
4      bK  	  up
p	V P                  4       R7       Rp\        V R
R4      '       g	   V'       g    V P                  V4       W n        V'       d;   VP	                  4        U	UUu. uF  w  p	w  rÍWÂ8:  g   K  V	NK  	  uppp	 F  pW4 K  	  RRR4       R# u up
p	i   \         d!   p\        P                  R	T4        Rp?L«Rp?ii ; i  \         d*   pT'       g   h \        P                  RT4        Rp?LµRp?ii ; iu uppp	i   + '       g   i     R# ; i)zASerialize all whole-index writers through one durable write lock.Ú
_save_lockÚ_persisted_routing_generationNÚ_fast_persisted_entriesFÚreplace_gateway_routing_entriesr�   Tz1gateway.session: state.db routing save failed: %sÚ_write_sessions_jsonzKgateway.session: sessions.json mirror save failed after state.db commit: %s)Ú_lazyÚ	threadingÚLockr5   rŸ   r©   rª   r˜   Údumpsr‘   r%   r\   rc   Ú_save_sessions_jsonr  )r0   rÒ   r  Úfast_persistedr¢   Úrevisionr£   Údb_savedÚreplacerÚkÚvr   ÚrevrÆ   s   &&&           r   rö   Ú-SessionPersistenceMixin._persist_routing_dataº  s¿  € à�Z‰Z˜¤i§n¡n×5Õ5ØœW TÐ+JÈAÓNÔNØ÷ 6Ñ5ô
 % TÐ+DÀdÓKˆNßØ3A×3GÑ3GÖ3IÑ/�CÑ/˜(ØÖ,Ü$(§J¢J¨zÓ$:˜›	ñ 4Jð ˆHØ×.Ñ.Ð/PÓQˆHØÒ#ð]Ù¸4¿:¹:¼<ÔH¹<±4°1˜a¤§¢¨A£Ò.¹<ÒHÐPT×PcÑPcÓPeÕfØ#�Hô �tÐ3°T×:Ò:Ç(ð	#Ø×,Ñ,¨TÔ2ð 2<Ô.÷ Ø1?×1EÑ1EÔ1GÕ]Ñ1G¡+ !¡X cÈ3ÑK\ŸA˜AÑ1GÖ]�CØ&Ò+ñ ^÷C 6Ñ5ùó Iøä ô ]Ü—N‘NÐ#VÐX[×\Ñ\ûð]ûô
 !ô #ß#Øô —N‘NðØ!÷#ñ #ûð#üô ^÷C 6×5Ð5ús�   ©G2Á0G2Á<3G2Â0FÃ"F Ã'FÄG2ÄF4Ä."G2ÅG+Å"G+Å(G2Æ FÆF1ÆF,Æ'G2Æ,F1Æ1G2Æ4G(Æ?G#ÇG2Ç#G(Ç(
G2Ç2H	c               ó    € V ^8„  d   QhRRRR/# )r   rÒ   rð   r   r@   r   )r   s   "r   r   r    à  s   € ÷ wñ w¨ð w¸4ñ wr   c                óT   € \        V P                  R,          R\        /VCRR7       R# )zLWrite the legacy sessions.json mirror of the routing index (atomic + fsync).rÃ   Ú_READMEi€  )ÚmodeN)r   r�   Ú_SESSIONS_JSON_README)r0   rÒ   s   &&r   r  Ú+SessionPersistenceMixin._save_sessions_jsonà  s&   € ä˜$×+Ñ+¨oÕ=À	ÔK`Ð?iÐdhÐ?iÐpu×vr   c               ó   € V ^8„  d   QhRR/# r?   r   )r   s   "r   r   r    ä  s   € ÷ 5ñ 5˜tñ 5r   c                ó®   € V P                   ;_uu_ 4        V P                  4       w  rRRR4       V P                  XX4       R#   + '       g   i     L$; i)zESnapshot latest state under ``_lock`` and persist after releasing it.N)r„   r÷   rö   )r0   rÒ   r  s   &  r   Ú_save_entriesÚ%SessionPersistenceMixin._save_entriesä  s9   € à�Z�Z‹ZØ#×<Ñ<Ó>ÑˆD÷ à×"Ñ" 4¨Ö4÷ �Zús   •AÁA	r°   Ú	lock_heldFc               ó(   € V ^8„  d   QhRRRRRRRR/# )	r   rL   r   r°   zOptional[dict[str, Any]]r)  r   r   r@   r   )r   s   "r   r   r    ê  s,   € ÷ +!ñ +!Øð+!Ø/Gð+!àð+!à$(ñ+!r   c               ón  € V'       d   \         P                  ! 4       MV P                  pT;_uu_ 4        V P                  P	                  V4      pVf    RRR4       R# Ve   \        V4      MVP                  4       p\        P                  ! V4      V P                  4       r‡RRR4       V P                  R4      p	V	e´    V P                  R\        P                  4      ;_uu_ 4        \        V R^ 4      X8¼  d    RRR4       R# V P                  R\
        4      p
V
P	                  V4      pVe   V^ ,          V8¼  d    RRR4       R# V	! VXV P                  4       R7       W‡3W¡&   RRR4       R# VeF   V;_uu_ 4        V P'                  4       pRRR4       \        V4      XV&   V P)                  VX4       R# V P+                  4        R#   + '       g   i     EL4; i  + '       g   i     R# ; i  \          d!   p\"        P%                  RY4        Rp?L©Rp?ii ; i  + '       g   i     Lš; i)uÅ  Persist ONE routing entry via UPSERT â€” the per-turn fast path (a full rewrite fsyncs a
multi-MB sessions.json). The key -> session_id mapping never changes here: structural
transitions use the full rewrite (which also refreshes the sessions.json mirror; it may lag
in metadata only). The revision comes from the shared routing generation counter; under
``_save_lock`` the upsert is skipped if a full snapshot or a newer fast save of this key
already persisted (the reverse case lives in ``_persist_routing_data``). No DB or a failed
upsert falls back to the full rewrite. ``entry_data`` persists a candidate BEFORE it is
published to the live entry (failure-atomic transitions); the fallback carries it too.NÚsave_gateway_routing_entryr  r  r  r�   zagateway.session: single-entry routing save failed for %r (%s); falling back to full index rewrite)Ú
contextlibÚnullcontextr„   rl   r/   r«   rò   r©   r  rý   r˜   r  r  r  r5   r‘   r%   r\   rc   r»   rö   r'  )r0   rL   r°   r)  Úguardrn   Ú
serializedr£   r  Úsaverr  Ú	persistedr   Úfallback_datas   &&$$          r   Ú_save_entryÚ#SessionPersistenceMixin._save_entryê  sÇ  € ÷ -6”
×&Ò&Ô(¸4¿:¹:ˆßŠUØ—M‘M×%Ñ% kÓ2ˆEØŠ}Ø÷ ‰Uð .8Ò-Cœ˜jÔ)ÈÏÉËˆJä#'§:¢:¨jÓ#9¸4×;_Ñ;_Ó;a˜÷ ð ×'Ñ'Ð(DÓEˆØÒð?Ø—Z‘Z ¬i¯n©n×=Õ=Ü˜tÐ%DÀaÓHÈHÔTØ÷ >Ñ=ð &*§Z¡ZÐ0IÌ4Ó%P�NØ .× 2Ñ 2°;Ó ?�IØ Ò,°¸1µÀÔ1IØ÷ >Ñ=ñ ˜+ z¸×9LÑ9LÓ9NÕOØ3;Ð2H�NÑ/÷ >ñ ð
 Ò!ç’Ø $× 6Ñ 6Ó 8�÷ ä)-¨jÓ)9ˆM˜+Ñ&Ø×&Ñ& }°hÖ?à×ÑÖ ÷? �UˆUú÷ >Ö=ñ ûÜô ?Ü—‘ð,Ø-8÷?ñ ?ûð?ú÷ —úsl   ´!GÁAGÃ(G6 Ã)G"Ã=G6 Ä:G"ÅG6 ÅG"Å)G6 ÆH$ÇG	Ç"G3	Ç-G6 Ç3G6 Ç6H!ÈHÈH!È$H4	)r4   r¶   r  rº   r¼   rü   rB   )&rÎ   Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r1   r8   Úpropertyr<   ÚsetterrI   rT   r_   re   ro   rs   r€   r†   r‹   r‘   r˜   r¤   Ústaticmethodr    r…   r¹   r½   rÚ   r»   rÜ   rý   r·   r÷   rö   r  r'  r4  Ú__static_attributes__r   r   r   r   r   (   sÿ   † Ùa÷[ò09ð ñ^ó ð^ð 	‡Z�Zô ó ð ð ñó ðõ.Hõõ.&õPSõLõ0õ)õ
.õ
*õ4õ
ð  ô	ó ð	õ,õ*Fõ>õ@*õXNõEõ(õ/õ:Põ
$,õLwõ5ð+!ØJNð+!à÷+!ó +!r   r   )r9  Ú
__future__r   r-  Úloggingr©   r  Úpathlibr   Útypingr   r   r   r   Úutilsr   r¨   r
   Ú	getLoggerr\   Úobjectr6   r#  r   r   r   r   r   Ú<module>rE     sg   ðñDõ #ã Û Û Û Ý ß 5Ó 5Ý #çÝ,ð 
×	Ò	Ð,Ó	-€ñ ‹x€ðEð õM÷
m!ó m!r   