Skip to main content

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, resolve_recorder_socket,
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 [`resolve_recorder_socket`] (never the live daemon from a test
54    /// process, #9139; 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            // #9139: a test process never binds the operator's live daemon.
151            let socket = resolve_recorder_socket();
152            // #4638: only a durable project root entitles the recorder to bring
153            // a new palace into being — a temp root's id is unique per run.
154            let creation = if trusty_common::bin_resolve::is_under_system_temp(project_dir) {
155                debug!(
156                    project_dir = %project_dir.display(),
157                    palace = %palace,
158                    "turn_recorder: project root is under a system temp root — \
159                     palace auto-create withheld (#4638)"
160                );
161                PalaceCreation::Forbidden
162            } else {
163                PalaceCreation::Allowed
164            };
165            // #2425: the sink reports every turn's durability verdict back to
166            // this session's retained status.
167            let observer = Arc::new(RegistryMemoryDurabilityObserver {
168                registry: Arc::downgrade(self),
169                session_id: id.to_string(),
170            });
171            entry.memory_sink = Some(Arc::new(TurnMemorySink::new_observed(
172                socket, palace, creation, observer,
173            )));
174        }
175        entry.memory_sink.clone()
176    }
177
178    /// Fold one turn's durability verdict into the session's retained status,
179    /// emitting a session log event at each streak threshold it crosses
180    /// (#2425).
181    ///
182    /// Why: a fail-open sink makes a session whose durable history is thinning
183    /// look identical to a healthy one. Warning at the FIRST and THIRD
184    /// consecutive failure — rather than every failure — is what keeps a
185    /// multi-hour outage from burying the event log while still surfacing the
186    /// problem on the turn it starts.
187    /// What: `Err(session_not_found)` if the session is gone. `Err(internal)`
188    /// when the reconciler refuses the outcome because its pending-run bound is
189    /// exhausted; before returning that, `unrecorded_outcomes` is incremented,
190    /// so `session.get_transcript` still SAYS its counters under-report rather
191    /// than reading as if nothing was lost. Warning messages carry only the
192    /// closed [`crate::session::MemoryFailureCategory`] vocabulary and the two
193    /// counters — never a prompt, response, or daemon error string.
194    /// Test: `registry_tests::memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three`,
195    /// `registry_tests::outcome_beyond_the_reorder_bound_is_counted_as_unrecorded`,
196    /// `registry_tests::memory_degradation_event_is_redacted`.
197    pub(crate) fn record_memory_durability(
198        &self,
199        id: &str,
200        outcome: MemoryTurnOutcome,
201    ) -> Result<(), RpcError> {
202        let warnings = {
203            let mut sessions = self.lock();
204            let entry = sessions
205                .get_mut(id)
206                .ok_or_else(|| RpcError::session_not_found(id))?;
207            match entry
208                .memory_outcomes
209                .observe(&mut entry.memory_durability, outcome)
210            {
211                Ok(warnings) => warnings,
212                Err(()) => {
213                    entry.memory_durability.unrecorded_outcomes = entry
214                        .memory_durability
215                        .unrecorded_outcomes
216                        .saturating_add(1);
217                    return Err(RpcError::internal("memory outcome reorder bound exceeded"));
218                }
219            }
220        };
221        for warning in warnings {
222            let total = self
223                .get_transcript(id)?
224                .memory_durability
225                .total_failed_turns;
226            self.record_log(
227                id,
228                "warn",
229                &format!(
230                    "durable memory degraded: category={:?} total_failed_turns={total} \
231                     consecutive_failed_turns={}",
232                    warning.category, warning.consecutive
233                ),
234            )?;
235        }
236        Ok(())
237    }
238}
239
240/// The [`MemoryDurabilityObserver`] a registry-owned sink is built with.
241///
242/// Why: `Weak` breaks the registry -> sink -> observer -> registry cycle, so a
243/// dropped registry stays dropped.
244/// What: forwards each outcome to [`SessionRegistry::record_memory_durability`]
245/// on the thread that produced it.
246/// Test: `observer_tests::weak_observer_does_not_keep_registry_alive`,
247/// `observer_tests::unrecordable_outcomes_are_reported_in_subprocess`.
248struct RegistryMemoryDurabilityObserver {
249    registry: Weak<SessionRegistry>,
250    session_id: String,
251}
252
253impl MemoryDurabilityObserver for RegistryMemoryDurabilityObserver {
254    /// Report one outcome, failing OPEN on the turn and never SILENT on the
255    /// signal (#2425).
256    ///
257    /// Why: this runs on the turn path (a synchronous queue-full report from
258    /// `enqueue`) as well as in the detached drain, so it must not propagate,
259    /// block, or panic — a failed memory write must not kill the turn. That is
260    /// the execution contract, and it is unchanged. What it does NOT license is
261    /// discarding the error: `record_memory_durability` fails exactly when the
262    /// degradation signal could not be retained, so swallowing it made the
263    /// signal loss itself unobservable — which is the failure #2425 exists to
264    /// prevent. The registry-side counter this pairs with (`unrecorded_outcomes`)
265    /// survives only while the session does; the `warn!` here survives the
266    /// session's removal, which is the `session_not_found` case.
267    /// What: a dead registry means the session and its status died with it, so
268    /// there is nothing left to degrade and nothing to report. Any other error
269    /// is warned about with the RPC code and no session content.
270    /// Test: `observer_tests::weak_observer_does_not_keep_registry_alive`,
271    /// `observer_tests::unrecordable_outcomes_are_reported_in_subprocess`.
272    fn observe(&self, outcome: MemoryTurnOutcome) {
273        let Some(registry) = self.registry.upgrade() else {
274            return;
275        };
276        if let Err(error) = registry.record_memory_durability(&self.session_id, outcome) {
277            warn!(
278                failure_category = "memory_durability_unrecorded",
279                rpc_code = error.code,
280                "turn_recorder: a durable-memory outcome could not be recorded on its \
281                 session — retained degradation counters under-report (#2425)"
282            );
283        }
284    }
285}
286
287#[cfg(test)]
288mod observer_tests {
289    use super::*;
290    use crate::session::memory_sink::MemoryFailureCategory;
291    use chrono::Utc;
292    use std::process::Command;
293
294    const UNRECORDABLE_CHILD_ENV: &str = "TCODE_MEMORY_UNRECORDABLE_OUTCOME_CHILD";
295    const CHILD_TEST_PATH: &str =
296        "session::registry::memory_sink_ext::observer_tests::unrecordable_outcome_child";
297    /// A prompt the child must never leak into a warning on stderr.
298    const PROMPT_SENTINEL: &str = "sk-live-session-prompt-do-not-leak";
299
300    /// The observer must not keep the registry it reports to alive — a strong
301    /// back-reference would be a cycle (registry -> sink -> observer).
302    #[test]
303    fn weak_observer_does_not_keep_registry_alive() {
304        let registry = Arc::new(SessionRegistry::new());
305        let weak = Arc::downgrade(&registry);
306        let observer = RegistryMemoryDurabilityObserver {
307            registry: weak.clone(),
308            session_id: "gone".into(),
309        };
310        drop(registry);
311        assert!(weak.upgrade().is_none());
312        observer.observe(MemoryTurnOutcome::Degraded {
313            sequence: 1,
314            category: MemoryFailureCategory::DrainClosed,
315            at: Utc::now(),
316        });
317    }
318
319    /// Drive both of `record_memory_durability`'s error arms through the
320    /// observer, with the warnings this test's parent reads off stderr.
321    ///
322    /// Runs only under the parent below — a bare `cargo test` sees it return
323    /// immediately.
324    #[test]
325    fn unrecordable_outcome_child() {
326        if std::env::var_os(UNRECORDABLE_CHILD_ENV).is_none() {
327            return;
328        }
329        crate::logging::init_tracing_for_test();
330
331        let registry = Arc::new(SessionRegistry::new());
332        let session = registry.create(
333            PROMPT_SENTINEL.to_string(),
334            None,
335            crate::binding::ProjectBinding::None,
336        );
337
338        // Arm 1: the session is gone. Nothing can retain the signal, so the
339        // warning on stderr is the only surviving record of it.
340        let orphaned = RegistryMemoryDurabilityObserver {
341            registry: Arc::downgrade(&registry),
342            session_id: "no-such-session".into(),
343        };
344        orphaned.observe(MemoryTurnOutcome::Degraded {
345            sequence: 1,
346            category: MemoryFailureCategory::QueueFull,
347            at: Utc::now(),
348        });
349
350        // Arm 2: sequence 1 never arrives, so every later outcome parks as its
351        // own non-adjacent pending run until the bound refuses one.
352        let observer = RegistryMemoryDurabilityObserver {
353            registry: Arc::downgrade(&registry),
354            session_id: session.id.clone(),
355        };
356        for sequence in (2..).step_by(2).take(reorder_bound() + 1) {
357            observer.observe(MemoryTurnOutcome::Degraded {
358                sequence,
359                category: MemoryFailureCategory::QueueFull,
360                at: Utc::now(),
361            });
362        }
363    }
364
365    /// #2425 regression: neither error arm of `record_memory_durability` may be
366    /// swallowed. `observe` cannot propagate (it runs on the turn path), so the
367    /// proof has to be read off the child's stderr.
368    #[test]
369    fn unrecordable_outcomes_are_reported_in_subprocess() {
370        let output = Command::new(std::env::current_exe().expect("current test binary"))
371            .args([
372                "--exact",
373                CHILD_TEST_PATH,
374                "--nocapture",
375                "--test-threads=1",
376            ])
377            .env(UNRECORDABLE_CHILD_ENV, "1")
378            .env("RUST_LOG", "warn")
379            .output()
380            .expect("run unrecordable outcome child");
381        let stderr = String::from_utf8_lossy(&output.stderr);
382        assert!(output.status.success(), "child failed: {stderr}");
383        assert_eq!(
384            stderr.matches("memory_durability_unrecorded").count(),
385            2,
386            "both a session_not_found and a bound-exceeded refusal must be \
387             reported, not swallowed: {stderr}"
388        );
389        assert!(
390            !stderr.contains(PROMPT_SENTINEL),
391            "the warning leaked session content: {stderr}"
392        );
393    }
394
395    /// How many non-adjacent pending runs the reconciler accepts before it
396    /// refuses one — mirrors its own `QUEUE_CAPACITY + 2`.
397    fn reorder_bound() -> usize {
398        crate::session::memory_sink::QUEUE_CAPACITY + 2
399    }
400}