
    iO                        d Z ddlZddlmc mZ ddlZddlZddl	Z	ddl
mc mZ ddlmZmZmZ ddlZddlZe	j(                  j+                  dd       ddlmZmZ ddlmZmZmZmZmZ ddlm Z  ddl!m"Z" dd	l#m$Z$m%Z% d'd
e&defdZ'd(dedefdZ( G d d      Z) G d d      Z* G d d      Z+ G d d      Z, G d d      Z- G d d      Z. G d d      Z/ G d d      Z0 G d d       Z1 G d! d"      Z2 G d# d$      Z3 G d% d&      Z4y))u_  
VERIFICATION_STAMP
Story: 2.07 (Track B)
Verified By: parallel-builder
Verified At: 2026-02-25T00:00:00Z
Tests: 12/12
Coverage: 100%

Module 2 Black-Box Test Suite — JIT Hydration Pipeline
Story 2.07 — Track B

Tests the full JIT hydration pipeline from the outside:
  - Redis L1 read/write contract
  - scatter_gather_memory concurrency and graceful degradation
  - zero_amnesia_envelope XML assembly and escaping
  - interceptor_jit_hydration end-to-end payload enrichment
  - JITHydrationInterceptor pre_execute and error handling

ALL external I/O is mocked. No live Redis, Qdrant, or KG required.
    N)	AsyncMock	MagicMockpatchz/mnt/e/genesis-system)RedisL1ClientRedisL1State)MemoryContextbuild_envelopeFALLBACK_WORKINGFALLBACK_KGFALLBACK_CONSTRAINTS)scatter_gather_memory)interceptor_jit_hydration)JITHydrationInterceptor_ERROR_ENVELOPEtask_idreturnc           
      ,    t        | d| ddgdg d d      S )Nzsess-abcredisqdrantzTesting JIT hydration   r   
session_idactive_task_idfocus_entitiescurrent_hypothesisexhausted_pathsactive_blockerversion)r   )r   s    :/mnt/e/genesis-system/tests/memory/test_redis_l1_schema.py_make_stater    +   s,    *2	 	    statec                    t               }| t        j                  | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                  d      }t        |      |_        nt        d      |_        t        d      |_        t        d      |_        t        d      |_        |S )zCReturn a mock aioredis client wired to return the given state JSON.Nr   )return_valueT   )r   jsondumpsr   r   r   r   r   r   r   r   getsetexincrdelete)r"   
mock_redisraws      r   _make_mock_redisr.   8   s    Jjj}}**#22#22"'":":$44#22}}	
 	 #4
"5
 d3JQ/JO!q1Jr!   c                       e Zd Zej                  j
                  d        Zej                  j
                  d        Zej                  j
                  d        Zy)TestRedisL1ReadWritec                 |  K   t        d      }t        d      }i fd}fd}t               }t        |      |_        t        |      |_        ||_        |j                  |       d{   }d}||u }|st        j                  d	|fd
||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }	dd|	iz  }
t        t        j                  |
            dx}}|j                  d       d{   }d}||u}|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }	dd|	iz  }
t        t        j                  |
            dx}}|j                   }|j                   }||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j"                  }|j"                  }||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j$                  }|j$                  }||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j&                  }|j&                  }||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j(                  }|j(                  }||k(  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}y7 7 w)zMset_state followed by get_state returns a RedisL1State with identical fields.ztask-set-getredis://fake:6379	redis_urlc                 "   K   | d<   |d<   yw)NkeyvalueT )r6   ttldatastored_datas      r   
