bamboo-storage 2026.10.21

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
434
435
436
437
438
439
440
441
442
//! Exact final-admission authority races against the real file inbox.

use super::*;
use bamboo_domain::{
    Session, SessionMessageKind, Storage, SupervisorManagementMutation as Mutation,
    SupervisorManagementRequest, SupervisorReference,
};
use std::time::Duration;
use tokio::sync::Notify;

async fn fixture() -> (
    tempfile::TempDir,
    Arc<SessionStoreV2>,
    FileSessionInbox,
    SupervisorReference,
) {
    let home = tempfile::tempdir().unwrap();
    let store = Arc::new(
        SessionStoreV2::new(home.path().to_path_buf())
            .await
            .unwrap(),
    );
    let reference: SupervisorReference = (&store
        .get_or_create_default_supervisor("model")
        .await
        .unwrap())
        .into();
    let mut target = Session::new("target", "original-model");
    target.set_project_id_meta("project-a");
    target.metadata_version = 3;
    store.save_session(&target).await.unwrap();
    mutate(
        &store,
        &reference,
        0,
        Mutation::ConfigureProjectScope {
            allowed_projects: ["project-a".parse().unwrap()].into(),
        },
    )
    .await
    .unwrap();
    mutate(
        &store,
        &reference,
        1,
        Mutation::Attach {
            target_session_id: "target".into(),
        },
    )
    .await
    .unwrap();
    let inbox = FileSessionInbox::new(store.clone(), SessionInboxLimits::default());
    (home, store, inbox, reference)
}

async fn mutate(
    store: &SessionStoreV2,
    reference: &SupervisorReference,
    revision: u64,
    mutation: Mutation,
) -> std::io::Result<bamboo_domain::SupervisorManagementReceipt> {
    store
        .mutate_supervisor_management(&SupervisorManagementRequest {
            supervisor: reference.clone(),
            expected_state_revision: revision,
            mutation,
        })
        .await
}

fn envelope(reference: &SupervisorReference) -> SessionMessageEnvelope {
    let mut message = SessionMessageEnvelope::user_input("target", "continue original work");
    message.source = SessionMessageSource::Session {
        session_id: reference.session_id.clone(),
    };
    message.kind = SessionMessageKind::PeerMessage;
    message
}

fn bound_envelope(
    reference: &SupervisorReference,
    target: &bamboo_domain::SupervisorCurrentUserTarget,
) -> SessionMessageEnvelope {
    let mut message = envelope(reference);
    let operation = uuid::Uuid::new_v4().to_string();
    message.id = bamboo_domain::supervisor_current_user_message_id(reference, target, &operation);
    message.correlation_id = Some(operation);
    message
}

#[tokio::test]
async fn supervisor_current_user_followup_rejects_changed_target_but_not_legacy_acl() {
    for change in [
        "detach",
        "scope",
        "project",
        "version",
        "birth",
        "supervisor",
        "damage",
    ] {
        let (_home, store, inbox, reference) = fixture().await;
        let caller = bamboo_domain::SessionCallerReference::from(
            &store
                .load_session(&reference.session_id)
                .await
                .unwrap()
                .unwrap(),
        );
        let target = store
            .inspect_supervisor_current_user_target(&reference, "target")
            .await
            .unwrap();
        let message = bound_envelope(&reference, &target);
        assert!(
            store
                .inspect_supervisor_link(&reference, "target")
                .await
                .unwrap()
                .authorized
        );
        match change {
            "detach" => {
                mutate(
                    &store,
                    &reference,
                    2,
                    Mutation::Detach {
                        target_session_id: "target".into(),
                    },
                )
                .await
                .unwrap();
            }
            "scope" => {
                mutate(
                    &store,
                    &reference,
                    2,
                    Mutation::ConfigureProjectScope {
                        allowed_projects: Default::default(),
                    },
                )
                .await
                .unwrap();
            }
            "project" | "version" => {
                let mut target = store.load_session("target").await.unwrap().unwrap();
                if change == "project" {
                    target.set_project_id_meta("project-b");
                }
                target.metadata_version += 1;
                store.save_session(&target).await.unwrap();
            }
            "birth" => {
                let original = store.load_session("target").await.unwrap().unwrap();
                store.delete_session("target").await.unwrap();
                let mut target = store
                    .recreate_root_session("target", "new-model")
                    .await
                    .unwrap();
                target.set_project_id_meta("project-a");
                target.metadata_version += 1;
                store.save_session(&target).await.unwrap();
                // Restore the old numeric fence only after the fresh Root's
                // Project mutation has followed its canonical next-revision CAS.
                target.metadata_version = original.metadata_version;
                assert_ne!(target.created_at, original.created_at);
                store.save_session(&target).await.unwrap();
            }
            "supervisor" => {
                store.delete_session(&reference.session_id).await.unwrap();
                store
                    .get_or_create_default_supervisor("replacement")
                    .await
                    .unwrap();
            }
            "damage" => {
                tokio::fs::write(
                    store.sessions_root_dir().join("target/runtime.json"),
                    b"broken",
                )
                .await
                .unwrap();
            }
            _ => unreachable!(),
        }
        let delivered = inbox
            .deliver_supervisor_current_user_followup(&caller, &reference, &target, &message)
            .await;
        let legacy_only = matches!(change, "detach" | "scope");
        assert_eq!(delivered.is_ok(), legacy_only, "{change}: {delivered:?}");
        assert_eq!(
            tokio::fs::try_exists(store.sessions_root_dir().join("target/inbox/generation"))
                .await
                .unwrap(),
            legacy_only,
            "{change}"
        );
    }
}

