ultron-durable 1.0.0

Pi Durable storage: records, the Storage contract, and the in-memory working copy
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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Port of upstream `test/session-documents.test.ts` ("Session document transactions"), run against every backend.
//! Not ported: tests of callbacks that settle with pending acquisitions, of Tx use after settlement, and of non-JSON
//! values; a synchronous callback, the borrow checker, and `serde_json::Value` make those states unrepresentable.

use crate::session_support;

use chord_delta::path;
use durable::{
    DocDefinition, DocSemantics, DocumentFork, DocumentHistory, Owner, SessionError, StorageError, TaskId, TaskRecord,
    TaskState,
};
use serde_json::{Value, json};
use session_support::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

fn conversation(history: DocumentHistory, fork: DocumentFork) -> DocSemantics {
    DocSemantics::Conversation { history, fork }
}

fn live_value() -> Value {
    json!({ "items": [], "nested": { "count": 0 }, "other": { "label": "x" } })
}

fn live_doc() -> durable::Doc {
    DocDefinition::new(
        "test.live",
        1,
        conversation(DocumentHistory::Latest, DocumentFork::Initial),
        |_| live_value(),
    )
    .define()
    .unwrap()
}

fn counter_doc() -> durable::Doc {
    DocDefinition::new("test.counter", 1, DocSemantics::Session, |_| json!({ "count": 0 }))
        .define()
        .unwrap()
}

fn setup_live(backend: Backend) -> (TestSession, durable::ConversationId) {
    let t = TestSession::open(backend);
    let c = t.create_conversation();
    t.session
        .commit(|tx| {
            let live = tx.doc(&live_doc(), Owner::Conversation(c))?;
            live.push(&path!["items"], vec![json!("a"), json!("b")])?;
            Ok(())
        })
        .unwrap();
    (t, c)
}

fn snapshot(t: &TestSession, doc: &durable::Doc, owner: Owner) -> Option<Arc<Value>> {
    t.session.snapshot(doc, owner).unwrap()
}

#[test]
fn durable_session_documents_create_an_initial_base_on_first_access_and_adopt_it_after_storage_success() {
    each_backend(|backend| {
        let t = TestSession::open(backend);
        let c = t.create_conversation();
        t.session
            .commit(|tx| {
                tx.doc(&live_doc(), Owner::Conversation(c))?
                    .set(&path!["message"], json!("hello"))?;
                Ok(())
            })
            .unwrap();
        let writes = t.storage.last_commit();
        assert_eq!(writes.len(), 1);
        assert_matches(
            &json(&writes[0]),
            json!({
                "type": "document.create",
                "record": {
                    "kind": "test.live",
                    "scope": { "kind": "conversation", "conversationId": c.0 },
                    "history": "latest",
                    "fork": "initial",
                },
                "content": { "kind": "base", "version": 1, "value": { "message": "hello", "items": [], "nested": { "count": 0 }, "other": { "label": "x" } } },
            }),
        );
        let value = snapshot(&t, &live_doc(), Owner::Conversation(c)).unwrap();
        assert_eq!(
            *value,
            json!({ "message": "hello", "items": [], "nested": { "count": 0 }, "other": { "label": "x" } })
        );
        let publication = t.last_publication();
        let published = &document_changes(&publication)[0];
        assert_eq!(published.record.created_at, publication.seq);
        assert!(Arc::ptr_eq(published.value.as_ref().unwrap(), &value));
        assert_eq!(published.conversation_id, Some(c));
    });
}

#[test]
fn durable_session_documents_never_create_on_snapshot() {
    each_backend(|backend| {
        let t = TestSession::open(backend);
        let c = t.create_conversation();
        let before = t.storage.commit_count();
        assert_eq!(snapshot(&t, &live_doc(), Owner::Conversation(c)), None);
        assert_eq!(snapshot(&t, &counter_doc(), Owner::Session), None);
        assert_eq!(t.storage.commit_count(), before);
        assert_eq!(t.storage.mint_count(), 1);
    });
}

