made-core 0.5.0

Domain core of MADE: entities, value objects, events, ports. No IO.
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
//! Conformance suite for [`MemoryWriterPort`] and [`MemoryReaderPort`].
//!
//! Memory is the one port where an adapter can look like it works and
//! not: a backend that silently drops writes answers every read with
//! nothing, and nothing is exactly what an empty scope looks like. The
//! properties here are written to tell those two apart.
//!
//! The suite is capability-driven on purpose. A backend that declares
//! nothing is legitimate — it is the honest shape of "no memory
//! configured" — so what is checked is not that a backend does
//! everything, but that **it does what it says it does**. Claiming a
//! capability and not having it is the failure; having less than
//! everything is not.
//!
//! # What this suite cannot check
//!
//! **Whether the memory is any good.** That entries are stored and
//! come back says nothing about whether a later session can navigate
//! them. Quality is the backend's to measure, not this suite's.
//!
//! **Survival.** An in-process backend loses everything on restart, so
//! no property runnable against every implementation could assert it.

use crate::conformance::MemoryConformanceFailure;
use crate::ports::{MemoryReaderPort, MemoryWriteOutcome, MemoryWriterPort};
use crate::value_objects::{
    Attributes, MemoryConfidence, MemoryEntryKind, MemoryEvidence, MemoryMoment, MemoryRelation,
    MemoryRelationKind, MemoryWrite,
};

mod support;

use support::{entry, expect_unsupported, moment, named, scope, write, Checked};

/// Every property a memory adapter must satisfy.
///
/// Nine of them. The tenth asked whether a backend answered a question
/// put in words; the port no longer has that method, because nothing in
/// this engine ever asked one (ADR-013, E2).
#[derive(Debug)]
pub struct MemoryConformance;

impl MemoryConformance {
    /// Run the whole suite, returning the properties that passed.
    ///
    /// The adapter must be empty. Each property uses its own scope, so
    /// a shared backend is fine as long as nothing else writes to
    /// those scopes while the suite runs.
    pub async fn run(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Result<Vec<&'static str>, MemoryConformanceFailure> {
        let mut passed = Vec::new();

        Self::capabilities_are_stable(writer, reader)?;
        passed.push("capabilities_are_stable");

        Self::an_unwritten_scope_recalls_nothing(reader).await?;
        passed.push("an_unwritten_scope_recalls_nothing");

        Self::what_is_remembered_can_be_recalled(writer, reader).await?;
        passed.push("what_is_remembered_can_be_recalled");

        Self::scopes_do_not_bleed_into_each_other(writer, reader).await?;
        passed.push("scopes_do_not_bleed_into_each_other");

        Self::the_same_write_twice_is_one_memory(writer, reader).await?;
        passed.push("the_same_write_twice_is_one_memory");

        Self::reasons_survive_the_round_trip(writer, reader).await?;
        passed.push("reasons_survive_the_round_trip");

        Self::a_chain_of_reasons_can_be_followed(writer, reader).await?;
        passed.push("a_chain_of_reasons_can_be_followed");

        Self::evidence_survives_the_round_trip(writer, reader).await?;
        passed.push("evidence_survives_the_round_trip");

        Self::time_travel_is_honoured_or_declined(writer, reader).await?;
        passed.push("time_travel_is_honoured_or_declined");

        Ok(passed)
    }

