bamboo-storage 2026.10.13

Session storage backends for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
//! Child-wait mutations share the canonical physical Session writer boundary.
//! They own wait/control fields, never transcript or Actor execution authority.

use super::*;
use bamboo_domain::{
    AgentRuntimeState, ChildWaitPolicy, RootActorRuntimePublisher, WaitingForChildrenState,
};

pub(crate) fn runtime(session: &Session) -> AgentRuntimeState {
    session
        .agent_runtime_state
        .clone()
        .or_else(|| {
            session
                .metadata
                .get("agent.runtime.state")
                .and_then(|raw| serde_json::from_str(raw).ok())
        })
        .unwrap_or_else(|| AgentRuntimeState::new(format!("{}-child-wait", session.id)))
}

pub(crate) fn write_runtime(session: &mut Session, state: AgentRuntimeState) -> io::Result<()> {
    session.metadata.insert(
        "agent.runtime.state".into(),
        serde_json::to_string(&state).map_err(|error| other_io_error(error.to_string()))?,
    );
    session.agent_runtime_state = Some(state);
    Ok(())
}

pub(crate) fn validate_incarnation(expected: &Session, latest: &Session) -> io::Result<()> {
    if expected.id != latest.id
        || expected.created_at != latest.created_at
        || expected.kind != latest.kind
        || expected.parent_session_id != latest.parent_session_id
        || expected.root_session_id != latest.root_session_id
        || expected.authority_identity != latest.authority_identity
        || expected.spawn_depth != latest.spawn_depth
        || expected.project_id_meta() != latest.project_id_meta()
    {
        return Err(io::Error::new(
            io::ErrorKind::WouldBlock,
            bamboo_domain::SessionAuthorityConflict(
                "child wait Session incarnation changed".into(),
            ),
        ));
    }
    Ok(())
}

pub(crate) fn terminal(status: &str) -> bool {
    matches!(
        status,
        "completed" | "error" | "timeout" | "cancelled" | "skipped"
    )
}

pub(crate) fn is_observation(expected: &Session, updated: &Session) -> bool {
    runtime(expected) == runtime(updated)
        && ["runtime.suspend_reason", "guardian.state"]
            .iter()
            .all(|key| expected.metadata.get(*key) == updated.metadata.get(*key))
        && expected
            .messages
            .iter()
            .map(|message| &message.id)
            .eq(updated.messages.iter().map(|message| &message.id))
}

pub(crate) fn register_pending(
    latest: &mut Session,
    pending: Vec<(String, Option<String>)>,
    policy: ChildWaitPolicy,
) -> io::Result<()> {
    let mut state = runtime(latest);
    let mut wait = state
        .waiting_for_children
        .take()
        .unwrap_or_else(|| WaitingForChildrenState::for_children(Vec::new(), policy, Utc::now()));
    wait.wait_for = policy;
    for (id, tag) in pending {
        wait.child_session_ids.push(id);
        if wait.registered_by_tool_call_id.is_none() {
            wait.registered_by_tool_call_id = tag;
        }
    }
    wait.child_session_ids.sort();
    wait.child_session_ids.dedup();
    state.waiting_for_children = Some(wait);
    write_runtime(latest, state)?;
    latest.metadata.insert(
        "runtime.suspend_reason".into(),
        "waiting_for_children".into(),
    );
    latest.updated_at = Utc::now();
    Ok(())
}