#[test]
fn durable_session_documents_return_shared_immutable_snapshots_and_keep_prior_revisions_stable() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let first = snapshot(&t, &live_doc(), owner).unwrap();
        assert!(Arc::ptr_eq(&snapshot(&t, &live_doc(), owner).unwrap(), &first));
        t.session
            .commit(|tx| Ok(tx.doc(&live_doc(), owner)?.set(&path!["nested", "count"], json!(1))?))
            .unwrap();
        let second = snapshot(&t, &live_doc(), owner).unwrap();
        assert!(!Arc::ptr_eq(&second, &first));
        assert_eq!(first["nested"]["count"], 0);
        assert_eq!(second["nested"]["count"], 1);
    });
}

#[test]
fn durable_session_documents_publish_the_adopted_revision_and_the_admitted_ops() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        t.session
            .commit(|tx| {
                let live = tx.doc(&live_doc(), owner)?;
                live.set(&path!["other"], json!({ "label": "y" }))?;
                live.push(&path!["items"], vec![json!("c")])?;
                Ok(())
            })
            .unwrap();
        let value = snapshot(&t, &live_doc(), owner).unwrap();
        let published = document_changes(&t.last_publication()).remove(0);
        assert!(Arc::ptr_eq(published.value.as_ref().unwrap(), &value));
        let admitted = json(&t.storage.last_commit()[0]);
        assert_eq!(admitted["type"], "document.change");
        assert_eq!(admitted["content"]["kind"], "delta");
        assert_eq!(Value::Array(published.ops.clone()), admitted["content"]["ops"]);
        assert_eq!(
            published.ops,
            vec![
                json!(["s", ["other"], { "label": "y" }]),
                json!(["p", ["items"], 2, 0, ["c"]])
            ]
        );
    });
}

#[test]
fn durable_session_documents_suppress_writes_and_publications_for_empty_batches() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let (commits, published) = (t.storage.commit_count(), t.publication_count());
        t.session
            .commit(|tx| {
                let live = tx.doc(&live_doc(), Owner::Conversation(c))?;
                live.set(&path!["nested", "count"], json!(0))?;
                live.push(&path!["items"], vec![json!("z")])?;
                live.pop(&path!["items"])?;
                Ok(())
            })
            .unwrap();
        assert_eq!(t.storage.commit_count(), commits);
        assert_eq!(t.publication_count(), published);
    });
}

#[test]
fn durable_session_documents_write_and_publish_replayable_nonempty_structural_no_ops() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let before = snapshot(&t, &live_doc(), owner).unwrap();
        t.session
            .commit(|tx| {
                let live = tx.doc(&live_doc(), owner)?;
                let first = live.shift(&path!["items"])?.unwrap();
                live.unshift(&path!["items"], vec![first])?;
                Ok(())
            })
            .unwrap();
        assert_matches(
            &json(&t.storage.last_commit()[0]),
            json!({ "type": "document.change", "content": { "kind": "delta" } }),
        );
        let after = snapshot(&t, &live_doc(), owner).unwrap();
        assert_eq!(after, before);
        assert!(!Arc::ptr_eq(&after, &before));
        assert_eq!(
            document_changes(&t.last_publication())[0].ops,
            vec![json!(["p", ["items"], 0, 1, []]), json!(["p", ["items"], 0, 0, ["a"]])]
        );
    });
}