    async fn an_unwritten_scope_recalls_nothing(reader: &dyn MemoryReaderPort) -> Checked {
        const PROPERTY: &str = "an_unwritten_scope_recalls_nothing";
        let recollection = reader
            .recall(&scope("unwritten"))
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !reader.capabilities().recalls() {
            return expect_unsupported(PROPERTY, &recollection, "recall");
        }
        if recollection.entries().is_empty() {
            Ok(())
        } else {
            Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!(
                    "a scope nobody wrote to came back with {} entries",
                    recollection.entries().len()
                ),
            ))
        }
    }

    /// The property that tells a working backend from one that drops
    /// writes: both answer an empty scope with nothing, and only one
    /// answers a written scope with something.
    async fn what_is_remembered_can_be_recalled(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "what_is_remembered_can_be_recalled";
        let scope = scope("round-trip");
        let outcome = writer
            .remember(
                &scope,
                write(vec![entry(
                    "the rollback was rehearsed in March",
                    MemoryEntryKind::Observation,
                    moment(10),
                )]),
                "conformance:round-trip",
            )
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !writer.capabilities().remembers() {
            return if outcome == MemoryWriteOutcome::NotRemembered {
                Ok(())
            } else {
                Err(MemoryConformanceFailure::new(
                    PROPERTY,
                    format!("a backend that does not remember answered {outcome:?}"),
                ))
            };
        }
        if outcome != MemoryWriteOutcome::Remembered {
            return Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!("a first write answered {outcome:?}"),
            ));
        }
        if !reader.capabilities().recalls() {
            return Ok(());
        }

        let recalled = reader
            .recall(&scope)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        match recalled.entries() {
            [only] if only.summary() == "the rollback was rehearsed in March" => Ok(()),
            [] => Err(MemoryConformanceFailure::new(
                PROPERTY,
                "what was written came back as nothing — a dropped write and an empty scope must not look the same",
            )),
            others => Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!("expected exactly what was written, got {} entries", others.len()),
            )),
        }
    }

    async fn scopes_do_not_bleed_into_each_other(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "scopes_do_not_bleed_into_each_other";
        if !writer.capabilities().remembers() || !reader.capabilities().recalls() {
            return Ok(());
        }
        let mine = scope("mine");
        let yours = scope("yours");
        writer
            .remember(
                &mine,
                write(vec![entry("mine", MemoryEntryKind::Decision, moment(1))]),
                "conformance:mine",
            )
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        writer
            .remember(
                &yours,
                write(vec![entry("yours", MemoryEntryKind::Decision, moment(2))]),
                "conformance:yours",
            )
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        let recalled = reader
            .recall(&mine)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        if recalled.entries().iter().any(|e| e.summary() == "yours") {
            return Err(MemoryConformanceFailure::new(
                PROPERTY,
                "one scope's memory surfaced in another's",
            ));
        }
        Ok(())
    }

    /// A retry must not double the memory, and must say which of the
    /// two happened. Answering "remembered" to both makes a caller
    /// unable to tell a successful retry from a write it never sent.
    async fn the_same_write_twice_is_one_memory(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "the_same_write_twice_is_one_memory";
        if !writer.capabilities().remembers() {
            return Ok(());
        }
        let scope = scope("retried");
        let entries = || {
            write(vec![entry(
                "decided once",
                MemoryEntryKind::Decision,
                moment(5),
            )])
        };

        let first = writer
            .remember(&scope, entries(), "conformance:retried")
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        let second = writer
            .remember(&scope, entries(), "conformance:retried")
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if first != MemoryWriteOutcome::Remembered {
            return Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!("a first write answered {first:?}"),
            ));
        }
        if second != MemoryWriteOutcome::AlreadyRemembered {
            return Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!("the same write repeated answered {second:?}, not AlreadyRemembered"),
            ));
        }
        if !reader.capabilities().recalls() {
            return Ok(());
        }
        let recalled = reader
            .recall(&scope)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        if recalled.entries().len() == 1 {
            Ok(())
        } else {
            Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!(
                    "one write made twice left {} entries",
                    recalled.entries().len()
                ),
            ))
        }
    }

    /// The reasons are the part a later session follows, and a backend
    /// that keeps the entries while dropping the edges leaves memory
    /// that reads correctly and cannot be walked.
    ///
    /// That is the failure this property exists for, and it is the one
    /// that looks most like success: every entry is there, every
    /// summary is right, and the question "how did this come about"
    /// has quietly stopped having an answer.
    async fn reasons_survive_the_round_trip(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "reasons_survive_the_round_trip";
        const WHY: &str = "the queue growth is what made a rollback necessary";
        let scope = scope("reasons");
        let observation = named(
            "conformance:observation",
            "the queue was backing up",
            MemoryEntryKind::Observation,
            moment(40),
        );
        let decision = named(
            "conformance:decision",
            "roll back rather than restart",
            MemoryEntryKind::Decision,
            moment(50),
        );
        let because = MemoryRelation::new(
            decision.id().clone(),
            observation.id().clone(),
            MemoryRelationKind::ChosenBecause,
            WHY,
            MemoryConfidence::High,
        )
        .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        let explained = MemoryWrite::new(vec![observation, decision], vec![because])
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        // Accepting a reason is not the same as keeping one: a backend
        // that keeps none must still take the write, or a caller would
        // have to choose between explaining itself and being stored.
        let outcome = writer
            .remember(&scope, explained, "conformance:reasons")
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !writer.capabilities().remembers() {
            return if outcome == MemoryWriteOutcome::NotRemembered {
                Ok(())
            } else {
                Err(MemoryConformanceFailure::new(
                    PROPERTY,
                    format!("a backend that does not remember answered {outcome:?}"),
                ))
            };
        }
        if !writer.capabilities().keeps_reasons() || !reader.capabilities().recalls() {
            return Ok(());
        }

        let recalled = reader
            .recall(&scope)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        match recalled.relations() {
            [only] if only.why() == WHY && only.kind() == MemoryRelationKind::ChosenBecause => {
                if only.from().as_str() == "conformance:decision"
                    && only.to().as_str() == "conformance:observation"
                {
                    Ok(())
                } else {
                    Err(MemoryConformanceFailure::new(
                        PROPERTY,
                        format!(
                            "a reason came back pointing {} -> {}",
                            only.from(),
                            only.to()
                        ),
                    ))
                }
            }
            [] => Err(MemoryConformanceFailure::new(
                PROPERTY,
                "the entries came back and the reason between them did not — \
                 memory that can be read and not followed",
            )),
            others => Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!("expected exactly the reason written, got {}", others.len()),
            )),
        }
    }

    /// Two hops, because one proves nothing.
    ///
    /// A backend that returned the single edge it was handed would pass
    /// a one-hop check while being unable to follow anything. The
    /// question a later session actually asks — how did this outcome
    /// come from that observation — is never one hop.
    async fn a_chain_of_reasons_can_be_followed(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "a_chain_of_reasons_can_be_followed";
        let scope = scope("chain");
        let observation = named(
            "chain:observation",
            "the queue was backing up",
            MemoryEntryKind::Observation,
            moment(60),
        );
        let decision = named(
            "chain:decision",
            "roll back rather than restart",
            MemoryEntryKind::Decision,
            moment(70),
        );
        let outcome = named(
            "chain:outcome",
            "the queue drained",
            MemoryEntryKind::Outcome,
            moment(80),
        );
        let chain = vec![
            MemoryRelation::new(
                decision.id().clone(),
                observation.id().clone(),
                MemoryRelationKind::ChosenBecause,
                "the queue growth is what made a rollback necessary",
                MemoryConfidence::High,
            )
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?,
            MemoryRelation::new(
                outcome.id().clone(),
                decision.id().clone(),
                MemoryRelationKind::FollowsFrom,
                "the queue drained because the rollback removed the bad revision",
                MemoryConfidence::Medium,
            )
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?,
        ];
        let from = outcome.id().clone();
        let to = observation.id().clone();

        if writer.capabilities().remembers() {
            let explained = MemoryWrite::new(vec![observation, decision, outcome], chain)
                .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
            writer
                .remember(&scope, explained, "conformance:chain")
                .await
                .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        }

        let followed = reader
            .follow(&scope, &from, &to)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !reader.capabilities().follows_reasons() {
            return expect_unsupported(PROPERTY, &followed, "follow");
        }
        if !writer.capabilities().remembers() || !writer.capabilities().keeps_reasons() {
            return Ok(());
        }

        let reached = followed
            .relations()
            .iter()
            .any(|relation| relation.to() == &to);
        if followed.relations().len() >= 2 && reached {
            Ok(())
        } else {
            Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!(
                    "following an outcome back to what it came from returned {} step(s) \
                     and {} the far end — a memory that cannot be walked",
                    followed.relations().len(),
                    if reached { "reached" } else { "never reached" }
                ),
            ))
        }
    }

    async fn evidence_survives_the_round_trip(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "evidence_survives_the_round_trip";
        if !writer.capabilities().keeps_evidence() {
            return Ok(());
        }
        let scope = scope("evidence");
        let evidenced = entry(
            "the queue was empty at 03:20",
            MemoryEntryKind::Observation,
            moment(20),
        )
        .with_evidence(vec![MemoryEvidence::new(
            "dead-letter count",
            Some("dead-letter-queue".to_owned()),
            Attributes::empty(),
        )
        .expect("evidence should be valid")]);

        writer
            .remember(&scope, write(vec![evidenced]), "conformance:evidence")
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !reader.capabilities().recalls() {
            return Ok(());
        }
        let recalled = reader
            .recall(&scope)
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        match recalled.entries().first() {
            Some(entry) if entry.evidence().len() == 1 => Ok(()),
            Some(entry) => Err(MemoryConformanceFailure::new(
                PROPERTY,
                format!(
                    "a backend that keeps evidence returned an entry with {} of it",
                    entry.evidence().len()
                ),
            )),
            None => Err(MemoryConformanceFailure::new(
                PROPERTY,
                "the evidenced entry did not come back at all",
            )),
        }
    }

    async fn time_travel_is_honoured_or_declined(
        writer: &dyn MemoryWriterPort,
        reader: &dyn MemoryReaderPort,
    ) -> Checked {
        const PROPERTY: &str = "time_travel_is_honoured_or_declined";
        let scope = scope("as-known-at");
        if writer.capabilities().remembers() {
            writer
                .remember(
                    &scope,
                    write(vec![
                        entry("known early", MemoryEntryKind::Observation, moment(100)),
                        entry("known later", MemoryEntryKind::Observation, moment(900)),
                    ]),
                    "conformance:as-known-at",
                )
                .await
                .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;
        }

        let recalled = reader
            .as_known_at(&scope, MemoryMoment::at(moment(500)))
            .await
            .map_err(|error| MemoryConformanceFailure::new(PROPERTY, error.to_string()))?;

        if !reader.capabilities().travels_in_time() {
            return expect_unsupported(PROPERTY, &recalled, "as_known_at");
        }
        if !writer.capabilities().remembers() {
            return Ok(());
        }
        if recalled
            .entries()
            .iter()
            .any(|e| e.summary() == "known later")
        {
            return Err(MemoryConformanceFailure::new(
                PROPERTY,
                "reading memory as of a moment returned something learned after it",
            ));
        }
        if recalled
            .entries()
            .iter()
            .any(|e| e.summary() == "known early")
        {
            Ok(())
        } else {
            Err(MemoryConformanceFailure::new(
                PROPERTY,
                "reading memory as of a moment lost what was already known then",
            ))
        }
    }
}