fake_setexzSTestRedisL1ReadWrite.test_set_then_get_returns_equivalent_state.<locals>.fake_setex^   s     !$K#'K s   c                 X   K   | j                  d      k(  rj                  d      S y w)Nr6   r7   )r(   )r6   r;   s    r   fake_getzQTestRedisL1ReadWrite.test_set_then_get_returns_equivalent_state.<locals>.fake_getc   s*     kooe,,"w//s   '*side_effectNTisz%(py0)s is %(py3)s
set_resultpy0py3assert %(py5)spy5is notz%(py0)s is not %(py3)s	retrieved==)zL%(py2)s
{%(py2)s = %(py0)s.task_id
} == %(py6)s
{%(py6)s = %(py4)s.task_id
}r"   )rF   py2py4py6assert %(py8)spy8)zR%(py2)s
{%(py2)s = %(py0)s.session_id
} == %(py6)s
{%(py6)s = %(py4)s.session_id
})zb%(py2)s
{%(py2)s = %(py0)s.current_hypothesis
} == %(py6)s
{%(py6)s = %(py4)s.current_hypothesis
})zZ%(py2)s
{%(py2)s = %(py0)s.focus_entities
} == %(py6)s
{%(py6)s = %(py4)s.focus_entities
})zL%(py2)s
{%(py2)s = %(py0)s.version
} == %(py6)s
{%(py6)s = %(py4)s.version
})r    r   r   r)   r(   _redis	set_state
@pytest_ar_call_reprcompare@py_builtinslocals_should_repr_global_name	_safereprAssertionError_format_explanation	get_stater   r   r   r   r   )selfr"   clientr<   r>   mock_rrD   @py_assert2@py_assert1@py_format4@py_format6rM   @py_assert5@py_assert3@py_format7@py_format9r;   s                   @r   *test_set_then_get_returns_equivalent_statez?TestRedisL1ReadWrite.test_set_then_get_returns_equivalent_stateU   s2     N+)<= 	
	
  Z884
!++E22
!!zT!!!!zT!!!!!!z!!!z!!!T!!!!!!! **>::	 $$y$$$$y$$$$$$y$$$y$$$$$$$$$$  1EMM1 M1111 M111111y111y111 111111E111E111M1111111##7u'7'77#'77777#'7777777y777y777#777777u777u777'77777777++Gu/G/GG+/GGGGG+/GGGGGGGyGGGyGGG+GGGGGGuGGGuGGG/GGGGGGGG''?5+?+??'+?????'+???????y???y???'??????5???5???+????????  1EMM1 M1111 M111111y111y111 111111E111E111M1111111 3 ;s&   A+\<.\6/B=\<,\9-X
\<9\<c                   K   t        d      }t        d      }||_        |j                  d       d{   }d}||u }|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      d	z  }d
d|iz  }t        t	        j                  |            dx}}y7 w)z:get_state on a key not in Redis returns None (cold start).r2   r3   N)r"   znonexistent-taskrA   rC   resultrE   rH   rI   )r   r.   rU   r_   rW   rX   rY   rZ   r[   r\   r]   r^   )r`   ra   rb   rm   rc   rd   re   rf   s           r   *test_get_state_on_missing_key_returns_nonez?TestRedisL1ReadWrite.test_get_state_on_missing_key_returns_noney   s      )<=!-''(:;;v~vvv <s   4C#C!B+C#c                   
K   t        d      }t        d      }i 