#[test]
fn durable_session_documents_revoke_escaped_drafts_when_the_callback_settles() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let escaped = t
            .session
            .commit(|tx| {
                let live = tx.doc(&live_doc(), owner)?;
                live.set(&path!["message"], json!("inside"))?;
                Ok(live)
            })
            .unwrap();
        assert_eq!(
            escaped.get(&path!["message"]).unwrap_err().to_string(),
            "Cannot use a settled overlay"
        );
        assert!(escaped.set(&path!["message"], json!("outside")).is_err());
        assert!(escaped.get(&path!["items"]).is_err());
        assert!(escaped.push(&path!["items"], vec![json!("outside")]).is_err());
        assert_eq!(snapshot(&t, &live_doc(), owner).unwrap()["message"], "inside");
        let returned = t.session.commit(|tx| tx.doc(&live_doc(), owner)).unwrap();
        assert!(returned.get(&path!["message"]).is_err());
    });
}

#[test]
fn durable_session_documents_abort_every_change_when_the_callback_fails() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let before = snapshot(&t, &live_doc(), owner).unwrap();
        let commits = t.storage.commit_count();
        let error = t
            .session
            .commit(|tx| {
                tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("lost"))?;
                tx.doc(&counter_doc(), Owner::Session)?.set(&path!["count"], json!(5))?;
                Err::<(), _>(SessionError::Error("callback failed".into()))
            })
            .unwrap_err();
        assert_eq!(error.to_string(), "callback failed");
        assert_eq!(t.storage.commit_count(), commits);
        assert!(Arc::ptr_eq(&snapshot(&t, &live_doc(), owner).unwrap(), &before));
        assert_eq!(snapshot(&t, &counter_doc(), Owner::Session), None);
        t.session
            .commit(|tx| Ok(tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("kept"))?))
            .unwrap();
        assert_eq!(snapshot(&t, &live_doc(), owner).unwrap()["message"], "kept");
    });
}

#[test]
fn durable_session_documents_memoize_duplicate_acquisition_and_initialize_once() {
    each_backend(|backend| {
        let t = TestSession::open(backend);
        let c = t.create_conversation();
        let inits = Arc::new(AtomicUsize::new(0));
        let counted = inits.clone();
        let doc = DocDefinition::new(
            "test.live",
            1,
            conversation(DocumentHistory::Latest, DocumentFork::Initial),
            move |_| {
                counted.fetch_add(1, Ordering::SeqCst);
                live_value()
            },
        )
        .define()
        .unwrap();
        let mints = t.storage.mint_count();
        t.session
            .commit(|tx| {
                let first = tx.doc(&doc, Owner::Conversation(c))?;
                let second = tx.doc(&doc, Owner::Conversation(c))?;
                assert!(first.ptr_eq(&second));
                assert!(tx.doc(&doc, Owner::Conversation(c))?.ptr_eq(&first));
                first.set(&path!["message"], json!("once"))?;
                Ok(())
            })
            .unwrap();
        assert_eq!(inits.load(Ordering::SeqCst), 1);
        assert_eq!(t.storage.mint_count(), mints + 1);
        assert_eq!(types(&t.storage.last_commit()), ["document.create"]);
    });
}

#[test]
fn durable_session_documents_reject_definitions_whose_semantics_or_version_disagree_with_storage() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let rewindable = DocDefinition::new(
            "test.live",
            1,
            conversation(DocumentHistory::Rewindable, DocumentFork::AsOf),
            |_| live_value(),
        )
        .define()
        .unwrap();
        let v2 = DocDefinition::new(
            "test.live",
            2,
            conversation(DocumentHistory::Latest, DocumentFork::Initial),
            |_| live_value(),
        )
        .define()
        .unwrap();
        let semantics = t.session.snapshot(&rewindable, owner).unwrap_err();
        assert!(
            semantics
                .to_string()
                .contains("does not match the supplied definition semantics")
        );
        assert_eq!(semantics.name(), "TypeError");
        let error = t.session.commit(|tx| tx.doc(&rewindable, owner).map(drop)).unwrap_err();
        assert!(
            error
                .to_string()
                .contains("does not match the supplied definition semantics")
        );
        let error = t.session.commit(|tx| tx.doc(&v2, owner).map(drop)).unwrap_err();
        assert!(
            error.to_string().contains("requires migration from version 1"),
            "{error}"
        );
    });
}

