trusty_code/session/registry_memory_sink.rs
1//! `SessionRegistry`'s #2345 turn-recorder sink lazy-init/lookup. Split out
2//! of `registry.rs` for the same 500-SLOC-cap reason `registry_events.rs`
3//! was split out (#2344) — a child module of `registry` (declared via
4//! `#[path = ...] mod memory_sink_ext;`), so it shares full access to
5//! `SessionRegistry`'s private `lock` helper and `SessionEntry`'s private
6//! `memory_sink` field exactly as if this method were still defined in
7//! `registry.rs`.
8//!
9//! Why: the turn recorder's sink (and its background drain task) must be
10//! constructed exactly ONCE per session — see the `memory_sink` module's own
11//! docs — not once per `task.run`; this is the single lazy-init/lookup entry
12//! point `task::executor::run_and_record` calls at each run's turn boundary.
13//! It is therefore also the ONE place that knows the session's project root at
14//! sink-construction time, which makes it the only place that can enforce the
15//! #4638 bound: the recorder may bring a NEW palace into being for a durable
16//! project root and never for an ephemeral one.
17//! What: [`SessionRegistry::memory_sink_for`].
18//! Test: `registry_tests::memory_sink_for_reuses_the_same_sink_across_calls`,
19//! `registry_tests::memory_sink_for_unknown_session_returns_none`,
20//! `registry_tests::memory_sink_for_many_sessions_mint_at_most_one_palace`.
21
22use std::path::Path;
23use std::sync::Weak;
24
25use tracing::{debug, warn};
26
27use crate::session::memory_sink::{
28 MemoryDurabilityObserver, MemoryTurnOutcome, PalaceCreation, TurnMemorySink,
29 derive_palace_id_for_project,
30};
31
32use super::*;
33
34impl SessionRegistry {
35 /// Lazily construct (on first call) or return (on every later call) this
36 /// session's durable turn-recorder sink.
37 ///
38 /// Why: `task::executor::run_and_record` needs the SAME
39 /// `Arc<TurnMemorySink>` — and therefore the same background drain task
40 /// and bounded queue — across every `task.run` on one session, not a
41 /// fresh one per run (a fresh sink per run would spawn a new drain task
42 /// each time, multiplying in-flight writers with no bound). Constructing
43 /// it here, inside the session-map lock, means two calls can never build
44 /// two different sinks for the same session even under a hypothetical
45 /// race (in practice `Self::begin_execution`'s single-in-flight-run guard
46 /// already prevents concurrent calls per session).
47 /// What: `None` if `id` is unknown (best-effort — mirrors
48 /// `Self::set_run_outcome`'s framing; the caller has already validated
49 /// the session's existence earlier in the same run via
50 /// `begin_execution`/`begin_pm_transcript`). On the FIRST call for a
51 /// session, derives the palace id from `project_dir` via
52 /// [`derive_palace_id_for_project`], resolves trusty-memory's base URL
53 /// via `trusty_common::memory_rpc::resolve_memory_socket_or_unreachable`
54 /// (fail-open — the sink is built regardless of whether the daemon is
55 /// currently reachable; every write attempt after that is independently
56 /// fail-open, see `memory_sink::write_turn`), and stores the constructed
57 /// `Arc`. On every SUBSEQUENT call, `project_dir` is ignored and the
58 /// already-built sink is returned unchanged — a session's palace/base-url
59 /// binding is fixed for its lifetime, mirroring
60 /// `Self::begin_pm_transcript`'s analogous "the system prompt is fixed
61 /// after the first call" rule.
62 /// `project_dir` is `None` for a PROJECTLESS session, which returns `None`:
63 /// a memory palace is project-scoped by construction, so with no project
64 /// there is nothing to scope one to. This is a deliberate skip, not a
65 /// degradation — the caller must NOT substitute the run's scratch root,
66 /// since deriving a palace id from a throwaway temp path would mint a fresh,
67 /// orphaned palace on every projectless run. The whole sink is already
68 /// fail-open and fire-and-forget, so its absence costs a projectless run
69 /// nothing but the durable turn record it has no home for anyway.
70 ///
71 /// (#4638) This is also where the sink's [`PalaceCreation`] entitlement is
72 /// decided, and that decision is the fix for the leak the paragraph above
73 /// was written to prevent. The projectless branch guarded only the `None`
74 /// case, so a session BOUND to a `tempfile::TempDir` walked straight
75 /// through it: [`derive_palace_id_for_project`] fell to its
76 /// `parent_dir_slug` level and produced a per-RUN-unique id
77 /// (`t-tmp<random>` on macOS, from `$TMPDIR/.tmpXXXXXX`), and
78 /// [`TurnMemorySink`]'s drain task auto-CREATED that palace on the live
79 /// daemon at the first turn. Every such run minted one palace nothing would
80 /// ever read again: 5,667 orphans in three weeks, 97.8% of every palace on
81 /// the machine, which turned trusty-memory's O(n) full-registry handlers
82 /// (#4637) into a ~90-minute `GET /api/v1/status`. A palace is an expensive
83 /// object (usearch index, KG redb, drawer table, recall log), not a cheap
84 /// namespace, and the trusty-code suite alone drives dozens of temp-rooted
85 /// sessions per `cargo test` run.
86 ///
87 /// The BOUND: [`PalaceCreation::Allowed`] only for a DURABLE project root,
88 /// so the recorder can create at most one palace per real project, reused
89 /// by every session on that project forever — the same palace
90 /// `catchup::pm_catchup_context` reads its digest from. N sessions create
91 /// at most one palace, never N. Sessions stay distinguishable INSIDE it via
92 /// `chat_turn_append`'s `session_id` and `memory_remember`'s
93 /// `session:<id>` tag (exactly how #2348's `recall_session` already scopes
94 /// its query), so no session-level recall is lost.
95 ///
96 /// (#5811) A project root whose palace CANNOT BE RESOLVED gets no sink at
97 /// all. [`derive_palace_id_for_project`] used to answer the shared literal
98 /// `"unknown-project"` on any failure, and a durable root carries
99 /// [`PalaceCreation::Allowed`], so two projects with unresolvable identity
100 /// auto-created and then shared one palace holding both of their real
101 /// prompts and responses. Declining the sink is the structural fix: there is
102 /// no palace to name, so there is nothing to write into. The resolve runs
103 /// BEFORE the temp-root check because an unresolvable identity is
104 /// disqualifying whether or not the root is durable.
105 ///
106 /// An ephemeral root still gets a full sink — only the CREATE is withheld.
107 /// That distinction is deliberate: the sink is what registers #2348's
108 /// `recall_session` tool and what `run_and_record` reuses for its
109 /// `socket`/`palace`, so returning `None` here would silently change the
110 /// PM's tool surface for a temp-rooted run. With
111 /// [`PalaceCreation::Forbidden`] the drain task still writes into a palace
112 /// that ALREADY exists and merely declines to bring a new one into being —
113 /// see `memory_sink::drain`.
114 /// Test: `registry_tests::memory_sink_for_reuses_the_same_sink_across_calls`,
115 /// `registry_tests::memory_sink_for_unknown_session_returns_none`,
116 /// `registry_tests::memory_sink_for_projectless_session_returns_none`,
117 /// `registry_tests::memory_sink_for_temp_rooted_session_forbids_palace_create`,
118 /// `registry_tests::memory_sink_for_many_sessions_mint_at_most_one_palace`.
119 ///
120 /// (#2425) The receiver is `&Arc<Self>` rather than `&self` because the
121 /// sink is handed a durability observer holding a `Weak<SessionRegistry>`,
122 /// and a weak reference can only be minted from an `Arc`. `Weak` and not
123 /// `Arc`: the registry owns the sink, which owns the observer, so a strong
124 /// back-reference would be a cycle that never drops. This is a BREAKING
125 /// change to `trusty-code`'s public API — every in-workspace caller already
126 /// holds an `Arc<SessionRegistry>`, so no call site changed.
127 pub fn memory_sink_for(
128 self: &Arc<Self>,
129 id: &str,
130 project_dir: Option<&Path>,
131 ) -> Option<Arc<TurnMemorySink>> {
132 let project_dir = project_dir?;
133 // #5811: never let a failed resolution become a shared, auto-creatable
134 // palace id — decline the sink instead.
135 let palace = match derive_palace_id_for_project(project_dir) {
136 Ok(palace) => palace,
137 Err(e) => {
138 warn!(
139 project_dir = %project_dir.display(),
140 error = %e,
141 "turn_recorder: no palace could be resolved for this project — \
142 turn recording is DISABLED for this session (#5811)"
143 );
144 return None;
145 }
146 };
147 let mut sessions = self.lock();
148 let entry = sessions.get_mut(id)?;
149 if entry.memory_sink.is_none() {
150 let socket = trusty_common::memory_rpc::resolve_memory_socket_or_unreachable();
151 // #4638: only a durable project root entitles the recorder to bring
152 // a new palace into being — a temp root's id is unique per run.
153 let creation = if trusty_common::bin_resolve::is_under_system_temp(project_dir) {
154 debug!(
155 project_dir = %project_dir.display(),
156 palace = %palace,
157 "turn_recorder: project root is under a system temp root — \
158 palace auto-create withheld (#4638)"
159 );
160 PalaceCreation::Forbidden
161 } else {
162 PalaceCreation::Allowed
163 };
164 // #2425: the sink reports every turn's durability verdict back to
165 // this session's retained status.
166 let observer = Arc::new(RegistryMemoryDurabilityObserver {
167 registry: Arc::downgrade(self),
168 session_id: id.to_string(),
169 });
170 entry.memory_sink = Some(Arc::new(TurnMemorySink::new_observed(
171 socket, palace, creation, observer,
172 )));
173 }
174 entry.memory_sink.clone()
175 }
176
177 /// Fold one turn's durability verdict into the session's retained status,
178 /// emitting a session log event at each streak threshold it crosses
179 /// (#2425).
180 ///
181 /// Why: a fail-open sink makes a session whose durable history is thinning
182 /// look identical to a healthy one. Warning at the FIRST and THIRD
183 /// consecutive failure — rather than every failure — is what keeps a
184 /// multi-hour outage from burying the event log while still surfacing the
185 /// problem on the turn it starts.
186 /// What: `Err(session_not_found)` if the session is gone. `Err(internal)`
187 /// when the reconciler refuses the outcome because its pending-run bound is
188 /// exhausted; before returning that, `unrecorded_outcomes` is incremented,
189 /// so `session.get_transcript` still SAYS its counters under-report rather
190 /// than reading as if nothing was lost. Warning messages carry only the
191 /// closed [`crate::session::MemoryFailureCategory`] vocabulary and the two
192 /// counters — never a prompt, response, or daemon error string.
193 /// Test: `registry_tests::memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three`,
194 /// `registry_tests::outcome_beyond_the_reorder_bound_is_counted_as_unrecorded`,
195 /// `registry_tests::memory_degradation_event_is_redacted`.
196 pub(crate) fn record_memory_durability(
197 &self,
198 id: &str,
199 outcome: MemoryTurnOutcome,
200 ) -> Result<(), RpcError> {
201 let warnings = {
202 let mut sessions = self.lock();
203 let entry = sessions
204 .get_mut(id)
205 .ok_or_else(|| RpcError::session_not_found(id))?;
206 match entry
207 .memory_outcomes
208 .observe(&mut entry.memory_durability, outcome)
209 {
210 Ok(warnings) => warnings,
211 Err(()) => {
212 entry.memory_durability.unrecorded_outcomes = entry
213 .memory_durability
214 .unrecorded_outcomes
215 .saturating_add(1);
216 return Err(RpcError::internal("memory outcome reorder bound exceeded"));
217 }
218 }
219 };
220 for warning in warnings {
221 let total = self
222 .get_transcript(id)?
223 .memory_durability
224 .total_failed_turns;
225 self.record_log(
226 id,
227 "warn",
228 &format!(
229 "durable memory degraded: category={:?} total_failed_turns={total} \
230 consecutive_failed_turns={}",
231 warning.category, warning.consecutive
232 ),
233 )?;
234 }
235 Ok(())
236 }
237}
238
239/// The [`MemoryDurabilityObserver`] a registry-owned sink is built with.
240///
241/// Why: `Weak` breaks the registry -> sink -> observer -> registry cycle, so a
242/// dropped registry stays dropped.
243/// What: forwards each outcome to [`SessionRegistry::record_memory_durability`]
244/// on the thread that produced it.
245/// Test: `observer_tests::weak_observer_does_not_keep_registry_alive`,
246/// `observer_tests::unrecordable_outcomes_are_reported_in_subprocess`.
247struct RegistryMemoryDurabilityObserver {
248 registry: Weak<SessionRegistry>,
249 session_id: String,
250}
251
252impl MemoryDurabilityObserver for RegistryMemoryDurabilityObserver {
253 /// Report one outcome, failing OPEN on the turn and never SILENT on the
254 /// signal (#2425).
255 ///
256 /// Why: this runs on the turn path (a synchronous queue-full report from
257 /// `enqueue`) as well as in the detached drain, so it must not propagate,
258 /// block, or panic — a failed memory write must not kill the turn. That is
259 /// the execution contract, and it is unchanged. What it does NOT license is
260 /// discarding the error: `record_memory_durability` fails exactly when the
261 /// degradation signal could not be retained, so swallowing it made the
262 /// signal loss itself unobservable — which is the failure #2425 exists to
263 /// prevent. The registry-side counter this pairs with (`unrecorded_outcomes`)
264 /// survives only while the session does; the `warn!` here survives the
265 /// session's removal, which is the `session_not_found` case.
266 /// What: a dead registry means the session and its status died with it, so
267 /// there is nothing left to degrade and nothing to report. Any other error
268 /// is warned about with the RPC code and no session content.
269 /// Test: `observer_tests::weak_observer_does_not_keep_registry_alive`,
270 /// `observer_tests::unrecordable_outcomes_are_reported_in_subprocess`.
271 fn observe(&self, outcome: MemoryTurnOutcome) {
272 let Some(registry) = self.registry.upgrade() else {
273 return;
274 };
275 if let Err(error) = registry.record_memory_durability(&self.session_id, outcome) {
276 warn!(
277 failure_category = "memory_durability_unrecorded",
278 rpc_code = error.code,
279 "turn_recorder: a durable-memory outcome could not be recorded on its \
280 session — retained degradation counters under-report (#2425)"
281 );
282 }
283 }
284}
285
286#[cfg(test)]
287mod observer_tests {
288 use super::*;
289 use crate::session::memory_sink::MemoryFailureCategory;
290 use chrono::Utc;
291 use std::process::Command;
292
293 const UNRECORDABLE_CHILD_ENV: &str = "TCODE_MEMORY_UNRECORDABLE_OUTCOME_CHILD";
294 const CHILD_TEST_PATH: &str =
295 "session::registry::memory_sink_ext::observer_tests::unrecordable_outcome_child";
296 /// A prompt the child must never leak into a warning on stderr.
297 const PROMPT_SENTINEL: &str = "sk-live-session-prompt-do-not-leak";
298
299 /// The observer must not keep the registry it reports to alive — a strong
300 /// back-reference would be a cycle (registry -> sink -> observer).
301 #[test]
302 fn weak_observer_does_not_keep_registry_alive() {
303 let registry = Arc::new(SessionRegistry::new());
304 let weak = Arc::downgrade(®istry);
305 let observer = RegistryMemoryDurabilityObserver {
306 registry: weak.clone(),
307 session_id: "gone".into(),
308 };
309 drop(registry);
310 assert!(weak.upgrade().is_none());
311 observer.observe(MemoryTurnOutcome::Degraded {
312 sequence: 1,
313 category: MemoryFailureCategory::DrainClosed,
314 at: Utc::now(),
315 });
316 }
317
318 /// Drive both of `record_memory_durability`'s error arms through the
319 /// observer, with the warnings this test's parent reads off stderr.
320 ///
321 /// Runs only under the parent below — a bare `cargo test` sees it return
322 /// immediately.
323 #[test]
324 fn unrecordable_outcome_child() {
325 if std::env::var_os(UNRECORDABLE_CHILD_ENV).is_none() {
326 return;
327 }
328 crate::logging::init_tracing_for_test();
329
330 let registry = Arc::new(SessionRegistry::new());
331 let session = registry.create(
332 PROMPT_SENTINEL.to_string(),
333 None,
334 crate::binding::ProjectBinding::None,
335 );
336
337 // Arm 1: the session is gone. Nothing can retain the signal, so the
338 // warning on stderr is the only surviving record of it.
339 let orphaned = RegistryMemoryDurabilityObserver {
340 registry: Arc::downgrade(®istry),
341 session_id: "no-such-session".into(),
342 };
343 orphaned.observe(MemoryTurnOutcome::Degraded {
344 sequence: 1,
345 category: MemoryFailureCategory::QueueFull,
346 at: Utc::now(),
347 });
348
349 // Arm 2: sequence 1 never arrives, so every later outcome parks as its
350 // own non-adjacent pending run until the bound refuses one.
351 let observer = RegistryMemoryDurabilityObserver {
352 registry: Arc::downgrade(®istry),
353 session_id: session.id.clone(),
354 };
355 for sequence in (2..).step_by(2).take(reorder_bound() + 1) {
356 observer.observe(MemoryTurnOutcome::Degraded {
357 sequence,
358 category: MemoryFailureCategory::QueueFull,
359 at: Utc::now(),
360 });
361 }
362 }
363
364 /// #2425 regression: neither error arm of `record_memory_durability` may be
365 /// swallowed. `observe` cannot propagate (it runs on the turn path), so the
366 /// proof has to be read off the child's stderr.
367 #[test]
368 fn unrecordable_outcomes_are_reported_in_subprocess() {
369 let output = Command::new(std::env::current_exe().expect("current test binary"))
370 .args([
371 "--exact",
372 CHILD_TEST_PATH,
373 "--nocapture",
374 "--test-threads=1",
375 ])
376 .env(UNRECORDABLE_CHILD_ENV, "1")
377 .env("RUST_LOG", "warn")
378 .output()
379 .expect("run unrecordable outcome child");
380 let stderr = String::from_utf8_lossy(&output.stderr);
381 assert!(output.status.success(), "child failed: {stderr}");
382 assert_eq!(
383 stderr.matches("memory_durability_unrecorded").count(),
384 2,
385 "both a session_not_found and a bound-exceeded refusal must be \
386 reported, not swallowed: {stderr}"
387 );
388 assert!(
389 !stderr.contains(PROMPT_SENTINEL),
390 "the warning leaked session content: {stderr}"
391 );
392 }
393
394 /// How many non-adjacent pending runs the reconciler accepts before it
395 /// refuses one — mirrors its own `QUEUE_CAPACITY + 2`.
396 fn reorder_bound() -> usize {
397 crate::session::memory_sink::QUEUE_CAPACITY + 2
398 }
399}