fd}t               }t        |      |_        ||_        |j                  |       d{    
d   }d}||k(  }|slt        j                  d	|fd
||f      t        j                  |      t        j                  |      dz  }dd|iz  }	t        t        j                  |	            dx}x}}y7 w)z<set_state uses the exact key format genesis:state:task:{id}.zmy-special-taskr2   r3   c                    K   | d<   yw)NkTr8   )r6   r9   r:   captured_keys      r   	spy_setexzNTestRedisL1ReadWrite.test_key_format_matches_genesis_prefix.<locals>.spy_setex   s      #Ls   
r?   Nrq   z"genesis:state:task:my-special-taskrN   z%(py1)s == %(py4)spy1rQ   assert %(py6)srR   )r    r   r   r)   rU   rV   rW   rX   r\   r]   r^   )r`   r"   ra   rs   rb   @py_assert0rh   rc   @py_format5ri   rr   s             @r   &test_key_format_matches_genesis_prefixz;TestRedisL1ReadWrite.test_key_format_matches_genesis_prefix   s      -.)<=	  Y7u%%%C H$HH $HHHHH $HHHH HHH$HHHHHHHH 	&s   AC CBC N)	__name__
__module____qualname__pytestmarkasynciork   rn   rz   r8   r!   r   r0   r0   S   s]    [[!2 !2F [[  [[I Ir!   r0   c                   D    e Zd Zej                  j
                  d        Zy)TestScatterGatherAllSucceedc           	      l  K   t        dt        d      5  t        dt        d      5  t        dt        d      5  t        dd	gd
d       d{   }ddd       ddd       ddd       j                  }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||k\  }|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}y7 ;# 1 sw Y   ;xY w# 1 sw Y   @xY w# 1 sw Y   ExY ww)zGWhen all 3 layers return data, MemoryContext has all 3 fields non-None.*core.memory.scatter_gather._fetch_redis_l1zWorking: task A, Focus: redisnew_callabler$   'core.memory.scatter_gather._fetch_kg_l2u+   KG Topology:
entity_1: tool — Redis cache+core.memory.scatter_gather._fetch_qdrant_l3z;Learned Constraints:
Scar 1: avoid retry loops (score=0.91)ztask-allr   ztest intent   
timeout_msNrJ   )z9%(py2)s
{%(py2)s = %(py0)s.working_state
} is not %(py5)sctxrF   rP   rI   assert %(py7)spy7z7%(py2)s
{%(py2)s = %(py0)s.kg_topology
} is not %(py5)sz?%(py2)s
{%(py2)s = %(py0)s.learned_constraints
} is not %(py5)sr   >=z2%(py2)s
{%(py2)s = %(py0)s.latency_ms
} >= %(py5)sr   r   r   working_staterW   rX   rY   rZ   r[   r\   r]   r^   kg_topologylearned_constraints
latency_ms)r`   r   rd   @py_assert4rh   rf   @py_format8s          r   3test_all_three_fetches_succeed_populates_all_fieldszOTestScatterGatherAllSucceed.test_all_three_fetches_succeed_populates_all_fields   sr     >Y  fE  F	d;Y  fT  U	d ?i  ge  f	d
 .j7)]_bccC	d 	d 	d   ,, ,,,, ,,,,,,s,,,s,,, ,,,,,,,,,,*d*d****d******s***s******d*******&&2d2&d2222&d222222s222s222&222d2222222~~""~""""~""""""s"""s"""~"""""""""" d	d 	d 	d 	d 	d 	ds]   N4N'NNN

NNN'$L&N4
NNNN$	N''N1,N4N)r{   r|   r}   r~   r   r   r   r8   r!   r   r   r      s    [[# #r!   r   c                   D    e Zd Zej                  j
                  d        Zy)TestScatterGatherRedisTimeoutc           	      h  K   d }t        d|      5  t        dt        d      5  t        dt        d      5  t        d	d
gdd       d{   }ddd       ddd       ddd       j                  }d}||u }|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}|j                  }d}||k\  }|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      t	        j                  |      dz  }dd|iz  }t        t	        j                  |            dx}x}}y7 ;# 1 sw Y   ;xY w# 1 sw Y   @xY w# 1 sw Y   ExY ww)zRWhen the L1 Redis fetch times out, working_state is None, others may be populated.c                 J   K   t        j                  d       d {    y 7 wN
   r   sleep)_task_ids    r   
slow_redisz^TestScatterGatherRedisTimeout.test_redis_timeout_yields_none_working_state.<locals>.slow_redis        --###   #!#r   r?   r   zKG Topology:
some entityr   r   zLearned Constraints:
scar 1ztask-redis-slowentityintent   r   NrA   z5%(py2)s
{%(py2)s = %(py0)s.working_state
} is %(py5)sr   r   r   r   rJ   r   r   r   r   r   r   )r`   r   r   rd   r   rh   rf   r   s           r   ,test_redis_timeout_yields_none_working_statezJTestScatterGatherRedisTimeout.test_redis_timeout_yields_none_working_state   sn    	$ >JW	f;Y  fA  B	f ?i  gE  F	f
 ..?(XbdeeC	f 	f 	f   (D( D(((( D((((((s(((s((( (((D(((((((*d*d****d******s***s******d*******&&2d2&d2222&d222222s222s222&222d2222222~~""~""""~""""""s"""s"""~"""""""""" f	f 	f 	f 	f 	f 	fs]   N2N%NNN
NNN%"L&N2NNNN"	N%%N/*N2N)r{   r|   r}   r~   r   r   r   r8   r!   r   r   r      s    [[# #r!   r   c                   D    e Zd Zej                  j
                  d        Zy)TestScatterGatherAllTimeoutc           	      	  K   d }t        d|      5  t        d|      5  t        d|      5  t        ddgdd	
       d{   }ddd       ddd       ddd       j                  }d}||u }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j                  }d}||u }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j                  }d}||u }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|j                  }t        |t              }	|	sddt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dt        j                         v st        j                  t              rt        j                  t              ndt        j                  |	      dz  }
t        t        j                  |
            dx}}	|j                  }d}||k\  }|st        j                  d|fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}y7 }# 1 sw Y   }xY w# 1 sw Y   xY w# 1 sw Y   xY ww)zRWhen all 3 layers time out, all fields are None but latency_ms is still populated.c                 J   K   t        j                  d       d {    y 7 wr   r   )_args    r   slowzaTestScatterGatherAllTimeout.test_all_three_timeout_all_fields_none_latency_recorded.<locals>.slow   r   r   r   r?   r   r   ztask-all-slowxyr   r   NrA   r   r   r   r   r   )z3%(py2)s
{%(py2)s = %(py0)s.kg_topology
} is %(py5)s)z;%(py2)s
{%(py2)s = %(py0)s.learned_constraints
} is %(py5)szUassert %(py6)s
{%(py6)s = %(py0)s(%(py3)s
{%(py3)s = %(py1)s.latency_ms
}, %(py4)s)
}
isinstancefloat)rF   rv   rG   rQ   rR   r   r   r   )r   r   r   rW   rX   rY   rZ   r[   r\   r]   r^   r   r   r   r   r   )r`   r   r   rd   r   rh   rf   r   rc   rg   ri   s              r   7test_all_three_timeout_all_fields_none_latency_recordedzSTestScatterGatherAllTimeout.test_all_three_timeout_all_fields_none_latency_recorded   s    	$ >DQ	Z;DQ	Z ?TR	Z
 .oucVXYYC	Z 	Z 	Z   (D( D(((( D((((((s(((s((( (((D(((((((&$&$&&&&$&&&&&&s&&&s&&&&&&$&&&&&&&&&.$.&$....&$......s...s...&...$.........0z.%00000000z000z000000#000#000.000000%000%0000000000~~""~""""~""""""s"""s"""~"""""""""" Z	Z 	Z 	Z 	Z 	Z 	Zs]   S*SSSS 
SSSQ(S* SSSS	SS'"S*N)r{   r|   r}   r~   r   r   r   r8   r!   r   r   r      s    [[# #r!   r   c                       e Zd Zd Zy)TestEnvelopeBuilderFallbacksc                 l   t        dddd      }t        |      }t        |v }|st        j                  d|fdt        |f      dt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  |      rt        j                  |      nddz  }d	d
|iz  }t        t        j                  |            d}t        |v }|st        j                  d|fdt        |f      dt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  |      rt        j                  |      nddz  }d	d
|iz  }t        t        j                  |            d}t        |v }|st        j                  d|fdt        |f      dt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  |      rt        j                  |      nddz  }d	d
|iz  }t        t        j                  |            d}y)zHbuild_envelope with all None fields uses canonical FALLBACK_* constants.Ng(@r   r   r   r   in)z%(py0)s in %(py2)sr
   xml_str)rF   rP   zassert %(py4)srQ   r   r   )r   r	   r
   rW   rX   rY   rZ   r[   r\   r]   r^   r   r   )r`   r   r   rd   @py_format3ry   s         r   7test_all_none_fields_produce_canonical_fallback_stringszTTestEnvelopeBuilderFallbacks.test_all_none_fields_produce_canonical_fallback_strings   sb    $	
 !%7****7***************7***7*******g%%%%{g%%%%%%{%%%{%%%%%%g%%%g%%%%%%%#w....#w......#...#......w...w.......r!   N)r{   r|   r}   r   r8   r!   r   r   r      s    /r!   r   c                       e Zd Zd Zd Zy)TestEnvelopeBuilderValidXMLc                    t        dddd      }t        |      }t        j                  |      }|j                  }d}||k(  }|st        j                  d|fd||f      d	t        j                         v st        j                  |      rt        j                  |      nd	t        j                  |      t        j                  |      d
z  }dd|iz  }t        t        j                  |            dx}x}}y)z<build_envelope always produces XML parseable by ElementTree.z
some statezsome topologyz
some scarsg@r   ZERO_AMNESIA_STATErN   )z+%(py2)s
{%(py2)s = %(py0)s.tag
} == %(py5)srootr   r   r   N)r   r	   ET
fromstringtagrW   rX   rY   rZ   r[   r\   r]   r^   )	r`   r   r   r   rd   r   rh   rf   r   s	            r   test_output_parses_as_valid_xmlz;TestEnvelopeBuilderValidXML.test_output_parses_as_valid_xml   s    &' ,	
 !%}}W%xx///x/////x///////t///t///x///////////r!   c                    t        dddd      }t        |      }t        j                  |      }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      dz  }dd	|iz  }t        t	        j                  |            dx}}y)
z<Even with all None fields, the envelope parses as valid XML.Ng        r   rJ   rL   r   rE   rH   rI   r   r	   r   r   rW   rX   rY   rZ   r[   r\   r]   r^   )r`   r   r   r   rc   rd   re   rf   s           r   ,test_all_none_fields_also_produces_valid_xmlzHTestEnvelopeBuilderValidXML.test_all_none_fields_also_produces_valid_xml  s     $	
 !%}}W%t4t4tt4r!   N)r{   r|   r}   r   r   r8   r!   r   r   r      s    0
 r!   r   c                       e Zd Zd Zd Zy)TestEnvelopeBuilderXMLEscapingc                 `   t        dddd      }t        |      }d}||v }|st        j                  d|fd||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndd	z  }t        j                  d
      dz   d|iz  }t        t        j                  |            dx}}t        j                  |      }|j                  d      }d}||u}	|	st        j                  d|	fd||f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |      dz  }dd|iz  }t        t        j                  |            dx}	}|j                  }	d}
|	|
u}|st        j                  d|fd|	|
f      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |	      t        j                  |
      dz  }dd|iz  }t        t        j                  |            dx}	x}}
d}|j                  }
||
v }|st        j                  d|fd||
f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      ndt        j                  |
      dz  }dd|iz  }t        t        j                  |            dx}x}}
y)a  Content containing < is escaped to &lt; in the raw XML string.

        ElementTree round-trip:
          - The raw XML bytes must contain &lt; (escaped form).
          - After ET.fromstring() parsing, working_el.text contains the decoded
            literal '<' (ElementTree always decodes entities on parse).
          - The XML string would be un-parseable if < were left unescaped.
        zCondition: a < bN      ?r   z&lt;r   z%(py1)s in %(py3)sr   rv   rG   z-Raw XML must contain &lt; for the < characterz
>assert %(py5)srI   WORKING_CONTEXTrJ   rL   
working_elrE   rH   )z0%(py2)s
{%(py2)s = %(py0)s.text
} is not %(py5)sr   r   r   <)z,%(py1)s in %(py5)s
{%(py5)s = %(py3)s.text
})rv   rG   rI   )r   r	   rW   rX   r\   rY   rZ   r[   _format_assertmsgr]   r^   r   r   findtext)r`   r   r   rx   rc   re   rf   r   r   rd   r   rh   r   s                r   'test_lt_character_is_escaped_in_contentzFTestEnvelopeBuilderXMLEscaping.test_lt_character_is_escaped_in_content  s    , $	
 !%Qv QQQvQQQvQQQQQQQQQQQQQ"QQQQQQQ}}W%YY01
!%%z%%%%z%%%%%%z%%%z%%%%%%%%%%*d*d****d******z***z******d*******%joo%so%%%%so%%%s%%%%%%j%%%j%%%o%%%%%%%r!   c                    t        dddd      }t        |      }t        j                  |      }d}||u}|st	        j
                  d|fd||f      dt        j                         v st	        j                  |      rt	        j                  |      ndt	        j                  |      dz  }d	d
|iz  }t        t	        j                  |            dx}}d}||v }|st	        j
                  d|fd||f      t	        j                  |      dt        j                         v st	        j                  |      rt	        j                  |      nddz  }d	d
|iz  }t        t	        j                  |            dx}}y)z?Content containing & is escaped to &amp; to preserve valid XML.z	foo & barNr   r   rJ   rL   r   rE   rH   rI   z&amp;r   r   r   r   r   )	r`   r   r   r   rc   rd   re   rf   rx   s	            r   test_ampersand_is_escapedz8TestEnvelopeBuilderXMLEscaping.test_ampersand_is_escaped9  s    % $	
 !%}}W%t4t4tt4!w'!!!!w'!!!w!!!!!!'!!!'!!!!!!!r!   N)r{   r|   r}   r   r   r8   r!   r   r   r     s    &4"r!   r   c                   |    e Zd Zej                  j
                  d        Zej                  j
                  d        Zy)'TestInterceptorJITHydrationFullPipelinec                 P  K   t        dt        d      5  t        dt        d      5  t        dt        d      5  ddd}t        |       d{   }ddd       ddd       ddd       d	}|v }|st        j                  d
|fd||f      t        j
                  |      dt        j                         v st        j                  |      rt        j
                  |      nddz  }dd|iz  }t        t        j                  |            dx}}|d	   }t        |      }d}	||	kD  }
|
st        j                  d|
fd||	f      dt        j                         v st        j                  t              rt        j
                  t              ndt        j
                  |      t        j
                  |      t        j
                  |	      dz  }dd|iz  }t        t        j                  |            dx}x}x}
}	y7 # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY ww)zCinterceptor_jit_hydration adds system_injection key to the payload.r   Nr   r   r   z	task-fullzBuild the redis schemar   promptsystem_injectionr   r   rm   r   rH   rI   r   >)z/%(py4)s
{%(py4)s = %(py0)s(%(py2)s)
} > %(py7)slen)rF   rP   rQ   r   zassert %(py9)spy9)r   r   r   rW   rX   r\   rY   rZ   r[   r]   r^   r   )r`   payloadrm   rx   rc   re   rf   rd   rh   @py_assert6rg   r   @py_format10s                r   'test_payload_gains_system_injection_keyzOTestInterceptorJITHydrationFullPipeline.test_payload_gains_system_injection_keyM  sy     >Yeij	>;Yeij	> ?ifjk	>
 #.9QRG4W==F	> 	> 	> "+!V++++!V+++!++++++V+++V+++++++,-2s-.22.2222.222222s222s222-222.2222222222 >	> 	> 	> 	> 	> 	>s]   H&HHG?G<
G?HH$FH&<G??H	HH	HH#H&c                 4  K   t        dt        d      5  t        dt        d      5  t        dt        d      5  dddd	}t        |       d{   }ddd       ddd       ddd       d
   }d}||k(  }|slt        j                  d|fd||f      t        j
                  |      t        j
                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|d   }d}||k(  }|slt        j                  d|fd||f      t        j
                  |      t        j
                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}|d   }d}||k(  }|slt        j                  d|fd||f      t        j
                  |      t        j
                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}y7 # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY ww)zKinterceptor_jit_hydration preserves all original keys in the returned dict.r   Nr   r   r   ztask-preservezDo something usefulmy_value)r   r   
custom_keyr   rN   rt   ru   rw   rR   r   r   )r   r   r   rW   rX   r\   r]   r^   )r`   r   rm   rx   rh   rc   ry   ri   s           r   $test_original_payload_keys_preservedzLTestInterceptorJITHydrationFullPipeline.test_original_payload_keys_preserved[  s     >Yeij
	>;Yeij
	> ?ifjk
	> +/(G
 5W==F
	> 
	> 
	> i 3O3 O3333 O333 333O3333333h8#88#88888#8888888#88888888l#1z1#z1111#z111#111z1111111	 >
	> 
	> 
	> 
	> 
	> 
	>s]   HHG>G1G.
G1G>H%F	H.G11G;6G>>H	HHHN)r{   r|   r}   r~   r   r   r   r   r8   r!   r   r   r   K  s<    [[3 3 [[2 2r!   r   c                   D    e Zd Zej                  j
                  d        Zy)%TestJITHydrationInterceptorPreExecutec                 .  K   t               }t        dt              5 }dddd|_        ddd}|j	                  |       d{   }ddd       d	}|v }|st        j                  d
|fd||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      nddz  }dd|iz  }t        t        j                  |            dx}}j                         y7 # 1 sw Y   xY ww)zNJITHydrationInterceptor.pre_execute returns payload with system_injection set.?core.memory.jit_hydration_interceptor.interceptor_jit_hydrationr   zt-99testzN<ZERO_AMNESIA_STATE><WORKING_CONTEXT>ok</WORKING_CONTEXT></ZERO_AMNESIA_STATE>)r   r   r   r   Nr   r   r   rm   r   rH   rI   )r   r   r   r$   pre_executerW   rX   r\   rY   rZ   r[   r]   r^   assert_awaited_once_with	r`   interceptormock_hydrater   rm   rx   rc   re   rf   s	            r   *test_pre_execute_attaches_system_injectionzPTestJITHydrationInterceptorPreExecute.test_pre_execute_attaches_system_injectionu  s      ./ Sbkl		<p| " $t)L%
 #)F;G&227;;F		< "+!V++++!V+++!++++++V+++V+++++++--g6 <		< 		<s/   D%D	DD	B?DD		DDN)r{   r|   r}   r~   r   r   r   r8   r!   r   r   r   s  s    [[7 7r!   r   c                   |    e Zd Zej                  j
                  d        Zej                  j
                  d        Zy)(TestJITHydrationInterceptorErrorHandlingc                   K   t               }t        dt        t        d            5  ddd}|j	                  |       d{   }ddd       d}|v }|st        j                  d	|fd
||f      t        j                  |      dt        j                         v st        j                  |      rt        j                  |      nddz  }dd|iz  }t        t        j                  |            dx}}|d   }|t        k(  }|st        j                  d|fd|t        f      t        j                  |      dt        j                         v st        j                  t              rt        j                  t              nddz  }dd|iz  }t        t        j                  |            dx}}|d   }d}||k(  }|slt        j                  d|fd||f      t        j                  |      t        j                  |      dz  }	dd|	iz  }
t        t        j                  |
            dx}x}}y7 # 1 sw Y   xY ww)zMWhen interceptor_jit_hydration raises, an error envelope is injected instead.r   zRedis is down)r   r@   zt-errz
risky taskr   Nr   r   r   rm   r   rH   rI   rN   )z%(py1)s == %(py3)sr   r   rt   ru   rw   rR   )r   r   r   RuntimeErrorr   rW   rX   r\   rY   rZ   r[   r]   r^   r   )r`   r   r   rm   rx   rc   re   rf   rh   ry   ri   s              r   /test_hydration_exception_injects_error_envelopezXTestJITHydrationInterceptorErrorHandling.test_hydration_exception_injects_error_envelope  sq     ./M"$_5
 	<
 #*\BG&227;;F	< "+!V++++!V+++!++++++V+++V+++++++()<)_<<<<)_<<<)<<<<<<_<<<_<<<<<<<i +G+ G++++ G+++ +++G+++++++ <	< 	<s/   &H>H1H.H1G'H>.H11H;6H>c                   K   t        t        t              }|sddt        j                         v st        j                  t               rt        j                  t               nddt        j                         v st        j                  t              rt        j                  t              nddt        j                         v st        j                  t              rt        j                  t              ndt        j                  |      dz  }t        t        j                  |            d}t        t              }d}||kD  }|st        j                  d|fd	||f      d
t        j                         v st        j                  t              rt        j                  t              nd
dt        j                         v st        j                  t              rt        j                  t              ndt        j                  |      t        j                  |      dz  }dd|iz  }t        t        j                  |            dx}x}}d}|t        v }|st        j                  d|fd|t        f      t        j                  |      dt        j                         v st        j                  t              rt        j                  t              nddz  }	dd|	iz  }
t        t        j                  |
            dx}}yw)zBThe _ERROR_ENVELOPE constant is a non-empty string (sanity check).z5assert %(py4)s
{%(py4)s = %(py0)s(%(py1)s, %(py2)s)
}r   r   str)rF   rv   rP   rQ   Nr   r   )z/%(py3)s
{%(py3)s = %(py0)s(%(py1)s)
} > %(py6)sr   )rF   rv   rG   rR   rS   rT   r   r   r   r   rH   rI   )r   r   r  rY   rZ   rW   r[   r\   r]   r^   r   rX   )r`   rh   ry   rc   rg   r   ri   rj   rx   re   rf   s              r   )test_error_envelope_is_a_non_empty_stringzRTestJITHydrationInterceptorErrorHandling.test_error_envelope_is_a_non_empty_string  s|     /3////////z///z/////////////////3///3//////////?#'a'#a''''#a''''''s'''s''''''?'''?'''#'''a'''''''#6#6666#666#6666666666666666s   K?LN)r{   r|   r}   r~   r   r   r   r  r8   r!   r   r   r     s<    [[, ," [[7 7r!   r   c                   D    e Zd Zej                  j
                  d        Zy)&TestJITHydrationInterceptorPostExecutec                    K   t               }ddd}ddi}t        d      5 }t        t        d            |_        |j                  ||       d	{    d	d	d	       y	7 # 1 sw Y   y	xY ww)
zQpost_execute swallows I/O errors and never raises (observability must not block).zt-post<ZERO_AMNESIA_STATE/>)r   r   status	completedz0core.memory.jit_hydration_interceptor.EVENTS_DIRzPermission deniedr?   N)r   r   r   OSErrormkdirpost_execute)r`   r   r   result_dictmock_dirs        r   .test_post_execute_does_not_raise_on_io_failurezUTestJITHydrationInterceptorPostExecute.test_post_execute_does_not_raise_on_io_failure  s      ./ 7
  - EF 	A(&7;N3OPHN**;@@@	A 	A A	A 	As.   A-0A!AA!	A-A!!A*&A-N)r{   r|   r}   r~   r   r   r  r8   r!   r   r  r    s     [[A Ar!   r  c                   |    e Zd Zej                  j
                  d        Zej                  j
                  d        Zy)'TestJITHydrationInterceptorOnCorrectionc                   K   t               }t        dt              5 }ddd|_        ddd}|j	                  |       d	{   }d	d	d	       d
   }d}||k(  }|slt        j                  d|fd||f      t        j                  |      t        j                  |      dz  }dd|iz  }	t        t        j                  |	            d	x}x}}j                          y	7 # 1 sw Y   xY ww)zDon_correction prepends 'CORRECTION: ' to the prompt and re-hydrates.r   r   zCORRECTION: retry thisr  )r   r   z
retry thiszt-corr)r   r   Nr   rN   rt   ru   rw   rR   )r   r   r   r$   on_correctionrW   rX   r\   r]   r^   assert_awaited_once)
r`   r   r   r   rm   rx   rh   rc   ry   ri   s
             r   -test_on_correction_prepends_correction_prefixzUTestJITHydrationInterceptorOnCorrection.test_on_correction_prepends_correction_prefix  s      ./M"
 		> 2$;)L% ".(CG&44W==F		> x <$<< $<<<<< $<<<< <<<$<<<<<<<<((*	 >		> 		>s/   C.$C"C C"BC. C""C+'C.c                   K   t               }t        dt        ddi      5 }ddi}|j                  |       d{   }ddd       d}|v}|st	        j
                  d	|fd
||f      t	        j                  |      dt        j                         v st	        j                  |      rt	        j                  |      nddz  }dd|iz  }t        t	        j                  |            dx}}j                          y7 # 1 sw Y   xY ww)zAon_correction with no prompt key still calls re-hydration safely.r   r   r  r   r   zt-no-promptNr   )not in)z%(py1)s not in %(py3)sr   r   rH   rI   )r   r   r   r  rW   rX   r\   rY   rZ   r[   r]   r^   r  r   s	            r   4test_on_correction_without_prompt_key_does_not_crashz\TestJITHydrationInterceptorOnCorrection.test_on_correction_without_prompt_key_does_not_crash  s      ./M",.EF
 	>  -0G&44W==F	> &xw&&&&xw&&&x&&&&&&w&&&w&&&&&&&((* >	> 	>s,   DC?C=C?B>D=C??DDN)r{   r|   r}   r~   r   r   r  r  r8   r!   r   r  r    s<    [[+ +& [[+ +r!   r  )ztask-001)N)5__doc__builtinsrY   _pytest.assertion.rewrite	assertionrewriterW   r   r&   sysxml.etree.ElementTreeetreeElementTreer   unittest.mockr   r   r   r~   pytest_asynciopathinsertcore.memory.redis_l1_schemar   r   !core.memory.zero_amnesia_enveloper   r	   r
   r   r   core.memory.scatter_gatherr   core.memory.jit_hydrationr   %core.memory.jit_hydration_interceptorr   r   r  r    r.   r0   r   r   r   r   r   r   r   r   r   r  r  r8   r!   r   <module>r*     s   (    
 " " 5 5   * + C A  A < ? Z
 
l 
L I 6BI BIR# #,# #8# #4/ /*   @'" '"\!2 !2P7 747 7@A A.$+ $+r!   