#[tokio::test]
async fn supervisor_followup_retains_relationship_and_project_locks_until_receipt() {
    for change in ["detach", "scope", "project", "version"] {
        let (home, store, mut inbox, reference) = fixture().await;
        let independent = Arc::new(
            SessionStoreV2::new(home.path().to_path_buf())
                .await
                .unwrap(),
        );
        let target_for_mutation = independent.load_session("target").await.unwrap().unwrap();
        let caller = bamboo_domain::SessionCallerReference::from(
            &store
                .load_session(&reference.session_id)
                .await
                .unwrap()
                .unwrap(),
        );
        let target = store
            .inspect_supervisor_current_user_target(&reference, "target")
            .await
            .unwrap();
        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        inbox.followup_authority_pause = Some((entered.clone(), release.clone()));
        let message = bound_envelope(&reference, &target);
        let pending_inbox = inbox.clone();
        let pending_ref = reference.clone();
        let pending_message = message.clone();
        let pending_caller = caller.clone();
        let pending_target = target.clone();
        let delivery = tokio::spawn(async move {
            pending_inbox
                .deliver_supervisor_current_user_followup(
                    &pending_caller,
                    &pending_ref,
                    &pending_target,
                    &pending_message,
                )
                .await
        });
        entered.notified().await;
        let mutation_ref = reference.clone();
        let mutation = async move {
            match change {
                "detach" => {
                    mutate(
                        &independent,
                        &mutation_ref,
                        2,
                        Mutation::Detach {
                            target_session_id: "target".into(),
                        },
                    )
                    .await
                    .unwrap();
                }
                "scope" => {
                    mutate(
                        &independent,
                        &mutation_ref,
                        2,
                        Mutation::ConfigureProjectScope {
                            allowed_projects: Default::default(),
                        },
                    )
                    .await
                    .unwrap();
                }
                "project" | "version" => {
                    let mut target = target_for_mutation;
                    if change == "project" {
                        target.set_project_id_meta("project-b");
                    }
                    target.metadata_version += 1;
                    independent.save_session(&target).await.unwrap();
                }
                _ => unreachable!(),
            }
        };
        tokio::pin!(mutation);
        // Poll the actual mutation until it has yielded to a held authority
        // lock before allowing the inbox writer to issue its receipt.
        std::future::poll_fn(|cx| {
            use std::future::Future;
            assert!(mutation.as_mut().poll(cx).is_pending(), "{change}");
            std::task::Poll::Ready(())
        })
        .await;
        release.notify_one();
        let receipt = tokio::time::timeout(Duration::from_secs(3), delivery)
            .await
            .unwrap()
            .unwrap()
            .unwrap();
        mutation.await;
        assert_eq!(receipt.generation, 1);
        assert_eq!(inbox.inspect("target").await.unwrap().pending, 1);
        // A later invocation must revalidate even when an exact receipt already exists.
        inbox.followup_authority_pause = None;
        let replay = inbox
            .deliver_supervisor_current_user_followup(&caller, &reference, &target, &message)
            .await;
        if matches!(change, "detach" | "scope") {
            assert_eq!(replay.unwrap().generation, receipt.generation);
        } else {
            assert!(replay.is_err());
        }
        assert!(
            store
                .inspect_supervisor_link(&reference, "target")
                .await
                .unwrap()
                .authorized
        );
    }
}

