66"""
77from __future__ import annotations
88
9+ from contextlib import ExitStack , contextmanager
910from datetime import datetime
1011import hashlib
1112import json
@@ -32,73 +33,47 @@ def _last_event(values):
3233 return max (dated , default = (None , None ), key = lambda pair : pair [0 ])[1 ]
3334
3435
35- def read_conversation_requests (root , registry , store , session , * , goal_ids , core_goal_ids ,
36- validate_source_session , history = False , offset = 0 , limit = 12 , search = "" ):
37- """Read only this host's exact source Session, with fresh caller read scope.
36+ @contextmanager
37+ def _locked_request_batch (root , scope , requests ):
38+ """Retain each request version for one page-sized typed observation."""
39+ available , lock_keys = set (), set ()
40+ with ExitStack () as locks :
41+ for path , _ , request_id in sorted (requests , key = lambda item : (item [2 ], str (item [0 ]))):
42+ # Exact requests share their guard across legacy entry locations.
43+ # Legacy records still use their individual entry lock.
44+ key = (request_id , None if scope .exact else path )
45+ if key not in lock_keys :
46+ try :
47+ locks .enter_context (_request_lock (root , request_id , scope , path .with_suffix (".lock" )))
48+ except (OSError , ValueError , KeyError , TypeError ):
49+ continue
50+ lock_keys .add (key )
51+ available .add (path )
52+ yield available
3853
39- The caller supplies provider-validated Goal visibility and rechecks it after
40- this read. A model/caller-supplied channel, path or source id is never used.
41- """
42- if type (offset ) is not int or offset < 0 or type (limit ) is not int or not 1 <= limit <= 12 :
43- raise ValueError ("invalid request page" )
44- if not isinstance (search , str ) or len (search ) > 200 :
45- raise ValueError ("request search must be at most 200 characters" )
46- query = search .strip ().casefold ()
47- paths = sorted ((_root (root ) / "entries" ).glob ("*/*.json" ))
48- rows , unreadable , cache , turn_readers , diagnostics = [], 0 , {}, {}, []
49- for path in paths [:2000 ]:
54+
55+ def _read_receipt_batch (root , rows ):
56+ if not rows :
57+ return []
58+ try :
59+ observed = read_inbox_transaction (root , {"operation" : "receipt_states" , "rows" : rows , "include_agenda" : True })
60+ states = list (zip (observed ["items" ], observed ["agenda_items" ], strict = True ))
61+ if len (states ) != len (rows ):
62+ raise ValueError ("Inbox receipt count does not match requests" )
63+ return states
64+ except (OSError , ValueError , KeyError , TypeError ):
65+ # A failed batch is only a read. Retry its rows independently while
66+ # all their guards remain held; one unavailable record must not hide
67+ # its readable neighbors or become an empty successful observation.
68+ return [None ] if len (rows ) == 1 else [_read_receipt_batch (root , [row ])[0 ] for row in rows ]
69+
70+
71+ def _project_request_observations (root , registry , observations , * , core_goal_ids , history ):
72+ """Combine captured receipt facts with current linked Core observations."""
73+ rows , unreadable , cache = [], 0 , {}
74+ for row , source_session_id , turn , state , agenda , controlled , read , read_error , decision , decision_error , replies in observations :
5075 try :
51- candidate = _read (path )
52- if candidate .get ("source_kind" ) == "peer" :
53- continue
54- if candidate .get ("source_channel" ) not in {None , session ["channel_id" ]}:
55- continue
56- if not isinstance (candidate .get ("request_id" ), str ) or not BARE_SHA256_PATTERN .fullmatch (candidate ["request_id" ]):
57- raise ValueError ("invalid request identity" )
58- route = _read (_root (root ) / "roundtrips" / (candidate ["request_id" ] + ".json" ))
59- if route .get ("channel_id" ) != session ["channel_id" ]:
60- continue
61- if not is_source_chat_host (root , route , store ):
62- raise ValueError ("original source host changed" )
63- source_session = store .load_session (route ["session_id" ])
64- if not source_session or source_session .get ("channel_id" ) != session ["channel_id" ]:
65- raise ValueError ("original source Session unavailable" )
66- validate_source_session (source_session )
67- gid , aid = route ["goal_id" ], route ["agent_id" ]
68- if goal_ids is not None and gid not in goal_ids :
69- continue
70- sid = source_session ["session_id" ]
71- if sid not in turn_readers :
72- turn_readers [sid ] = original_turn_reader (store , sid )
73- turn = turn_readers [sid ](route ["client_turn_id" ])
74- if turn is None :
75- raise ValueError ("original source Turn unavailable" )
76- with collaboration_goal_scope (registry , goal_id = gid , agents = (), caller_goal_ref = route .get ("goal_ref" )) as scope :
77- with _request_lock (root , candidate ["request_id" ], scope , path .with_suffix (".lock" )):
78- row = _entry (root , gid , aid , candidate ["request_id" ], scope = scope )
79- if row .get ("source_kind" ) == "peer" :
80- continue
81- grant = source_context_target_authority (root , source_session , turn , {"goal_id" : gid , "agent_id" : aid })
82- try :
83- decide_collaboration_lifecycle (scope , operation = "original_request_inspect" , record = row , route = route ,
84- initial_delivery = original_delivery_facts (row , route , turn , source_id = grant ["source_id" ]))
85- except CollaborationLifecycleRejected as exc :
86- # Only this typed refusal proves the route and source
87- # matched before the conflicting receipt was observed.
88- # Withhold the brief, work and completion state as before.
89- if exc .decision .get ("delivery_proof_reason" ) == "handoff_receipt_conflict" and len (diagnostics ) < 12 :
90- diagnostics .append ({"request_id" : row ["request_id" ], "goal_id" : gid , "agent_id" : aid ,
91- "code" : exc .decision ["code" ], "reason" : exc .decision ["delivery_proof_reason" ]})
92- raise
93- observed = read_inbox_transaction (root , {"operation" : "receipt_states" , "rows" : [row ], "include_agenda" : True })
94- state , agenda = observed ["items" ][0 ], observed ["agenda_items" ][0 ]
95- controlled = state .get ("readback" )
96- read , read_error = _receipt (root , "reads" , row )
97- decision , decision_error = _receipt (root , "decisions" , row )
98- replies = reply_status (root , row )
99- # Request/return observations are version-consistent. Core work is
100- # a separate current observation; never hold its request lock over
101- # another authority's IO.
76+ gid , aid = row ["goal_id" ], row ["agent_id" ]
10277 work = read_linked_work (root , registry , row , cache ,
10378 include_core_details = core_goal_ids is None or gid in core_goal_ids )
10479 warnings = list (state .get ("warnings" , [])) + work ["warnings" ]
@@ -122,11 +97,140 @@ def read_conversation_requests(root, registry, store, session, *, goal_ids, core
12297 "unavailable" if read_error or control_unavailable else "supplied" if read else "pending" ,
12398 "decision" : assessment ["status" ], "decision_reason" : assessment .get ("reason" ),
12499 "returns" : replies , "linked_todos" : work ["linked_todos" ], "evidence_refs" : work ["evidence_refs" ],
125- "warnings" : warnings , "source_session_id" : source_session [ "session_id" ] , "source_turn_id" : turn ["turn_id" ],
100+ "warnings" : warnings , "source_session_id" : source_session_id , "source_turn_id" : turn ["turn_id" ],
126101 "last_event_at" : _last_event ([row .get ("delivered_at" ), read_at , assessment .get ("at" ),
127102 * (reply .get (key ) for reply in replies for key in ("created_at" , "delivered_at" ))])})
128103 except (OSError , ValueError , KeyError , TypeError ):
129104 unreadable += 1
105+ return rows , unreadable
106+
107+
108+ def _request_groups (root , store , session , goal_ids , validate_source_session ):
109+ """Discover source-validated routes before acquiring any Goal guard."""
110+ paths = sorted ((_root (root ) / "entries" ).glob ("*/*.json" ))
111+ unreadable , groups = 0 , {}
112+ for path in paths [:2000 ]:
113+ try :
114+ candidate = _read (path )
115+ if candidate .get ("source_kind" ) == "peer" :
116+ continue
117+ if candidate .get ("source_channel" ) not in {None , session ["channel_id" ]}:
118+ continue
119+ if not isinstance (candidate .get ("request_id" ), str ) or not BARE_SHA256_PATTERN .fullmatch (candidate ["request_id" ]):
120+ raise ValueError ("invalid request identity" )
121+ route = _read (_root (root ) / "roundtrips" / (candidate ["request_id" ] + ".json" ))
122+ if route .get ("channel_id" ) != session ["channel_id" ]:
123+ continue
124+ if not is_source_chat_host (root , route , store ):
125+ raise ValueError ("original source host changed" )
126+ source_session = store .load_session (route ["session_id" ])
127+ if not source_session or source_session .get ("channel_id" ) != session ["channel_id" ]:
128+ raise ValueError ("original source Session unavailable" )
129+ validate_source_session (source_session )
130+ gid , aid = route ["goal_id" ], route ["agent_id" ]
131+ if goal_ids is not None and gid not in goal_ids :
132+ continue
133+ if not isinstance (gid , str ) or not isinstance (aid , str ):
134+ raise ValueError ("invalid request target" )
135+ key = (gid , json .dumps (route .get ("goal_ref" ), sort_keys = True ))
136+ groups .setdefault (key , []).append ((path , route , candidate ["request_id" ]))
137+ except (OSError , ValueError , KeyError , TypeError ):
138+ unreadable += 1
139+ return groups , unreadable , len (paths ) <= 2000
140+
141+
142+ def read_conversation_requests (root , registry , store , session , * , goal_ids , core_goal_ids ,
143+ validate_source_session , history = False , offset = 0 , limit = 12 , search = "" ):
144+ """Read only this host's exact source Session, with fresh caller read scope.
145+
146+ The caller supplies provider-validated Goal visibility and rechecks it after
147+ this read. A model/caller-supplied channel, path or source id is never used.
148+ """
149+ if type (offset ) is not int or offset < 0 or type (limit ) is not int or not 1 <= limit <= 12 :
150+ raise ValueError ("invalid request page" )
151+ if not isinstance (search , str ) or len (search ) > 200 :
152+ raise ValueError ("request search must be at most 200 characters" )
153+ query = search .strip ().casefold ()
154+ groups , unreadable , scan_complete = _request_groups (root , store , session , goal_ids , validate_source_session )
155+ turn_readers , diagnostics , work_reads = {}, [], []
156+ # Reuse only the held lifetime guard, never an authorization or request
157+ # snapshot. Resolve sources outside it first: their provider checks can
158+ # read another authority. Each source/Turn and request is reread below.
159+ # Keep each guard bounded to a page-sized batch so a long inventory does
160+ # not exclude Goal writers for the entire history scan.
161+ batches = [(key , items [start :start + limit ]) for key , items in groups .items ()
162+ for start in range (0 , len (items ), limit )]
163+ for (gid , _ ), requests in batches :
164+ start , failed = len (work_reads ), 0
165+ try :
166+ with (
167+ collaboration_goal_scope (registry , goal_id = gid , agents = (),
168+ caller_goal_ref = requests [0 ][1 ].get ("goal_ref" )) as scope ,
169+ _locked_request_batch (root , scope , requests ) as available ,
170+ ):
171+ prepared = []
172+ for path , route , request_id in requests :
173+ if path not in available :
174+ failed += 1
175+ continue
176+ try :
177+ source_session = store .load_session (route ["session_id" ])
178+ if not source_session or source_session .get ("channel_id" ) != session ["channel_id" ]:
179+ raise ValueError ("original source Session unavailable" )
180+ validate_source_session (source_session )
181+ sid = source_session ["session_id" ]
182+ if sid not in turn_readers :
183+ turn_readers [sid ] = original_turn_reader (store , sid )
184+ turn = turn_readers [sid ](route ["client_turn_id" ])
185+ if turn is None :
186+ raise ValueError ("original source Turn unavailable" )
187+ row = _entry (root , gid , route ["agent_id" ], request_id , scope = scope )
188+ if row .get ("source_kind" ) == "peer" :
189+ continue
190+ grant = source_context_target_authority (root , source_session , turn ,
191+ {"goal_id" : gid , "agent_id" : route ["agent_id" ]})
192+ try :
193+ decide_collaboration_lifecycle (scope , operation = "original_request_inspect" , record = row , route = route ,
194+ initial_delivery = original_delivery_facts (row , route , turn , source_id = grant ["source_id" ]))
195+ except CollaborationLifecycleRejected as exc :
196+ # Only this typed refusal proves the route and source
197+ # matched before the conflicting receipt was observed.
198+ # Withhold the brief, work and completion state as before.
199+ if exc .decision .get ("delivery_proof_reason" ) == "handoff_receipt_conflict" and len (diagnostics ) < 12 :
200+ diagnostics .append ({"request_id" : row ["request_id" ], "goal_id" : gid , "agent_id" : row ["agent_id" ],
201+ "code" : exc .decision ["code" ], "reason" : exc .decision ["delivery_proof_reason" ]})
202+ raise
203+ # Do not retain full model responses while waiting for
204+ # linked-work IO; only the displayed question is used.
205+ source_turn = {"turn_id" : turn ["turn_id" ], "message" : turn .get ("message" , "" )}
206+ prepared .append ((row , source_session ["session_id" ], source_turn ))
207+ except (OSError , ValueError , KeyError , TypeError ):
208+ failed += 1
209+ observations = _read_receipt_batch (root , [row for row , _ , _ in prepared ])
210+ for (row , source_session_id , source_turn ), observed in zip (prepared , observations , strict = True ):
211+ if observed is None :
212+ failed += 1
213+ continue
214+ try :
215+ state , agenda = observed
216+ controlled = state .get ("readback" )
217+ read , read_error = _receipt (root , "reads" , row )
218+ decision , decision_error = _receipt (root , "decisions" , row )
219+ replies = reply_status (root , row )
220+ work_reads .append ((row , source_session_id , source_turn , state , agenda , controlled ,
221+ read , read_error , decision , decision_error , replies ))
222+ except (OSError , ValueError , KeyError , TypeError ):
223+ failed += 1
224+ except (OSError , ValueError , KeyError , TypeError ):
225+ del work_reads [start :]
226+ unreadable += len (requests )
227+ else :
228+ unreadable += failed
229+ # Request/return observations are version-consistent. Core work is a
230+ # separate observation: release all lifetime/request guards before its IO.
231+ rows , projection_failures = _project_request_observations (root , registry , work_reads ,
232+ core_goal_ids = core_goal_ids , history = history )
233+ unreadable += projection_failures
130234 rows = list ({row ["request_id" ]: row for row in rows }.values ())
131235 pending_count = sum (row ["unfinished" ] for row in rows )
132236 visible = [row for row in rows if history or row ["unfinished" ]]
@@ -138,7 +242,7 @@ def read_conversation_requests(root, registry, store, session, *, goal_ids, core
138242 (row .get ("brief" ) or {}).get ("purpose" ), (row .get ("brief" ) or {}).get ("context" )))]
139243 visible .sort (key = lambda row : (row .get ("last_event_at" ) or "" , row ["request_id" ]), reverse = True )
140244 page = visible [offset :offset + limit ]
141- coverage = {"scan_complete" : len ( paths ) <= 2000 , "unreadable" : unreadable , "diagnostics" : diagnostics }
245+ coverage = {"scan_complete" : scan_complete , "unreadable" : unreadable , "diagnostics" : diagnostics }
142246 # A page fence over observations, not an atomic snapshot or a new ledger.
143247 snapshot_digest = hashlib .sha256 (json .dumps ([visible , coverage , query ], sort_keys = True , ensure_ascii = False ).encode ()).hexdigest ()
144248 return {"ok" : True , "session_id" : session ["session_id" ], "rows" : page ,
0 commit comments