#[test]
fn durable_session_documents_roll_back_prepared_documents_when_batch_assembly_fails() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        t.session
            .commit(|tx| Ok(tx.doc(&counter_doc(), Owner::Session)?.set(&path!["count"], json!(1))?))
            .unwrap();
        let live = snapshot(&t, &live_doc(), owner).unwrap();
        let counter = snapshot(&t, &counter_doc(), Owner::Session).unwrap();
        let commits = t.storage.commit_count();
        let error = t
            .session
            .commit(|tx| {
                tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("lost"))?;
                tx.doc(&counter_doc(), Owner::Session)?.set(&path!["count"], json!(2))?;
                // Replacing a missing task fails during assembly, after every change was prepared.
                tx.set_task(TaskRecord {
                    id: TaskId(999),
                    conversation_id: c,
                    kind: "missing".into(),
                    version: 1,
                    input: Value::Null,
                    owner: None,
                    background: false,
                    abort_requested: false,
                    abort_reason: None,
                    abandon_on_restart: false,
                    started_at: None,
                    ended_at: None,
                    state: TaskState::Pending {
                        checkpoint: json!({ "phase": "start" }),
                    },
                    memos: None,
                })
            })
            .unwrap_err();
        assert_eq!(error.to_string(), "Task 999 does not exist");
        assert_eq!(t.storage.commit_count(), commits);
        assert!(Arc::ptr_eq(&snapshot(&t, &live_doc(), owner).unwrap(), &live));
        assert!(Arc::ptr_eq(
            &snapshot(&t, &counter_doc(), Owner::Session).unwrap(),
            &counter
        ));
        t.session
            .commit(|tx| {
                tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("next"))?;
                tx.doc(&counter_doc(), Owner::Session)?.set(&path!["count"], json!(3))?;
                Ok(())
            })
            .unwrap();
        assert_eq!(snapshot(&t, &counter_doc(), Owner::Session).unwrap()["count"], 3);
    });
}

#[test]
fn durable_session_documents_fail_the_session_after_a_storage_failure_and_publish_nothing() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let before = snapshot(&t, &live_doc(), owner).unwrap();
        let published = t.publication_count();
        t.storage.fail_next_commit(StorageError::Failed("disk vanished".into()));
        let error = t
            .session
            .commit(|tx| Ok(tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("uncertain"))?))
            .unwrap_err();
        assert_eq!(error.to_string(), "disk vanished");
        assert_eq!(t.publication_count(), published);
        assert_eq!(before.get("message"), None);
        assert_eq!(
            t.session.snapshot(&live_doc(), owner).unwrap_err().name(),
            "SessionFailed"
        );
        let failed = t.session.commit(|_| Ok(())).unwrap_err();
        assert_eq!(failed.name(), "SessionFailed");
        assert_eq!(
            failed.to_string(),
            "Session failed after a storage error; close and reopen it"
        );
        assert_eq!(
            failed,
            SessionError::Failed(Box::new(SessionError::Storage(StorageError::Failed(
                "disk vanished".into()
            ))))
        );
        t.session.close().unwrap();
    });
}

#[test]
fn durable_session_documents_keep_the_previous_revision_unchanged_through_storage_settlement() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let before = snapshot(&t, &live_doc(), owner).unwrap();
        let copy = (*before).clone();
        let gate = t.storage.hold_commits();
        let session = t.session.clone();
        let commit = std::thread::spawn(move || {
            session.commit(|tx| {
                let live = tx.doc(&live_doc(), owner)?;
                live.push(&path!["items"], vec![json!("c")])?;
                live.set(&path!["nested", "count"], json!(9))?;
                Ok(())
            })
        });
        gate.wait_entered();
        assert!(Arc::ptr_eq(&snapshot(&t, &live_doc(), owner).unwrap(), &before));
        assert_eq!(*before, copy);
        gate.release();
        commit.join().unwrap().unwrap();
        assert_eq!(
            snapshot(&t, &live_doc(), owner).unwrap()["items"],
            json!(["a", "b", "c"])
        );
        assert_eq!(*before, copy);
    });
}