pub(crate) fn apply_transition(
    latest: &mut Session,
    expected: &Session,
    updated: &Session,
    runtime_only: bool,
) -> io::Result<()> {
    let mut state = runtime(latest);
    let before = runtime(expected);
    let desired = runtime(updated);
    state.waiting_for_children = desired.waiting_for_children;
    // A partial Guardian outcome can update only its verdict while another
    // activation opens the parent's reasoning gate. Apply the coordinator's
    // actual changes, rather than restoring its older runner snapshot.
    if desired.status != before.status {
        state.status = desired.status;
    }
    if desired.suspension != before.suspension {
        state.suspension = desired.suspension;
    }
    write_runtime(latest, state)?;
    for key in ["runtime.suspend_reason", "guardian.state"] {
        if updated.metadata.get(key) != expected.metadata.get(key) {
            match updated.metadata.get(key) {
                Some(value) => {
                    latest.metadata.insert(key.into(), value.clone());
                }
                None => {
                    latest.metadata.remove(key);
                }
            }
        }
    }
    latest.updated_at = Utc::now();
    if !runtime_only {
        for message in &updated.messages {
            if !expected.messages.iter().any(|old| old.id == message.id)
                && !latest.messages.iter().any(|old| old.id == message.id)
            {
                latest.messages.push(message.clone());
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod incremental_wait_tests {
    use super::*;
    use bamboo_domain::{AgentStatusState, SuspensionState};

    #[tokio::test]
    async fn partial_guardian_verdict_preserves_concurrently_activated_parent() {
        let temp = tempfile::tempdir().unwrap();
        let store = SessionStoreV2::new(temp.path().into()).await.unwrap();
        let mut expected = Session::new("partial-guardian-parent", "model");
        let mut state = AgentRuntimeState::new("waiting-run");
        state.status = AgentStatusState::Suspended;
        let original = WaitingForChildrenState::for_children(
            vec!["guardian".into(), "slow-child".into()],
            ChildWaitPolicy::All,
            Utc::now(),
        );
        state.waiting_for_children = Some(original.clone());
        state.suspension = Some(SuspensionState {
            reason: "waiting_for_children".into(),
            suspended_at: Utc::now(),
            resumable: true,
            hook_point: Some("ChildCompletion".into()),
        });
        write_runtime(&mut expected, state).unwrap();
        store.save_session(&expected).await.unwrap();

        let mut activated = expected.clone();
        let mut running = runtime(&activated);
        running.run_id = "new-parent-owner".into();
        running.status = AgentStatusState::Running;
        running.suspension = None;
        write_runtime(&mut activated, running).unwrap();
        store.save_session(&activated).await.unwrap();

        let mut verdict = expected.clone();
        verdict
            .metadata
            .insert("guardian.state".into(), "approved".into());
        assert!(store
            .compare_exchange_child_wait(&expected, &mut verdict, true, Arc::new(|_| {}),)
            .await
            .unwrap());
        let saved = store.load_session(&expected.id).await.unwrap().unwrap();
        let state = runtime(&saved);
        assert_eq!(state.run_id, "new-parent-owner");
        assert_eq!(state.status, AgentStatusState::Running);
        assert!(state.suspension.is_none());
        assert_eq!(state.waiting_for_children, Some(original));
        assert_eq!(
            saved.metadata.get("guardian.state").map(String::as_str),
            Some("approved")
        );
    }
}

impl SessionStoreV2 {
    /// Test-only barrier after fresh status reads while registration retains
    /// the physical parent writer. No production build exposes this hook.
    #[cfg(any(test, feature = "test-utils"))]
    pub fn pause_child_wait_registration_after_status_read(
        &self,
    ) -> (Arc<tokio::sync::Barrier>, Arc<tokio::sync::Barrier>) {
        let entered = Arc::new(tokio::sync::Barrier::new(2));
        let release = Arc::new(tokio::sync::Barrier::new(2));
        *self.child_wait_registration_pause.lock().unwrap() =
            Some((entered.clone(), release.clone()));
        (entered, release)
    }

    async fn child_wait_guards(&self, id: &str) -> io::Result<Arc<DefaultWriterGuards>> {
        validate_session_id(id)?;
        let lifecycle = self.lock_default_writer_lifecycle().await?;
        let task = self.lock_runtime_task_sidecar_shared().await?;
        let session = self
            .acquire_session_write_lock(id, SaveKind::Runtime)
            .await?;
        Ok(DefaultWriterGuards::shared(lifecycle, task, session))
    }

    /// Read the canonical owned child path without an instance index. Check
    /// durable linkage before loading any full transcript.
    pub(super) async fn load_child_wait_session(
        &self,
        parent: &Session,
        id: &str,
        full: bool,
    ) -> io::Result<Option<Session>> {
        validate_session_id(id)?;
        let root = if parent.kind == SessionKind::Root {
            &parent.id
        } else {
            &parent.root_session_id
        };
        validate_session_id(&parent.id)?;
        validate_session_id(root)?;
        let directory = self.abs_path_from_rel(&Self::child_rel_path(root, id));
        let side = Self::read_runtime_sidecar_at(&directory.join(RUNTIME_SIDECAR_FILE), id).await?;
        let Some(side) = side else {
            // Ordinary compatibility: legacy Child Main remains authoritative
            // when its optional sidecar is missing or corrupt.
            let bytes = match fs::read(directory.join("session.json")).await {
                Ok(bytes) => bytes,
                Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
                Err(error) => return Err(error),
            };
            compact_main::validate_full_main(&bytes)?;
            let main: Session = serde_json::from_slice(&bytes)
                .map_err(|error| other_io_error(error.to_string()))?;
            supervisor::validate_identity(&main)?;
            self.validate_root_tool_authority_overlay(id, &main, None)
                .await?;
            if main.id != id
                || main.kind != SessionKind::Child
                || main.parent_session_id.as_deref() != Some(&parent.id)
                || main.root_session_id != *root
                || !self.session_lifetime_is_live(&main).await?
            {
                return Ok(None);
            }
            return Ok(Some(if full {
                main
            } else {
                runtime_sidecar_snapshot(&main)
            }));
        };
        if side.id != id
            || side.kind != SessionKind::Child
            || side.parent_session_id.as_deref() != Some(&parent.id)
            || side.root_session_id != *root
            || !self.session_lifetime_is_live(&side).await?
        {
            return Ok(None);
        }
        if !full {
            return Ok(Some(side));
        }
        let bytes = match fs::read(directory.join("session.json")).await {
            Ok(bytes) => bytes,
            Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(error) => return Err(error),
        };
        compact_main::validate_full_main(&bytes)?;
        let main: Session =
            serde_json::from_slice(&bytes).map_err(|error| other_io_error(error.to_string()))?;
        if main.id != side.id
            || main.created_at != side.created_at
            || main.parent_session_id != side.parent_session_id
            || main.root_session_id != side.root_session_id
            || main.kind != side.kind
            || main.spawn_depth != side.spawn_depth
        {
            return Err(io::Error::new(
                io::ErrorKind::WouldBlock,
                bamboo_domain::SessionAuthorityConflict("child wait canonical pair changed".into()),
            ));
        }
        supervisor::validate_overlay(&main, Some(&side))?;
        self.validate_root_tool_authority_overlay(id, &main, Some(&side))
            .await?;
        if !self.session_lifetime_is_live(&main).await? {
            return Ok(None);
        }
        Ok(Some(overlay_runtime_sidecar(main, Some(side))))
    }

    async fn child_wait_terminal_status(
        &self,
        parent: &Session,
        id: &str,
    ) -> io::Result<Option<String>> {
        Ok(self
            .load_child_wait_session(parent, id, false)
            .await?
            .and_then(|child| child.last_run_status())
            .filter(|status| terminal(status)))
    }

    async fn publish_child_wait(
        &self,
        guards: &Arc<DefaultWriterGuards>,
        committed: &Session,
        publish: RootActorRuntimePublisher,
    ) -> io::Result<()> {
        let snapshot = committed.clone();
        Self::default_writer_job(guards, move || {
            publish(&snapshot);
            Ok(())
        })
        .await
    }

    pub(super) async fn register_child_wait(
        &self,
        expected: &Session,
        batch: &[(String, Option<String>)],
        policy: ChildWaitPolicy,
        check_terminal: bool,
        publish: RootActorRuntimePublisher,
    ) -> io::Result<(Session, usize)> {
        let started = Instant::now();
        let guards = self.child_wait_guards(&expected.id).await?;
        let mut latest = self
            .load_runtime_control_plane_unchecked(&expected.id)
            .await?
            .ok_or_else(|| {
                io::Error::new(io::ErrorKind::NotFound, "child wait parent disappeared")
            })?;
        validate_incarnation(expected, &latest)?;
        let mut pending = Vec::new();
        let mut satisfied = false;
        for entry in batch {
            if !check_terminal {
                // A synchronous launch owns a new run that has not reached
                // enqueue yet. Its predecessor's terminal status is irrelevant.
                pending.push(entry.clone());
                continue;
            }
            match self.child_wait_terminal_status(&latest, &entry.0).await? {
                Some(status) => {
                    satisfied |= policy == ChildWaitPolicy::Any
                        || (policy == ChildWaitPolicy::FirstError
                            && matches!(status.as_str(), "error" | "timeout" | "cancelled"));
                }
                None => pending.push(entry.clone()),
            }
        }
        #[cfg(any(test, feature = "test-utils"))]
        {
            let pause = self.child_wait_registration_pause.lock().unwrap().take();
            if let Some((entered, release)) = pause {
                entered.wait().await;
                release.wait().await;
            }
        }
        if satisfied || pending.is_empty() {
            self.publish_child_wait(&guards, &latest, publish).await?;
            return Ok((latest, 0));
        }
        let count = pending.len();
        register_pending(&mut latest, pending, policy)?;
        let rel = Self::default_writer_rel_path(&latest)?;
        self.save_runtime_state_after_lock(&latest, &rel, started, &guards, None, None)
            .await?;
        self.publish_child_wait(&guards, &latest, publish).await?;
        Ok((latest, count))
    }

    pub(super) async fn compare_exchange_child_wait(
        &self,
        expected: &Session,
        updated: &mut Session,
        runtime_only: bool,
        publish: RootActorRuntimePublisher,
    ) -> io::Result<bool> {
        let started = Instant::now();
        let guards = self.child_wait_guards(&expected.id).await?;
        let latest = if runtime_only {
            self.load_runtime_control_plane_unchecked(&expected.id)
                .await?
        } else {
            self.load_session_unlocked(&expected.id).await?
        }
        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "child wait parent disappeared"))?;
        validate_incarnation(expected, &latest)?;
        validate_incarnation(expected, updated)?;
        let state = runtime(&latest);
        if state.waiting_for_children != runtime(expected).waiting_for_children {
            return Ok(false);
        }
        if is_observation(expected, updated) {
            *updated = latest;
            return Ok(true);
        }
        let mut committed = latest;
        apply_transition(&mut committed, expected, updated, runtime_only)?;
        if runtime_only {
            let rel = Self::default_writer_rel_path(&committed)?;
            self.save_runtime_state_after_lock(&committed, &rel, started, &guards, None, None)
                .await?;
        } else {
            self.save_session_after_lock(&committed, started, &guards, None)
                .await?;
        }
        self.publish_child_wait(&guards, &committed, publish)
            .await?;
        *updated = committed;
        Ok(true)
    }
}