Skip to main content

bamboo_domain/session/
persistence.rs

1use std::io;
2use std::sync::Arc;
3
4use crate::session::task::TaskList;
5use crate::session::types::Session;
6use crate::session::PermissionAuditSeed;
7
8/// Result of the retrieval-window-specific execute-boundary checkpoint.
9///
10/// `Rebased` means persistence observed a newer durable transcript, made no
11/// write, and replaced the caller's staged value with a clean reconciled base
12/// that must be planned and prepared again before dispatch.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum RetrievalWindowCheckpointOutcome {
15    Committed,
16    Rebased,
17}
18
19/// Immutable execution provenance for an already-persisted untagged Child wait.
20/// This capability is captured once from the execution's initial snapshot; it
21/// is not Session metadata and must never be reconstructed at a later save.
22#[derive(Debug, Clone)]
23pub struct InheritedChildWait {
24    session_id: String,
25    created_at: chrono::DateTime<chrono::Utc>,
26    wait: crate::WaitingForChildrenState,
27}
28
29impl InheritedChildWait {
30    pub fn capture(session: &Session) -> Option<Self> {
31        let wait = session
32            .agent_runtime_state
33            .as_ref()?
34            .waiting_for_children
35            .as_ref()?;
36        if wait.registered_by_tool_call_id.is_some() {
37            return None;
38        }
39        Some(Self {
40            session_id: session.id.clone(),
41            created_at: session.created_at,
42            wait: wait.clone(),
43        })
44    }
45
46    pub fn session_id(&self) -> &str {
47        &self.session_id
48    }
49
50    pub fn wait(&self) -> &crate::WaitingForChildrenState {
51        &self.wait
52    }
53
54    pub fn validate_session(&self, session: &Session) -> io::Result<()> {
55        if session.id != self.session_id || session.created_at != self.created_at {
56            return Err(io::Error::other(crate::SessionAuthorityConflict(
57                "inherited child wait session changed identity or birth".into(),
58            )));
59        }
60        Ok(())
61    }
62}
63
64/// Provider-boundary admission through the bound Root writer. None from the
65/// port below means this execution does not use ordinary Root authority.
66#[derive(Debug, Default)]
67pub struct RootInboxAdmission {
68    pub merged: usize,
69    pub committed_messages: Vec<crate::Message>,
70    pub admission_error: Option<String>,
71}
72
73/// Merge messages from a live runner snapshot into an already-durable
74/// transcript without ever removing or rewriting a durable message.
75///
76/// Runtime sessions are append-oriented, and every newly-created message has a
77/// stable id.  A runner may nevertheless be holding a snapshot that predates a
78/// concurrent append (for example, an injected child-completion message).  A
79/// terminal/error checkpoint must not full-save that stale snapshot: doing so
80/// would shrink the transcript.  Keep the durable ordering and append only the
81/// live messages whose ids are not durable yet.
82pub fn append_missing_runtime_messages(session: &mut Session, durable: &Session) -> usize {
83    let mut seen = durable
84        .messages
85        .iter()
86        .map(|message| message.id.clone())
87        .collect::<std::collections::HashSet<_>>();
88    let missing = session
89        .messages
90        .iter()
91        .filter(|message| seen.insert(message.id.clone()))
92        .cloned()
93        .collect::<Vec<_>>();
94    let appended = missing.len();
95    session.messages = durable.messages.iter().cloned().chain(missing).collect();
96    // Provider-native groups are message-anchored and append-only as well. A
97    // concurrent durable prefix must not be erased by a stale runner save, and
98    // a runner's newly completed group must remain paired with its new message.
99    session.merge_provider_transcript_from_durable(durable);
100    appended
101}
102
103/// Merge the durable SessionInbox admitted-id cursor into a writer snapshot.
104///
105/// Runtime writers can hold a session clone from before another run admitted
106/// an inbox message. No later full save may erase that durable dedupe state.
107pub fn merge_session_inbox_admission(session: &mut Session, durable: &Session) {
108    let Some(durable_state) = durable.session_inbox_admission().cloned() else {
109        return;
110    };
111    session
112        .session_inbox_admission_mut()
113        .merge_from(&durable_state);
114}
115
116/// Restore durable provider messages identified by their typed
117/// `metadata.session_message` marker into a stale writer without preserving
118/// unrelated durable suffixes. The bounded cursor is only a fast recent index;
119/// the transcript marker is the unbounded source of truth after cursor
120/// eviction.
121///
122/// Insertion follows durable transcript neighbors so an admitted user/runtime
123/// message remains ahead of any later assistant output held by the stale
124/// runner. This is narrower than [`append_missing_runtime_messages`], retaining
125/// the historical shrink semantics for unrelated concurrent messages while
126/// making a cursor/tombstone incapable of outliving its transcript entry.
127pub fn restore_missing_admitted_inbox_messages(session: &mut Session, durable: &Session) -> usize {
128    let admission = durable.session_inbox_admission();
129    let mut restored = 0;
130    for (durable_index, message) in durable.messages.iter().enumerate() {
131        let typed_marker = message
132            .metadata
133            .as_ref()
134            .and_then(|metadata| metadata.get("session_message"))
135            .is_some_and(|marker| {
136                marker.get("id").and_then(serde_json::Value::as_str) == Some(message.id.as_str())
137                    && marker
138                        .get("target_session_id")
139                        .and_then(serde_json::Value::as_str)
140                        == Some(durable.id.as_str())
141                    && crate::SessionMessageId::parse(message.id.clone()).is_ok()
142            });
143        let recent_cursor = admission.is_some_and(|state| state.contains_str(&message.id));
144        if !(typed_marker || recent_cursor)
145            || session
146                .messages
147                .iter()
148                .any(|current| current.id == message.id)
149        {
150            continue;
151        }
152
153        let insertion = durable.messages[..durable_index]
154            .iter()
155            .rev()
156            .find_map(|predecessor| {
157                session
158                    .messages
159                    .iter()
160                    .position(|current| current.id == predecessor.id)
161                    .map(|index| index + 1)
162            })
163            .or_else(|| {
164                durable.messages[durable_index + 1..]
165                    .iter()
166                    .find_map(|successor| {
167                        session
168                            .messages
169                            .iter()
170                            .position(|current| current.id == successor.id)
171                    })
172            })
173            .unwrap_or(session.messages.len());
174        session.messages.insert(insertion, message.clone());
175        restored += 1;
176    }
177    restored
178}
179
180/// Port for runtime (non-authoritative) session persistence.
181///
182/// Implementors must:
183/// - Serialize concurrent saves per session ID.
184/// - Merge on-disk authoritative metadata (`title`, `title_generated`, `pinned`, `title_version`,
185///   `metadata_version`) before writing, so UI edits are never clobbered.
186#[async_trait::async_trait]
187pub trait RuntimeSessionPersistence: Send + Sync {
188    /// An execution-private binding, never reconstructed from mutable state.
189    fn inherited_child_wait(&self) -> Option<InheritedChildWait> {
190        None
191    }
192
193    /// Return an execution-private view retaining the captured wait provenance
194    /// through every intermediate save. Unsupported persisters fail closed.
195    fn bind_inherited_child_wait(
196        &self,
197        _inherited: InheritedChildWait,
198    ) -> io::Result<Arc<dyn RuntimeSessionPersistence>> {
199        Err(io::Error::new(
200            io::ErrorKind::Unsupported,
201            crate::SessionAuthorityConflict(
202                "execution-scoped inherited child wait persistence is unsupported".into(),
203            ),
204        ))
205    }
206
207    /// Immutable capability already captured by this concrete execution.
208    /// An unbound Host/default persister never supplies a current owner.
209    fn root_actor_writer(&self) -> Option<crate::RootActorRuntimeWrite> {
210        None
211    }
212
213    /// Execution-private input restriction. A selector carries no authority;
214    /// only a persister already bound to a real Root writer may install it.
215    /// Unsupported hosts fail closed. This introduces no durable state.
216    fn bind_root_inbox_receipt(
217        &self,
218        _receipt: crate::SessionInboxReceipt,
219    ) -> io::Result<Arc<dyn RuntimeSessionPersistence>> {
220        Err(io::Error::new(
221            io::ErrorKind::Unsupported,
222            "Root receipt binding unsupported",
223        ))
224    }
225
226    fn root_inbox_receipt(&self) -> Option<&crate::SessionInboxReceipt> {
227        None
228    }
229
230    /// Whether this Host requires an explicit execution capability for the
231    /// proposed Root. A route without a bound event/persistence handoff must
232    /// reject before claiming or making a provider call.
233    fn root_actor_execution_required(&self, _session: &Session) -> bool {
234        false
235    }
236
237    /// Host execution binding, never a request DTO. Legacy embedders have no
238    /// ActorDirectory; a host that enables one must reject unsupported storage
239    /// before claiming rather than returning an unfenced writer.
240    async fn bind_root_actor_execution(
241        &self,
242        _session: &Session,
243        _run_id: &str,
244    ) -> io::Result<Option<RootActorExecutionBinding>> {
245        Ok(None)
246    }
247
248    /// Persist the session, merging any newer authoritative metadata from disk.
249    async fn save_runtime_session(&self, session: &mut Session) -> io::Result<()>;
250
251    /// Persist a runner's final snapshot. Implementations with a per-session
252    /// lock should reconcile a tool-registered child wait against the latest
253    /// durable wait inside that lock: a child may finish after the runner's
254    /// last read but before this save. The default retains compatibility for
255    /// in-memory and test persisters without that concurrent completion path.
256    async fn save_finalized_runtime_session(&self, session: &mut Session) -> io::Result<()> {
257        self.save_runtime_session(session).await
258    }
259
260    /// Finalize a wait inherited by this execution. Backends must reconcile
261    /// against durable state inside their cross-process write transaction.
262    /// Unsupported adapters fail closed rather than reopen a read/save race.
263    async fn save_finalized_runtime_with_inherited_child_wait(
264        &self,
265        session: &mut Session,
266        inherited: &crate::session::runtime_state::WaitingForChildrenState,
267    ) -> io::Result<()> {
268        let _ = (session, inherited);
269        Err(io::Error::new(
270            io::ErrorKind::Unsupported,
271            crate::SessionAuthorityConflict(
272                "atomic inherited child wait finalization is unsupported".into(),
273            ),
274        ))
275    }
276
277    /// Authoritatively seed one validated actor activation.
278    ///
279    /// Unlike an ordinary runtime save, the incoming RunSpec posture and its
280    /// complete audit record must replace any posture left by a previous warm
281    /// activation. Implementations must still preserve durable SessionInbox
282    /// admission/transcript proof and serialize the operation per session.
283    ///
284    /// There is no safe generic implementation through
285    /// [`Self::save_runtime_session`]: that primitive is explicitly allowed to
286    /// adopt a newer disk posture, which would make warm workers sticky across
287    /// runs. Custom persisters therefore fail closed until they implement this
288    /// authority boundary deliberately.
289    async fn seed_runtime_activation(&self, _session: &mut Session) -> io::Result<()> {
290        Err(io::Error::new(
291            io::ErrorKind::Unsupported,
292            "runtime persistence does not support authoritative activation seeding",
293        ))
294    }
295
296    /// Atomically persist a worker-declared executor mapping for the current
297    /// host-authoritative permission posture.
298    ///
299    /// The caller supplies the audit revision it observed before dispatch.
300    /// Implementations must load and compare that revision while holding the
301    /// per-session lock, reject a concurrent posture update, and allocate a new
302    /// host revision/timestamp themselves. Remote audit clocks are never an
303    /// authority at this boundary.
304    async fn record_permission_posture_activation(
305        &self,
306        _session_id: &str,
307        _expected_audit_revision: Option<u64>,
308        _seed: &PermissionAuditSeed,
309    ) -> io::Result<Option<Session>> {
310        Err(io::Error::new(
311            io::ErrorKind::Unsupported,
312            "runtime persistence does not support atomic permission posture activation",
313        ))
314    }
315
316    /// Persist only the runtime control-plane for a session.
317    ///
318    /// Task lists and other runtime metadata belong to the control-plane and do
319    /// not require rewriting the potentially large message transcript. Built-in
320    /// persistence implementations with a runtime sidecar should override this
321    /// operation with their sidecar-only path. Custom/legacy implementations
322    /// remain source-compatible and safely fall back to the full runtime save.
323    ///
324    /// Callers must not rely on this operation to persist message or
325    /// `model_context_state` changes. The durable ledger is checkpoint-owned;
326    /// sidecar implementations must preserve its latest committed value while
327    /// applying the caller's narrow control-plane mutation.
328    async fn save_runtime_control_plane(&self, session: &mut Session) -> io::Result<()> {
329        self.save_runtime_session(session).await
330    }
331
332    /// Load the representation paired with
333    /// [`save_runtime_control_plane`](Self::save_runtime_control_plane).
334    ///
335    /// Sidecar-capable implementations should return their message-free
336    /// control-plane snapshot. The default deliberately returns the full
337    /// runtime session: when the paired save also falls back to a full save,
338    /// retaining the transcript makes that fallback safe rather than replacing
339    /// durable messages with an empty sidecar-shaped snapshot.
340    async fn load_runtime_control_plane(&self, session_id: &str) -> io::Result<Option<Session>> {
341        self.load_runtime_session(session_id).await
342    }
343
344    /// Atomically update only the shared Task list and its version.
345    ///
346    /// The default is safe for custom/legacy persistence: it loads the full
347    /// runtime session, changes only Task-owned fields, then uses the paired
348    /// control-plane save (which itself defaults to a full save). Returning
349    /// `false` means the implementation could not load the target; callers that
350    /// also hold a [`Storage`](crate::storage::Storage) may retain legacy
351    /// behavior with an explicit full-load/full-save fallback.
352    ///
353    /// Implementations with per-session transactions should override this so
354    /// the load, narrow mutation and save share one critical section.
355    async fn update_task_list_control_plane(
356        &self,
357        session_id: &str,
358        task_list: &TaskList,
359        version: &str,
360    ) -> io::Result<bool> {
361        let Some(mut session) = self.load_runtime_session(session_id).await? else {
362            return Ok(false);
363        };
364        session.set_task_list(task_list.clone());
365        session.set_task_list_version_meta(version.to_string());
366        self.save_runtime_control_plane(&mut session).await?;
367        Ok(true)
368    }
369
370    /// Atomically update Task-owned control-plane fields only when the durable
371    /// Task generation and exact list still match the expected snapshot.
372    ///
373    /// `false` covers an unsupported atomic compare-and-patch, a missing target,
374    /// or a version conflict. Callers must treat it as a stale write and must
375    /// not publish their staged Task state. The default fails closed because a
376    /// load followed by a separately locked save is not an atomic CAS.
377    async fn update_task_list_control_plane_if_version(
378        &self,
379        session_id: &str,
380        expected_version: &str,
381        expected_task_list: &TaskList,
382        task_list: &TaskList,
383        version: &str,
384    ) -> io::Result<bool> {
385        let _ = (
386            session_id,
387            expected_version,
388            expected_task_list,
389            task_list,
390            version,
391        );
392        Ok(false)
393    }
394
395    /// Recoverably compare-and-patch the executing session and its shared root.
396    /// Implementations must validate both generations before either target is
397    /// written and may return `Ok(true)` only after both Task generations are
398    /// durable with no undo record that could later revert them. An error after
399    /// one physical write must restore both originals before returning or retain
400    /// durable recovery state and fail subsequent paired access closed until
401    /// recovery completes. Root-session callers pass the same id twice and
402    /// receive the single-target CAS semantics above.
403    async fn update_task_list_control_planes_if_version(
404        &self,
405        session_id: &str,
406        shared_session_id: &str,
407        expected_version: &str,
408        expected_task_list: &TaskList,
409        task_list: &TaskList,
410        version: &str,
411    ) -> io::Result<bool> {
412        if session_id == shared_session_id {
413            return self
414                .update_task_list_control_plane_if_version(
415                    session_id,
416                    expected_version,
417                    expected_task_list,
418                    task_list,
419                    version,
420                )
421                .await;
422        }
423        let _ = (
424            session_id,
425            shared_session_id,
426            expected_version,
427            expected_task_list,
428            task_list,
429            version,
430        );
431        Ok(false)
432    }
433
434    /// Append-safe checkpoint used at the shared engine execute boundary.
435    ///
436    /// Unlike [`save_runtime_session`](Self::save_runtime_session), this must
437    /// preserve messages that were appended durably by a concurrent writer
438    /// after the runner loaded its snapshot.  Implementations that can provide
439    /// a per-session transaction should override this method and perform the
440    /// load/merge/save under one lock.  The default still reconciles against a
441    /// latest snapshot for lightweight/custom SDK persisters; the built-in
442    /// storage implementation supplies the atomic variant.
443    async fn checkpoint_runtime_session(&self, session: &mut Session) -> io::Result<()> {
444        if let Some(durable) = self.load_runtime_session(&session.id).await? {
445            append_missing_runtime_messages(session, &durable);
446            merge_session_inbox_admission(session, &durable);
447        }
448        self.save_runtime_session(session).await
449    }
450
451    /// Only the existing owner may claim structured Loop inputs. Unsupported
452    /// adapters do not fall back to ordinary provider-message admission.
453    async fn claim_scoped_loop_controls(
454        &self,
455        _session: &Session,
456        _inbox: Arc<dyn crate::SessionInboxPort>,
457        _active_run_id: &str,
458        _limit: usize,
459    ) -> io::Result<Vec<crate::ScopedLoopControlClaim>> {
460        Err(io::Error::new(
461            io::ErrorKind::Unsupported,
462            "scoped Loop claims unsupported",
463        ))
464    }
465
466    /// State, immutable control outcome and typed consumption proof share the
467    /// actual target checkpoint; ACK is last. Err never means rollback.
468    async fn checkpoint_scoped_loop_control(
469        &self,
470        _session: &mut Session,
471        _bindings: &[crate::ScopedLoopControlBinding],
472        _activation: Arc<dyn crate::SessionActivationPort>,
473        _input: Option<(
474            Arc<dyn crate::SessionInboxPort>,
475            crate::ScopedLoopControlClaim,
476        )>,
477    ) -> io::Result<()> {
478        Err(io::Error::new(
479            io::ErrorKind::Unsupported,
480            "scoped Loop checkpoint unsupported",
481        ))
482    }
483
484    /// Canonical read after a failed/uncertain checkpoint. A cached Session or
485    /// the proposed caller snapshot is not confirmation of what was written.
486    async fn load_loop_control_checkpoint(&self, _session_id: &str) -> io::Result<Option<Session>> {
487        Err(io::Error::new(
488            io::ErrorKind::Unsupported,
489            "strict Loop checkpoint reload unsupported",
490        ))
491    }
492
493    async fn admit_root_inbox(
494        &self,
495        _session: &mut Session,
496        _inbox: Arc<dyn crate::SessionInboxPort>,
497        _active_run_id: Option<&str>,
498    ) -> io::Result<Option<RootInboxAdmission>> {
499        Ok(None)
500    }
501
502    /// Atomically commit a staged archive transcript rewrite.
503    ///
504    /// `expected_base` is the exact pre-archive Session used for planning.
505    /// Implementations must compare it with the latest durable transcript while
506    /// holding their per-session serialization lock. If a concurrent append or
507    /// rewrite is present, they must perform no save, rebase `staged` onto that
508    /// durable snapshot, and return [`RetrievalWindowCheckpointOutcome::Rebased`].
509    /// Otherwise they must preserve the staged message archive flags and commit
510    /// them with the compression event and model-context reset. The built-in
511    /// implementation also accepts a MessageSummary archive through this same
512    /// boundary, preserving raw history while replacing its derived summary.
513    ///
514    /// There is no safe fallback through the ordinary append-only checkpoint,
515    /// because that path deliberately restores durable message clones and would
516    /// erase the new archive flags. Custom persisters therefore fail closed
517    /// until they implement this boundary explicitly.
518    async fn checkpoint_retrieval_window(
519        &self,
520        _expected_base: &Session,
521        _staged: &mut Session,
522    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
523        Err(io::Error::new(
524            io::ErrorKind::Unsupported,
525            "runtime persistence does not support retrieval-window checkpoints",
526        ))
527    }
528
529    /// Atomically commit a provider-visible System-prompt rewrite.
530    ///
531    /// This is deliberately separate from both the append-safe runtime
532    /// checkpoint (which must restore durable message content) and the
533    /// retrieval-window archive checkpoint (which requires a new archive
534    /// event). Implementations compare `expected_base` under their per-session
535    /// lock, return `Rebased` without writing on conflict, and accept only the
536    /// bounded prompt rewrite plus its provider/model-context reset.
537    async fn checkpoint_prompt_rewrite(
538        &self,
539        _expected_base: &Session,
540        _staged: &mut Session,
541    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
542        Err(io::Error::new(
543            io::ErrorKind::Unsupported,
544            "runtime persistence does not support prompt-rewrite checkpoints",
545        ))
546    }
547
548    /// Atomically commit one permanently rejected `archive_context` result.
549    ///
550    /// This boundary permits only the correlated Tool result rewrite, the
551    /// bounded consumed/rejection metadata, and the provider/model-context
552    /// reset required to make that rewrite visible. Implementations compare
553    /// `expected_base` under their per-session lock and return `Rebased`
554    /// without writing when the durable transcript changed concurrently.
555    async fn checkpoint_manual_archive_rejection(
556        &self,
557        _expected_base: &Session,
558        _staged: &mut Session,
559    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
560        Err(io::Error::new(
561            io::ErrorKind::Unsupported,
562            "runtime persistence does not support manual archive-rejection checkpoints",
563        ))
564    }
565
566    /// Atomically consume one successful no-op `archive_context` request.
567    ///
568    /// This boundary permits only the correlated consumed-occurrence marker.
569    /// Implementations compare `expected_base` under their per-session lock
570    /// and return `Rebased` without writing when any durable transcript,
571    /// metadata, runtime metadata, or execution-profile field changed. The
572    /// caller must then restage the marker from the returned durable snapshot.
573    async fn checkpoint_manual_archive_consumption(
574        &self,
575        _expected_base: &Session,
576        _staged: &mut Session,
577    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
578        Err(io::Error::new(
579            io::ErrorKind::Unsupported,
580            "runtime persistence does not support manual archive-consumption checkpoints",
581        ))
582    }
583
584    /// Load the latest runtime-visible session snapshot when the persistence
585    /// implementation can coordinate reads. Tools may update a repository-owned
586    /// clone while an agent loop holds its own live Session; the loop uses this
587    /// hook to merge narrowly-scoped tool side effects before its next save.
588    async fn load_runtime_session(&self, _session_id: &str) -> io::Result<Option<Session>> {
589        Ok(None)
590    }
591
592    /// Read a canonical snapshot for execution admission without publishing or
593    /// trusting a cached clone. Preserve the same bound-reader checks as the
594    /// runtime loader. A persister with a cache must override this operation to
595    /// read its durable source (or return Unsupported); the default serves
596    /// uncached/legacy loaders. This read never grants execution/write authority.
597    async fn load_runtime_admission_snapshot(
598        &self,
599        session_id: &str,
600    ) -> io::Result<Option<Session>> {
601        self.load_runtime_session(session_id).await
602    }
603
604    /// Clear the bounded compatibility queue iff it still equals the entries
605    /// that were durably copied into SessionInbox. Implementations with a
606    /// per-session transaction should override this method.
607    async fn clear_legacy_pending_messages(
608        &self,
609        session_id: &str,
610        expected: &[serde_json::Value],
611    ) -> io::Result<bool> {
612        let Some(mut latest) = self.load_runtime_session(session_id).await? else {
613            return Ok(false);
614        };
615        if latest.pending_injected_messages().as_deref() != Some(expected) {
616            return Ok(false);
617        }
618        latest.clear_pending_injected_messages();
619        self.save_runtime_session(&mut latest).await?;
620        Ok(true)
621    }
622
623    /// Append one JSON-line analysis record to the session's append-only
624    /// token-usage log (see [`Storage::append_token_usage_record`]). Defaults to
625    /// a no-op so non-file-backed persisters are unaffected.
626    ///
627    /// [`Storage::append_token_usage_record`]: crate::storage::Storage::append_token_usage_record
628    async fn append_token_usage_record(&self, session_id: &str, json_line: &str) -> io::Result<()> {
629        let _ = (session_id, json_line);
630        Ok(())
631    }
632}
633
634/// Ownership passed from the canonical repository into one concrete runtime.
635/// The runtime owns renewal and finish; dropping an execution must release its
636/// own fence without ever finishing a replacement owner.
637pub struct RootActorExecutionBinding {
638    pub persistence: Arc<dyn RuntimeSessionPersistence>,
639    pub directory: Arc<dyn crate::ActorDirectoryPort>,
640    pub owner: crate::RootActorRuntimeWrite,
641    pub lease_duration: std::time::Duration,
642    abandon: Option<Box<dyn FnOnce() + Send + Sync>>,
643}
644
645impl RootActorExecutionBinding {
646    pub fn new(
647        persistence: Arc<dyn RuntimeSessionPersistence>,
648        directory: Arc<dyn crate::ActorDirectoryPort>,
649        owner: crate::RootActorRuntimeWrite,
650        lease_duration: std::time::Duration,
651        abandon: impl FnOnce() + Send + Sync + 'static,
652    ) -> Self {
653        Self {
654            persistence,
655            directory,
656            owner,
657            lease_duration,
658            abandon: Some(Box::new(abandon)),
659        }
660    }
661
662    /// The runtime calls this only after handing finish to an owned detached
663    /// job, so cancellation of the waiter cannot strand this execution.
664    pub fn disarm_abandonment(&mut self) {
665        self.abandon.take();
666    }
667}
668
669impl Drop for RootActorExecutionBinding {
670    fn drop(&mut self) {
671        if let Some(abandon) = self.abandon.take() {
672            abandon();
673        }
674    }
675}
676
677#[async_trait::async_trait]
678impl<T: RuntimeSessionPersistence + ?Sized> RuntimeSessionPersistence for Arc<T> {
679    fn inherited_child_wait(&self) -> Option<InheritedChildWait> {
680        (**self).inherited_child_wait()
681    }
682
683    fn bind_inherited_child_wait(
684        &self,
685        inherited: InheritedChildWait,
686    ) -> io::Result<Arc<dyn RuntimeSessionPersistence>> {
687        (**self).bind_inherited_child_wait(inherited)
688    }
689
690    fn root_actor_writer(&self) -> Option<crate::RootActorRuntimeWrite> {
691        (**self).root_actor_writer()
692    }
693
694    fn bind_root_inbox_receipt(
695        &self,
696        receipt: crate::SessionInboxReceipt,
697    ) -> io::Result<Arc<dyn RuntimeSessionPersistence>> {
698        (**self).bind_root_inbox_receipt(receipt)
699    }
700
701    fn root_inbox_receipt(&self) -> Option<&crate::SessionInboxReceipt> {
702        (**self).root_inbox_receipt()
703    }
704
705    fn root_actor_execution_required(&self, session: &Session) -> bool {
706        (**self).root_actor_execution_required(session)
707    }
708
709    async fn bind_root_actor_execution(
710        &self,
711        session: &Session,
712        run_id: &str,
713    ) -> io::Result<Option<RootActorExecutionBinding>> {
714        (**self).bind_root_actor_execution(session, run_id).await
715    }
716    async fn save_runtime_session(&self, session: &mut Session) -> io::Result<()> {
717        (**self).save_runtime_session(session).await
718    }
719
720    async fn save_finalized_runtime_session(&self, session: &mut Session) -> io::Result<()> {
721        (**self).save_finalized_runtime_session(session).await
722    }
723
724    async fn save_finalized_runtime_with_inherited_child_wait(
725        &self,
726        session: &mut Session,
727        inherited: &crate::session::runtime_state::WaitingForChildrenState,
728    ) -> io::Result<()> {
729        (**self)
730            .save_finalized_runtime_with_inherited_child_wait(session, inherited)
731            .await
732    }
733
734    async fn seed_runtime_activation(&self, session: &mut Session) -> io::Result<()> {
735        (**self).seed_runtime_activation(session).await
736    }
737
738    async fn record_permission_posture_activation(
739        &self,
740        session_id: &str,
741        expected_audit_revision: Option<u64>,
742        seed: &PermissionAuditSeed,
743    ) -> io::Result<Option<Session>> {
744        (**self)
745            .record_permission_posture_activation(session_id, expected_audit_revision, seed)
746            .await
747    }
748
749    async fn save_runtime_control_plane(&self, session: &mut Session) -> io::Result<()> {
750        (**self).save_runtime_control_plane(session).await
751    }
752
753    async fn load_runtime_control_plane(&self, session_id: &str) -> io::Result<Option<Session>> {
754        (**self).load_runtime_control_plane(session_id).await
755    }
756
757    async fn update_task_list_control_plane(
758        &self,
759        session_id: &str,
760        task_list: &TaskList,
761        version: &str,
762    ) -> io::Result<bool> {
763        (**self)
764            .update_task_list_control_plane(session_id, task_list, version)
765            .await
766    }
767
768    async fn update_task_list_control_plane_if_version(
769        &self,
770        session_id: &str,
771        expected_version: &str,
772        expected_task_list: &TaskList,
773        task_list: &TaskList,
774        version: &str,
775    ) -> io::Result<bool> {
776        (**self)
777            .update_task_list_control_plane_if_version(
778                session_id,
779                expected_version,
780                expected_task_list,
781                task_list,
782                version,
783            )
784            .await
785    }
786
787    async fn update_task_list_control_planes_if_version(
788        &self,
789        session_id: &str,
790        shared_session_id: &str,
791        expected_version: &str,
792        expected_task_list: &TaskList,
793        task_list: &TaskList,
794        version: &str,
795    ) -> io::Result<bool> {
796        (**self)
797            .update_task_list_control_planes_if_version(
798                session_id,
799                shared_session_id,
800                expected_version,
801                expected_task_list,
802                task_list,
803                version,
804            )
805            .await
806    }
807
808    async fn checkpoint_runtime_session(&self, session: &mut Session) -> io::Result<()> {
809        (**self).checkpoint_runtime_session(session).await
810    }
811
812    async fn claim_scoped_loop_controls(
813        &self,
814        session: &Session,
815        inbox: Arc<dyn crate::SessionInboxPort>,
816        active_run_id: &str,
817        limit: usize,
818    ) -> io::Result<Vec<crate::ScopedLoopControlClaim>> {
819        (**self)
820            .claim_scoped_loop_controls(session, inbox, active_run_id, limit)
821            .await
822    }
823
824    async fn checkpoint_scoped_loop_control(
825        &self,
826        session: &mut Session,
827        bindings: &[crate::ScopedLoopControlBinding],
828        activation: Arc<dyn crate::SessionActivationPort>,
829        input: Option<(
830            Arc<dyn crate::SessionInboxPort>,
831            crate::ScopedLoopControlClaim,
832        )>,
833    ) -> io::Result<()> {
834        (**self)
835            .checkpoint_scoped_loop_control(session, bindings, activation, input)
836            .await
837    }
838
839    async fn load_loop_control_checkpoint(&self, session_id: &str) -> io::Result<Option<Session>> {
840        (**self).load_loop_control_checkpoint(session_id).await
841    }
842
843    async fn admit_root_inbox(
844        &self,
845        session: &mut Session,
846        inbox: Arc<dyn crate::SessionInboxPort>,
847        active_run_id: Option<&str>,
848    ) -> io::Result<Option<RootInboxAdmission>> {
849        (**self)
850            .admit_root_inbox(session, inbox, active_run_id)
851            .await
852    }
853
854    async fn checkpoint_retrieval_window(
855        &self,
856        expected_base: &Session,
857        staged: &mut Session,
858    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
859        (**self)
860            .checkpoint_retrieval_window(expected_base, staged)
861            .await
862    }
863
864    async fn checkpoint_prompt_rewrite(
865        &self,
866        expected_base: &Session,
867        staged: &mut Session,
868    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
869        (**self)
870            .checkpoint_prompt_rewrite(expected_base, staged)
871            .await
872    }
873
874    async fn checkpoint_manual_archive_rejection(
875        &self,
876        expected_base: &Session,
877        staged: &mut Session,
878    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
879        (**self)
880            .checkpoint_manual_archive_rejection(expected_base, staged)
881            .await
882    }
883
884    async fn checkpoint_manual_archive_consumption(
885        &self,
886        expected_base: &Session,
887        staged: &mut Session,
888    ) -> io::Result<RetrievalWindowCheckpointOutcome> {
889        (**self)
890            .checkpoint_manual_archive_consumption(expected_base, staged)
891            .await
892    }
893
894    async fn load_runtime_session(&self, session_id: &str) -> io::Result<Option<Session>> {
895        (**self).load_runtime_session(session_id).await
896    }
897
898    async fn load_runtime_admission_snapshot(
899        &self,
900        session_id: &str,
901    ) -> io::Result<Option<Session>> {
902        (**self).load_runtime_admission_snapshot(session_id).await
903    }
904
905    async fn clear_legacy_pending_messages(
906        &self,
907        session_id: &str,
908        expected: &[serde_json::Value],
909    ) -> io::Result<bool> {
910        (**self)
911            .clear_legacy_pending_messages(session_id, expected)
912            .await
913    }
914
915    async fn append_token_usage_record(&self, session_id: &str, json_line: &str) -> io::Result<()> {
916        (**self)
917            .append_token_usage_record(session_id, json_line)
918            .await
919    }
920}