#[test]
fn durable_session_documents_deliver_complete_publications_synchronously_after_adoption() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let published = t.publication_count();
        let result = t
            .session
            .commit(|tx| {
                tx.doc(&live_doc(), Owner::Conversation(c))?
                    .set(&path!["message"], json!("m"))?;
                Ok("done")
            })
            .unwrap();
        assert_eq!(result, "done");
        assert_eq!(t.publication_count(), published + 1);
    });
}

#[test]
fn durable_session_documents_publish_close_synchronously_and_support_unsubscription() {
    each_backend(|backend| {
        let t = TestSession::open(backend);
        let calls = Arc::new(std::sync::Mutex::new(Vec::new()));
        let active = calls.clone();
        t.session
            .subscribe_close(move || active.lock().unwrap().push("active"))
            .unwrap();
        let removed = calls.clone();
        let subscription = t
            .session
            .subscribe_close(move || removed.lock().unwrap().push("removed"))
            .unwrap();
        subscription.unsubscribe();
        t.session.close().unwrap();
        assert_eq!(*calls.lock().unwrap(), ["active"]);
    });
}

#[test]
fn durable_session_documents_settle_admitted_commits_before_close_and_reject_later_admission() {
    each_backend(|backend| {
        let (t, c) = setup_live(backend);
        let owner = Owner::Conversation(c);
        let gate = t.storage.hold_commits();
        let admitted = {
            let session = t.session.clone();
            std::thread::spawn(move || {
                session.commit(|tx| Ok(tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("admitted"))?))
            })
        };
        gate.wait_entered();
        let queued = {
            let session = t.session.clone();
            std::thread::spawn(move || {
                session.commit(|tx| Ok(tx.doc(&live_doc(), owner)?.set(&path!["message"], json!("queued"))?))
            })
        };
        let admitted_snapshot = {
            let session = t.session.clone();
            std::thread::spawn(move || session.snapshot(&counter_doc(), Owner::Session))
        };
        // Both are admitted to the line, behind the held commit, before the close begins.
        eventually(|| t.session.line_len() >= 3);
        let closing = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let began = closing.clone();
        t.session
            .subscribe_close(move || began.store(true, Ordering::SeqCst))
            .unwrap();
        let closed = {
            let session = t.session.clone();
            std::thread::spawn(move || session.close())
        };
        eventually(|| closing.load(Ordering::SeqCst));
        assert_eq!(t.session.commit(|_| Ok(())).unwrap_err(), SessionError::Closed);
        assert_eq!(
            t.session.snapshot(&live_doc(), owner).unwrap_err().to_string(),
            "Session is closed"
        );
        gate.release();
        admitted.join().unwrap().unwrap();
        queued.join().unwrap().unwrap();
        assert_eq!(admitted_snapshot.join().unwrap().unwrap(), None);
        closed.join().unwrap().unwrap();
        let address = durable::DocumentAddress {
            kind: "test.live".into(),
            scope: durable::DocumentScope::Conversation { conversation_id: c },
            key: None,
        };
        let stored = durable::Storage::find_document(&t.storage, &address, durable::DocumentPoint::Current);
        assert!(stored.is_err());
        // Both admitted commits reached Storage before it closed.
        let messages: Vec<Value> = t
            .storage
            .commits()
            .iter()
            .rev()
            .take(2)
            .map(|writes| json(&writes[0])["content"]["ops"].clone())
            .collect();
        assert_eq!(
            messages,
            [
                json!([["s", ["message"], "queued"]]),
                json!([["s", ["message"], "admitted"]])
            ]
        );
    });
}