#[tokio::test]
async fn supervisor_followup_held_lifecycle_does_not_reenter_behind_a_waiting_writer() {
    let (_home, store, mut inbox, reference) = fixture().await;
    let entered = Arc::new(Notify::new());
    let release = Arc::new(Notify::new());
    inbox.followup_authority_pause = Some((entered.clone(), release.clone()));
    let message = envelope(&reference);
    let target_birth = store
        .load_session("target")
        .await
        .unwrap()
        .unwrap()
        .created_at;
    let delivery = tokio::spawn(async move {
        inbox
            .deliver_supervisor_followup(&reference, target_birth, &message)
            .await
    });
    entered.notified().await;
    // delete_session_recursive reaches the exclusive lifecycle acquisition first.
    // Polling once registers its waiting writer before letting admission resume.
    let mut deleting = std::pin::pin!(store.delete_session_recursive("target", true));
    std::future::poll_fn(|cx| {
        use std::future::Future;
        assert!(deleting.as_mut().poll(cx).is_pending());
        std::task::Poll::Ready(())
    })
    .await;
    release.notify_one();
    let receipt = tokio::time::timeout(Duration::from_secs(3), delivery)
        .await
        .expect("held-lifecycle admission must not deadlock behind writer")
        .unwrap()
        .unwrap();
    assert_eq!(receipt.generation, 1);
    assert!(tokio::time::timeout(Duration::from_secs(3), deleting)
        .await
        .unwrap()
        .unwrap());
}

#[tokio::test]
async fn supervisor_observed_followup_rejects_old_birth_after_reopen() {
    let (home, store, inbox, reference) = fixture().await;
    let caller = bamboo_domain::SessionCallerReference::from(
        &store
            .load_session(&reference.session_id)
            .await
            .unwrap()
            .unwrap(),
    );
    let birth = store
        .load_session("target")
        .await
        .unwrap()
        .unwrap()
        .created_at;
    let message = envelope(&reference);
    let first = inbox
        .deliver_unscoped_supervisor_followup(&caller, &reference, birth, &message)
        .await
        .unwrap();
    assert_eq!(first.generation, 1);
    store.delete_session("target").await.unwrap();
    store
        .recreate_root_session("target", "replacement")
        .await
        .unwrap();

    // A reopened adapter has neither the old Inbox receipt nor an in-memory
    // operation map. The original caller's birth still fences the new target.
    let reopened = Arc::new(
        SessionStoreV2::new(home.path().to_path_buf())
            .await
            .unwrap(),
    );
    let fresh_inbox = FileSessionInbox::new(reopened, SessionInboxLimits::default());
    let before = fresh_inbox.inspect("target").await.unwrap();
    assert_eq!(before.generation, 0);
    let error = fresh_inbox
        .deliver_unscoped_supervisor_followup(&caller, &reference, birth, &message)
        .await
        .unwrap_err();
    assert!(
        error.to_string().contains("target lifetime changed"),
        "{error}"
    );
    let after = fresh_inbox.inspect("target").await.unwrap();
    assert_eq!(after.generation, before.generation);
    assert_eq!(after.pending, before.pending);
}

#[tokio::test]
async fn supervisor_followup_cannot_impersonate_user_runtime_or_another_session() {
    let (_home, store, inbox, reference) = fixture().await;
    let target_birth = store
        .load_session("target")
        .await
        .unwrap()
        .unwrap()
        .created_at;
    let mut user = SessionMessageEnvelope::user_input("target", "not a peer");
    assert!(inbox
        .deliver_supervisor_followup(&reference, target_birth, &user)
        .await
        .is_err());
    user.source = SessionMessageSource::Session {
        session_id: "other".into(),
    };
    user.kind = SessionMessageKind::PeerMessage;
    assert!(inbox
        .deliver_supervisor_followup(&reference, target_birth, &user)
        .await
        .is_err());
    user.source = SessionMessageSource::Runtime {
        subsystem: "supervisor".into(),
    };
    assert!(inbox
        .deliver_supervisor_followup(&reference, target_birth, &user)
        .await
        .is_err());
    assert_eq!(inbox.inspect("target").await.unwrap().generation, 0);
}